• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *               2000,2005 Wim Taymans <wim@fluendo.com>
4  *
5  * gstbasesrc.c:
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22 
23 /**
24  * SECTION:gstbasesrc
25  * @title: GstBaseSrc
26  * @short_description: Base class for getrange based source elements
27  * @see_also: #GstPushSrc, #GstBaseTransform, #GstBaseSink
28  *
29  * This is a generic base class for source elements. The following
30  * types of sources are supported:
31  *
32  *   * random access sources like files
33  *   * seekable sources
34  *   * live sources
35  *
36  * The source can be configured to operate in any #GstFormat with the
37  * gst_base_src_set_format() method. The currently set format determines
38  * the format of the internal #GstSegment and any %GST_EVENT_SEGMENT
39  * events. The default format for #GstBaseSrc is %GST_FORMAT_BYTES.
40  *
41  * #GstBaseSrc always supports push mode scheduling. If the following
42  * conditions are met, it also supports pull mode scheduling:
43  *
44  *   * The format is set to %GST_FORMAT_BYTES (default).
45  *   * #GstBaseSrcClass::is_seekable returns %TRUE.
46  *
47  * If all the conditions are met for operating in pull mode, #GstBaseSrc is
48  * automatically seekable in push mode as well. The following conditions must
49  * be met to make the element seekable in push mode when the format is not
50  * %GST_FORMAT_BYTES:
51  *
52  * * #GstBaseSrcClass::is_seekable returns %TRUE.
53  * * #GstBaseSrcClass::query can convert all supported seek formats to the
54  *   internal format as set with gst_base_src_set_format().
55  * * #GstBaseSrcClass::do_seek is implemented, performs the seek and returns
56  *    %TRUE.
57  *
58  * When the element does not meet the requirements to operate in pull mode, the
59  * offset and length in the #GstBaseSrcClass::create method should be ignored.
60  * It is recommended to subclass #GstPushSrc instead, in this situation. If the
61  * element can operate in pull mode but only with specific offsets and
62  * lengths, it is allowed to generate an error when the wrong values are passed
63  * to the #GstBaseSrcClass::create function.
64  *
65  * #GstBaseSrc has support for live sources. Live sources are sources that when
66  * paused discard data, such as audio or video capture devices. A typical live
67  * source also produces data at a fixed rate and thus provides a clock to publish
68  * this rate.
69  * Use gst_base_src_set_live() to activate the live source mode.
70  *
71  * A live source does not produce data in the PAUSED state. This means that the
72  * #GstBaseSrcClass::create method will not be called in PAUSED but only in
73  * PLAYING. To signal the pipeline that the element will not produce data, the
74  * return value from the READY to PAUSED state will be
75  * %GST_STATE_CHANGE_NO_PREROLL.
76  *
77  * A typical live source will timestamp the buffers it creates with the
78  * current running time of the pipeline. This is one reason why a live source
79  * can only produce data in the PLAYING state, when the clock is actually
80  * distributed and running.
81  *
82  * Live sources that synchronize and block on the clock (an audio source, for
83  * example) can use gst_base_src_wait_playing() when the
84  * #GstBaseSrcClass::create function was interrupted by a state change to
85  * PAUSED.
86  *
87  * The #GstBaseSrcClass::get_times method can be used to implement pseudo-live
88  * sources. It only makes sense to implement the #GstBaseSrcClass::get_times
89  * function if the source is a live source. The #GstBaseSrcClass::get_times
90  * function should return timestamps starting from 0, as if it were a non-live
91  * source. The base class will make sure that the timestamps are transformed
92  * into the current running_time. The base source will then wait for the
93  * calculated running_time before pushing out the buffer.
94  *
95  * For live sources, the base class will by default report a latency of 0.
96  * For pseudo live sources, the base class will by default measure the difference
97  * between the first buffer timestamp and the start time of get_times and will
98  * report this value as the latency.
99  * Subclasses should override the query function when this behaviour is not
100  * acceptable.
101  *
102  * There is only support in #GstBaseSrc for exactly one source pad, which
103  * should be named "src". A source implementation (subclass of #GstBaseSrc)
104  * should install a pad template in its class_init function, like so:
105  * |[<!-- language="C" -->
106  * static void
107  * my_element_class_init (GstMyElementClass *klass)
108  * {
109  *   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
110  *   // srctemplate should be a #GstStaticPadTemplate with direction
111  *   // %GST_PAD_SRC and name "src"
112  *   gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
113  *
114  *   gst_element_class_set_static_metadata (gstelement_class,
115  *      "Source name",
116  *      "Source",
117  *      "My Source element",
118  *      "The author <my.sink@my.email>");
119  * }
120  * ]|
121  *
122  * ## Controlled shutdown of live sources in applications
123  *
124  * Applications that record from a live source may want to stop recording
125  * in a controlled way, so that the recording is stopped, but the data
126  * already in the pipeline is processed to the end (remember that many live
127  * sources would go on recording forever otherwise). For that to happen the
128  * application needs to make the source stop recording and send an EOS
129  * event down the pipeline. The application would then wait for an
130  * EOS message posted on the pipeline's bus to know when all data has
131  * been processed and the pipeline can safely be stopped.
132  *
133  * An application may send an EOS event to a source element to make it
134  * perform the EOS logic (send EOS event downstream or post a
135  * %GST_MESSAGE_SEGMENT_DONE on the bus). This can typically be done
136  * with the gst_element_send_event() function on the element or its parent bin.
137  *
138  * After the EOS has been sent to the element, the application should wait for
139  * an EOS message to be posted on the pipeline's bus. Once this EOS message is
140  * received, it may safely shut down the entire pipeline.
141  *
142  */
143 
144 #ifdef HAVE_CONFIG_H
145 #  include "config.h"
146 #endif
147 
148 #include <stdlib.h>
149 #include <string.h>
150 
151 #include <gst/gst_private.h>
152 #include <gst/glib-compat-private.h>
153 
154 #include "gstbasesrc.h"
155 #include <gst/gst-i18n-lib.h>
156 #ifdef OHOS_OPT_PERFORMANCE
157 // ohos.opt.performance.0005
158 // add trace
159 #include "gst_trace.h"
160 #endif
161 
162 GST_DEBUG_CATEGORY_STATIC (gst_base_src_debug);
163 #define GST_CAT_DEFAULT gst_base_src_debug
164 
165 #define GST_LIVE_GET_LOCK(elem)               (&GST_BASE_SRC_CAST(elem)->live_lock)
166 #define GST_LIVE_LOCK(elem)                   g_mutex_lock(GST_LIVE_GET_LOCK(elem))
167 #define GST_LIVE_TRYLOCK(elem)                g_mutex_trylock(GST_LIVE_GET_LOCK(elem))
168 #define GST_LIVE_UNLOCK(elem)                 g_mutex_unlock(GST_LIVE_GET_LOCK(elem))
169 #define GST_LIVE_GET_COND(elem)               (&GST_BASE_SRC_CAST(elem)->live_cond)
170 #define GST_LIVE_WAIT(elem)                   g_cond_wait (GST_LIVE_GET_COND (elem), GST_LIVE_GET_LOCK (elem))
171 #define GST_LIVE_WAIT_UNTIL(elem, end_time)   g_cond_timed_wait (GST_LIVE_GET_COND (elem), GST_LIVE_GET_LOCK (elem), end_time)
172 #define GST_LIVE_SIGNAL(elem)                 g_cond_signal (GST_LIVE_GET_COND (elem));
173 #define GST_LIVE_BROADCAST(elem)              g_cond_broadcast (GST_LIVE_GET_COND (elem));
174 
175 
176 #define GST_ASYNC_GET_COND(elem)              (&GST_BASE_SRC_CAST(elem)->priv->async_cond)
177 #define GST_ASYNC_WAIT(elem)                  g_cond_wait (GST_ASYNC_GET_COND (elem), GST_OBJECT_GET_LOCK (elem))
178 #define GST_ASYNC_SIGNAL(elem)                g_cond_signal (GST_ASYNC_GET_COND (elem));
179 
180 #define CLEAR_PENDING_EOS(bsrc) \
181   G_STMT_START { \
182     g_atomic_int_set (&bsrc->priv->has_pending_eos, FALSE); \
183     gst_event_replace (&bsrc->priv->pending_eos, NULL); \
184   } G_STMT_END
185 
186 
187 /* BaseSrc signals and args */
188 enum
189 {
190   /* FILL ME */
191   LAST_SIGNAL
192 };
193 
194 #define DEFAULT_BLOCKSIZE       4096
195 #define DEFAULT_NUM_BUFFERS     -1
196 #define DEFAULT_DO_TIMESTAMP    FALSE
197 
198 enum
199 {
200   PROP_0,
201   PROP_BLOCKSIZE,
202   PROP_NUM_BUFFERS,
203 #ifndef GST_REMOVE_DEPRECATED
204   PROP_TYPEFIND,
205 #endif
206   PROP_DO_TIMESTAMP
207 };
208 
209 /* The basesrc implementation need to respect the following locking order:
210  *   1. STREAM_LOCK
211  *   2. LIVE_LOCK
212  *   3. OBJECT_LOCK
213  */
214 struct _GstBaseSrcPrivate
215 {
216   gboolean discont;             /* STREAM_LOCK */
217   gboolean flushing;            /* LIVE_LOCK */
218 
219   GstFlowReturn start_result;   /* OBJECT_LOCK */
220   gboolean async;               /* OBJECT_LOCK */
221 
222   /* if a stream-start event should be sent */
223   gboolean stream_start_pending;        /* STREAM_LOCK */
224 
225   /* if segment should be sent and a
226    * seqnum if it was originated by a seek */
227   gboolean segment_pending;     /* OBJECT_LOCK */
228   guint32 segment_seqnum;       /* OBJECT_LOCK */
229 
230   /* if EOS is pending (atomic) */
231   GstEvent *pending_eos;        /* OBJECT_LOCK */
232   gint has_pending_eos;         /* atomic */
233 
234   /* if the eos was caused by a forced eos from the application */
235   gboolean forced_eos;          /* LIVE_LOCK */
236 
237   /* startup latency is the time it takes between going to PLAYING and producing
238    * the first BUFFER with running_time 0. This value is included in the latency
239    * reporting. */
240   GstClockTime latency;         /* OBJECT_LOCK */
241   /* timestamp offset, this is the offset add to the values of gst_times for
242    * pseudo live sources */
243   GstClockTimeDiff ts_offset;   /* OBJECT_LOCK */
244 
245   gboolean do_timestamp;        /* OBJECT_LOCK */
246   gint dynamic_size;            /* atomic */
247   gint automatic_eos;           /* atomic */
248 
249   /* stream sequence number */
250   guint32 seqnum;               /* STREAM_LOCK */
251 
252   /* pending events (TAG, CUSTOM_BOTH, CUSTOM_DOWNSTREAM) to be
253    * pushed in the data stream */
254   GList *pending_events;        /* OBJECT_LOCK */
255   gint have_events;             /* OBJECT_LOCK */
256 
257   /* QoS *//* with LOCK */
258   gdouble proportion;           /* OBJECT_LOCK */
259   GstClockTime earliest_time;   /* OBJECT_LOCK */
260 
261   GstBufferPool *pool;          /* OBJECT_LOCK */
262   GstAllocator *allocator;      /* OBJECT_LOCK */
263   GstAllocationParams params;   /* OBJECT_LOCK */
264 
265   GCond async_cond;             /* OBJECT_LOCK */
266 
267   /* for _submit_buffer_list() */
268   GstBufferList *pending_bufferlist;
269 };
270 
271 #define BASE_SRC_HAS_PENDING_BUFFER_LIST(src) \
272     ((src)->priv->pending_bufferlist != NULL)
273 
274 static GstElementClass *parent_class = NULL;
275 static gint private_offset = 0;
276 
277 static void gst_base_src_class_init (GstBaseSrcClass * klass);
278 static void gst_base_src_init (GstBaseSrc * src, gpointer g_class);
279 static void gst_base_src_finalize (GObject * object);
280 
281 
282 GType
gst_base_src_get_type(void)283 gst_base_src_get_type (void)
284 {
285   static gsize base_src_type = 0;
286 
287   if (g_once_init_enter (&base_src_type)) {
288     GType _type;
289     static const GTypeInfo base_src_info = {
290       sizeof (GstBaseSrcClass),
291       NULL,
292       NULL,
293       (GClassInitFunc) gst_base_src_class_init,
294       NULL,
295       NULL,
296       sizeof (GstBaseSrc),
297       0,
298       (GInstanceInitFunc) gst_base_src_init,
299     };
300 
301     _type = g_type_register_static (GST_TYPE_ELEMENT,
302         "GstBaseSrc", &base_src_info, G_TYPE_FLAG_ABSTRACT);
303 
304     private_offset =
305         g_type_add_instance_private (_type, sizeof (GstBaseSrcPrivate));
306 
307     g_once_init_leave (&base_src_type, _type);
308   }
309   return base_src_type;
310 }
311 
312 static inline GstBaseSrcPrivate *
gst_base_src_get_instance_private(GstBaseSrc * self)313 gst_base_src_get_instance_private (GstBaseSrc * self)
314 {
315   return (G_STRUCT_MEMBER_P (self, private_offset));
316 }
317 
318 static GstCaps *gst_base_src_default_get_caps (GstBaseSrc * bsrc,
319     GstCaps * filter);
320 static GstCaps *gst_base_src_default_fixate (GstBaseSrc * src, GstCaps * caps);
321 static GstCaps *gst_base_src_fixate (GstBaseSrc * src, GstCaps * caps);
322 
323 static gboolean gst_base_src_is_random_access (GstBaseSrc * src);
324 static gboolean gst_base_src_activate_mode (GstPad * pad, GstObject * parent,
325     GstPadMode mode, gboolean active);
326 static void gst_base_src_set_property (GObject * object, guint prop_id,
327     const GValue * value, GParamSpec * pspec);
328 static void gst_base_src_get_property (GObject * object, guint prop_id,
329     GValue * value, GParamSpec * pspec);
330 static gboolean gst_base_src_event (GstPad * pad, GstObject * parent,
331     GstEvent * event);
332 static gboolean gst_base_src_send_event (GstElement * elem, GstEvent * event);
333 static gboolean gst_base_src_default_event (GstBaseSrc * src, GstEvent * event);
334 
335 static gboolean gst_base_src_query (GstPad * pad, GstObject * parent,
336     GstQuery * query);
337 
338 static void gst_base_src_set_pool_flushing (GstBaseSrc * basesrc,
339     gboolean flushing);
340 static gboolean gst_base_src_default_negotiate (GstBaseSrc * basesrc);
341 static gboolean gst_base_src_default_do_seek (GstBaseSrc * src,
342     GstSegment * segment);
343 static gboolean gst_base_src_default_query (GstBaseSrc * src, GstQuery * query);
344 static gboolean gst_base_src_default_prepare_seek_segment (GstBaseSrc * src,
345     GstEvent * event, GstSegment * segment);
346 static GstFlowReturn gst_base_src_default_create (GstBaseSrc * basesrc,
347     guint64 offset, guint size, GstBuffer ** buf);
348 static GstFlowReturn gst_base_src_default_alloc (GstBaseSrc * basesrc,
349     guint64 offset, guint size, GstBuffer ** buf);
350 static gboolean gst_base_src_decide_allocation_default (GstBaseSrc * basesrc,
351     GstQuery * query);
352 
353 static gboolean gst_base_src_set_flushing (GstBaseSrc * basesrc,
354     gboolean flushing);
355 
356 static gboolean gst_base_src_start (GstBaseSrc * basesrc);
357 static gboolean gst_base_src_stop (GstBaseSrc * basesrc);
358 
359 static GstStateChangeReturn gst_base_src_change_state (GstElement * element,
360     GstStateChange transition);
361 
362 static void gst_base_src_loop (GstPad * pad);
363 static GstFlowReturn gst_base_src_getrange (GstPad * pad, GstObject * parent,
364     guint64 offset, guint length, GstBuffer ** buf);
365 static GstFlowReturn gst_base_src_get_range (GstBaseSrc * src, guint64 offset,
366     guint length, GstBuffer ** buf);
367 static gboolean gst_base_src_seekable (GstBaseSrc * src);
368 static gboolean gst_base_src_negotiate_unlocked (GstBaseSrc * basesrc);
369 static gboolean gst_base_src_update_length (GstBaseSrc * src, guint64 offset,
370     guint * length, gboolean force);
371 
372 static void
gst_base_src_class_init(GstBaseSrcClass * klass)373 gst_base_src_class_init (GstBaseSrcClass * klass)
374 {
375   GObjectClass *gobject_class;
376   GstElementClass *gstelement_class;
377 
378   gobject_class = G_OBJECT_CLASS (klass);
379   gstelement_class = GST_ELEMENT_CLASS (klass);
380 
381   if (private_offset != 0)
382     g_type_class_adjust_private_offset (klass, &private_offset);
383 
384   GST_DEBUG_CATEGORY_INIT (gst_base_src_debug, "basesrc", 0, "basesrc element");
385 
386   parent_class = g_type_class_peek_parent (klass);
387 
388   gobject_class->finalize = gst_base_src_finalize;
389   gobject_class->set_property = gst_base_src_set_property;
390   gobject_class->get_property = gst_base_src_get_property;
391 
392   g_object_class_install_property (gobject_class, PROP_BLOCKSIZE,
393       g_param_spec_uint ("blocksize", "Block size",
394           "Size in bytes to read per buffer (-1 = default)", 0, G_MAXUINT,
395           DEFAULT_BLOCKSIZE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
396   g_object_class_install_property (gobject_class, PROP_NUM_BUFFERS,
397       g_param_spec_int ("num-buffers", "num-buffers",
398           "Number of buffers to output before sending EOS (-1 = unlimited)",
399           -1, G_MAXINT, DEFAULT_NUM_BUFFERS, G_PARAM_READWRITE |
400           G_PARAM_STATIC_STRINGS));
401 #ifndef GST_REMOVE_DEPRECATED
402   g_object_class_install_property (gobject_class, PROP_TYPEFIND,
403       g_param_spec_boolean ("typefind", "Typefind",
404           "Run typefind before negotiating (deprecated, non-functional)", FALSE,
405           G_PARAM_READWRITE | G_PARAM_DEPRECATED | G_PARAM_STATIC_STRINGS));
406 #endif
407   g_object_class_install_property (gobject_class, PROP_DO_TIMESTAMP,
408       g_param_spec_boolean ("do-timestamp", "Do timestamp",
409           "Apply current stream time to buffers", DEFAULT_DO_TIMESTAMP,
410           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
411 
412   gstelement_class->change_state =
413       GST_DEBUG_FUNCPTR (gst_base_src_change_state);
414   gstelement_class->send_event = GST_DEBUG_FUNCPTR (gst_base_src_send_event);
415 
416   klass->get_caps = GST_DEBUG_FUNCPTR (gst_base_src_default_get_caps);
417   klass->negotiate = GST_DEBUG_FUNCPTR (gst_base_src_default_negotiate);
418   klass->fixate = GST_DEBUG_FUNCPTR (gst_base_src_default_fixate);
419   klass->prepare_seek_segment =
420       GST_DEBUG_FUNCPTR (gst_base_src_default_prepare_seek_segment);
421   klass->do_seek = GST_DEBUG_FUNCPTR (gst_base_src_default_do_seek);
422   klass->query = GST_DEBUG_FUNCPTR (gst_base_src_default_query);
423   klass->event = GST_DEBUG_FUNCPTR (gst_base_src_default_event);
424   klass->create = GST_DEBUG_FUNCPTR (gst_base_src_default_create);
425   klass->alloc = GST_DEBUG_FUNCPTR (gst_base_src_default_alloc);
426   klass->decide_allocation =
427       GST_DEBUG_FUNCPTR (gst_base_src_decide_allocation_default);
428 
429   /* Registering debug symbols for function pointers */
430   GST_DEBUG_REGISTER_FUNCPTR (gst_base_src_activate_mode);
431   GST_DEBUG_REGISTER_FUNCPTR (gst_base_src_event);
432   GST_DEBUG_REGISTER_FUNCPTR (gst_base_src_query);
433   GST_DEBUG_REGISTER_FUNCPTR (gst_base_src_getrange);
434   GST_DEBUG_REGISTER_FUNCPTR (gst_base_src_fixate);
435 }
436 
437 static void
gst_base_src_init(GstBaseSrc * basesrc,gpointer g_class)438 gst_base_src_init (GstBaseSrc * basesrc, gpointer g_class)
439 {
440   GstPad *pad;
441   GstPadTemplate *pad_template;
442 
443   basesrc->priv = gst_base_src_get_instance_private (basesrc);
444 
445   basesrc->is_live = FALSE;
446   g_mutex_init (&basesrc->live_lock);
447   g_cond_init (&basesrc->live_cond);
448   basesrc->num_buffers = DEFAULT_NUM_BUFFERS;
449   basesrc->num_buffers_left = -1;
450   g_atomic_int_set (&basesrc->priv->automatic_eos, TRUE);
451 
452   basesrc->can_activate_push = TRUE;
453 
454   pad_template =
455       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (g_class), "src");
456   g_return_if_fail (pad_template != NULL);
457 
458   GST_DEBUG_OBJECT (basesrc, "creating src pad");
459   pad = gst_pad_new_from_template (pad_template, "src");
460 
461   GST_DEBUG_OBJECT (basesrc, "setting functions on src pad");
462   gst_pad_set_activatemode_function (pad, gst_base_src_activate_mode);
463   gst_pad_set_event_function (pad, gst_base_src_event);
464   gst_pad_set_query_function (pad, gst_base_src_query);
465   gst_pad_set_getrange_function (pad, gst_base_src_getrange);
466 
467   /* hold pointer to pad */
468   basesrc->srcpad = pad;
469   GST_DEBUG_OBJECT (basesrc, "adding src pad");
470   gst_element_add_pad (GST_ELEMENT (basesrc), pad);
471 
472   basesrc->blocksize = DEFAULT_BLOCKSIZE;
473   basesrc->clock_id = NULL;
474   /* we operate in BYTES by default */
475   gst_base_src_set_format (basesrc, GST_FORMAT_BYTES);
476   basesrc->priv->do_timestamp = DEFAULT_DO_TIMESTAMP;
477   g_atomic_int_set (&basesrc->priv->have_events, FALSE);
478 
479   g_cond_init (&basesrc->priv->async_cond);
480   basesrc->priv->start_result = GST_FLOW_FLUSHING;
481   GST_OBJECT_FLAG_UNSET (basesrc, GST_BASE_SRC_FLAG_STARTED);
482   GST_OBJECT_FLAG_UNSET (basesrc, GST_BASE_SRC_FLAG_STARTING);
483   GST_OBJECT_FLAG_SET (basesrc, GST_ELEMENT_FLAG_SOURCE);
484 
485   GST_DEBUG_OBJECT (basesrc, "init done");
486 }
487 
488 static void
gst_base_src_finalize(GObject * object)489 gst_base_src_finalize (GObject * object)
490 {
491   GstBaseSrc *basesrc;
492   GstEvent **event_p;
493 
494   basesrc = GST_BASE_SRC (object);
495 
496   g_mutex_clear (&basesrc->live_lock);
497   g_cond_clear (&basesrc->live_cond);
498   g_cond_clear (&basesrc->priv->async_cond);
499 
500   event_p = &basesrc->pending_seek;
501   gst_event_replace (event_p, NULL);
502 
503   if (basesrc->priv->pending_events) {
504     g_list_foreach (basesrc->priv->pending_events, (GFunc) gst_event_unref,
505         NULL);
506     g_list_free (basesrc->priv->pending_events);
507   }
508 
509   G_OBJECT_CLASS (parent_class)->finalize (object);
510 }
511 
512 /* Call with LIVE_LOCK held */
513 static GstFlowReturn
gst_base_src_wait_playing_unlocked(GstBaseSrc * src)514 gst_base_src_wait_playing_unlocked (GstBaseSrc * src)
515 {
516   while (G_UNLIKELY (!src->live_running && !src->priv->flushing)) {
517     /* block until the state changes, or we get a flush, or something */
518     GST_DEBUG_OBJECT (src, "live source waiting for running state");
519     GST_LIVE_WAIT (src);
520     GST_DEBUG_OBJECT (src, "live source unlocked");
521   }
522 
523   if (src->priv->flushing)
524     goto flushing;
525 
526   return GST_FLOW_OK;
527 
528   /* ERRORS */
529 flushing:
530   {
531     GST_DEBUG_OBJECT (src, "we are flushing");
532     return GST_FLOW_FLUSHING;
533   }
534 }
535 
536 
537 /**
538  * gst_base_src_wait_playing:
539  * @src: the src
540  *
541  * If the #GstBaseSrcClass::create method performs its own synchronisation
542  * against the clock it must unblock when going from PLAYING to the PAUSED state
543  * and call this method before continuing to produce the remaining data.
544  *
545  * This function will block until a state change to PLAYING happens (in which
546  * case this function returns %GST_FLOW_OK) or the processing must be stopped due
547  * to a state change to READY or a FLUSH event (in which case this function
548  * returns %GST_FLOW_FLUSHING).
549  *
550  * Returns: %GST_FLOW_OK if @src is PLAYING and processing can
551  * continue. Any other return value should be returned from the create vmethod.
552  */
553 GstFlowReturn
gst_base_src_wait_playing(GstBaseSrc * src)554 gst_base_src_wait_playing (GstBaseSrc * src)
555 {
556   GstFlowReturn ret;
557 
558   g_return_val_if_fail (GST_IS_BASE_SRC (src), GST_FLOW_ERROR);
559 
560   GST_LIVE_LOCK (src);
561   ret = gst_base_src_wait_playing_unlocked (src);
562   GST_LIVE_UNLOCK (src);
563 
564   return ret;
565 }
566 
567 /**
568  * gst_base_src_set_live:
569  * @src: base source instance
570  * @live: new live-mode
571  *
572  * If the element listens to a live source, @live should
573  * be set to %TRUE.
574  *
575  * A live source will not produce data in the PAUSED state and
576  * will therefore not be able to participate in the PREROLL phase
577  * of a pipeline. To signal this fact to the application and the
578  * pipeline, the state change return value of the live source will
579  * be GST_STATE_CHANGE_NO_PREROLL.
580  */
581 void
gst_base_src_set_live(GstBaseSrc * src,gboolean live)582 gst_base_src_set_live (GstBaseSrc * src, gboolean live)
583 {
584   g_return_if_fail (GST_IS_BASE_SRC (src));
585 
586   GST_OBJECT_LOCK (src);
587   src->is_live = live;
588   GST_OBJECT_UNLOCK (src);
589 }
590 
591 /**
592  * gst_base_src_is_live:
593  * @src: base source instance
594  *
595  * Check if an element is in live mode.
596  *
597  * Returns: %TRUE if element is in live mode.
598  */
599 gboolean
gst_base_src_is_live(GstBaseSrc * src)600 gst_base_src_is_live (GstBaseSrc * src)
601 {
602   gboolean result;
603 
604   g_return_val_if_fail (GST_IS_BASE_SRC (src), FALSE);
605 
606   GST_OBJECT_LOCK (src);
607   result = src->is_live;
608   GST_OBJECT_UNLOCK (src);
609 
610   return result;
611 }
612 
613 /**
614  * gst_base_src_set_format:
615  * @src: base source instance
616  * @format: the format to use
617  *
618  * Sets the default format of the source. This will be the format used
619  * for sending SEGMENT events and for performing seeks.
620  *
621  * If a format of GST_FORMAT_BYTES is set, the element will be able to
622  * operate in pull mode if the #GstBaseSrcClass::is_seekable returns %TRUE.
623  *
624  * This function must only be called in states < %GST_STATE_PAUSED.
625  */
626 void
gst_base_src_set_format(GstBaseSrc * src,GstFormat format)627 gst_base_src_set_format (GstBaseSrc * src, GstFormat format)
628 {
629   g_return_if_fail (GST_IS_BASE_SRC (src));
630   g_return_if_fail (GST_STATE (src) <= GST_STATE_READY);
631 
632   GST_OBJECT_LOCK (src);
633   gst_segment_init (&src->segment, format);
634   GST_OBJECT_UNLOCK (src);
635 }
636 
637 /**
638  * gst_base_src_set_dynamic_size:
639  * @src: base source instance
640  * @dynamic: new dynamic size mode
641  *
642  * If not @dynamic, size is only updated when needed, such as when trying to
643  * read past current tracked size.  Otherwise, size is checked for upon each
644  * read.
645  */
646 void
gst_base_src_set_dynamic_size(GstBaseSrc * src,gboolean dynamic)647 gst_base_src_set_dynamic_size (GstBaseSrc * src, gboolean dynamic)
648 {
649   g_return_if_fail (GST_IS_BASE_SRC (src));
650 
651   g_atomic_int_set (&src->priv->dynamic_size, dynamic);
652 }
653 
654 /**
655  * gst_base_src_set_automatic_eos:
656  * @src: base source instance
657  * @automatic_eos: automatic eos
658  *
659  * If @automatic_eos is %TRUE, @src will automatically go EOS if a buffer
660  * after the total size is returned. By default this is %TRUE but sources
661  * that can't return an authoritative size and only know that they're EOS
662  * when trying to read more should set this to %FALSE.
663  *
664  * When @src operates in %GST_FORMAT_TIME, #GstBaseSrc will send an EOS
665  * when a buffer outside of the currently configured segment is pushed if
666  * @automatic_eos is %TRUE. Since 1.16, if @automatic_eos is %FALSE an
667  * EOS will be pushed only when the #GstBaseSrcClass::create implementation
668  * returns %GST_FLOW_EOS.
669  *
670  * Since: 1.4
671  */
672 void
gst_base_src_set_automatic_eos(GstBaseSrc * src,gboolean automatic_eos)673 gst_base_src_set_automatic_eos (GstBaseSrc * src, gboolean automatic_eos)
674 {
675   g_return_if_fail (GST_IS_BASE_SRC (src));
676 
677   g_atomic_int_set (&src->priv->automatic_eos, automatic_eos);
678 }
679 
680 /**
681  * gst_base_src_set_async:
682  * @src: base source instance
683  * @async: new async mode
684  *
685  * Configure async behaviour in @src, no state change will block. The open,
686  * close, start, stop, play and pause virtual methods will be executed in a
687  * different thread and are thus allowed to perform blocking operations. Any
688  * blocking operation should be unblocked with the unlock vmethod.
689  */
690 void
gst_base_src_set_async(GstBaseSrc * src,gboolean async)691 gst_base_src_set_async (GstBaseSrc * src, gboolean async)
692 {
693   g_return_if_fail (GST_IS_BASE_SRC (src));
694 
695   GST_OBJECT_LOCK (src);
696   src->priv->async = async;
697   GST_OBJECT_UNLOCK (src);
698 }
699 
700 /**
701  * gst_base_src_is_async:
702  * @src: base source instance
703  *
704  * Get the current async behaviour of @src. See also gst_base_src_set_async().
705  *
706  * Returns: %TRUE if @src is operating in async mode.
707  */
708 gboolean
gst_base_src_is_async(GstBaseSrc * src)709 gst_base_src_is_async (GstBaseSrc * src)
710 {
711   gboolean res;
712 
713   g_return_val_if_fail (GST_IS_BASE_SRC (src), FALSE);
714 
715   GST_OBJECT_LOCK (src);
716   res = src->priv->async;
717   GST_OBJECT_UNLOCK (src);
718 
719   return res;
720 }
721 
722 
723 /**
724  * gst_base_src_query_latency:
725  * @src: the source
726  * @live: (out) (allow-none): if the source is live
727  * @min_latency: (out) (allow-none): the min latency of the source
728  * @max_latency: (out) (allow-none): the max latency of the source
729  *
730  * Query the source for the latency parameters. @live will be %TRUE when @src is
731  * configured as a live source. @min_latency and @max_latency will be set
732  * to the difference between the running time and the timestamp of the first
733  * buffer.
734  *
735  * This function is mostly used by subclasses.
736  *
737  * Returns: %TRUE if the query succeeded.
738  */
739 gboolean
gst_base_src_query_latency(GstBaseSrc * src,gboolean * live,GstClockTime * min_latency,GstClockTime * max_latency)740 gst_base_src_query_latency (GstBaseSrc * src, gboolean * live,
741     GstClockTime * min_latency, GstClockTime * max_latency)
742 {
743   GstClockTime min;
744 
745   g_return_val_if_fail (GST_IS_BASE_SRC (src), FALSE);
746 
747   GST_OBJECT_LOCK (src);
748   if (live)
749     *live = src->is_live;
750 
751   /* if we have a startup latency, report this one, else report 0. Subclasses
752    * are supposed to override the query function if they want something
753    * else. */
754   if (src->priv->latency != -1)
755     min = src->priv->latency;
756   else
757     min = 0;
758 
759   if (min_latency)
760     *min_latency = min;
761   if (max_latency)
762     *max_latency = min;
763 
764   GST_LOG_OBJECT (src, "latency: live %d, min %" GST_TIME_FORMAT
765       ", max %" GST_TIME_FORMAT, src->is_live, GST_TIME_ARGS (min),
766       GST_TIME_ARGS (min));
767   GST_OBJECT_UNLOCK (src);
768 
769   return TRUE;
770 }
771 
772 /**
773  * gst_base_src_set_blocksize:
774  * @src: the source
775  * @blocksize: the new blocksize in bytes
776  *
777  * Set the number of bytes that @src will push out with each buffer. When
778  * @blocksize is set to -1, a default length will be used.
779  */
780 void
gst_base_src_set_blocksize(GstBaseSrc * src,guint blocksize)781 gst_base_src_set_blocksize (GstBaseSrc * src, guint blocksize)
782 {
783   g_return_if_fail (GST_IS_BASE_SRC (src));
784 
785   GST_OBJECT_LOCK (src);
786   src->blocksize = blocksize;
787   GST_OBJECT_UNLOCK (src);
788 }
789 
790 /**
791  * gst_base_src_get_blocksize:
792  * @src: the source
793  *
794  * Get the number of bytes that @src will push out with each buffer.
795  *
796  * Returns: the number of bytes pushed with each buffer.
797  */
798 guint
gst_base_src_get_blocksize(GstBaseSrc * src)799 gst_base_src_get_blocksize (GstBaseSrc * src)
800 {
801   gint res;
802 
803   g_return_val_if_fail (GST_IS_BASE_SRC (src), 0);
804 
805   GST_OBJECT_LOCK (src);
806   res = src->blocksize;
807   GST_OBJECT_UNLOCK (src);
808 
809   return res;
810 }
811 
812 
813 /**
814  * gst_base_src_set_do_timestamp:
815  * @src: the source
816  * @timestamp: enable or disable timestamping
817  *
818  * Configure @src to automatically timestamp outgoing buffers based on the
819  * current running_time of the pipeline. This property is mostly useful for live
820  * sources.
821  */
822 void
gst_base_src_set_do_timestamp(GstBaseSrc * src,gboolean timestamp)823 gst_base_src_set_do_timestamp (GstBaseSrc * src, gboolean timestamp)
824 {
825   g_return_if_fail (GST_IS_BASE_SRC (src));
826 
827   GST_OBJECT_LOCK (src);
828   src->priv->do_timestamp = timestamp;
829   if (timestamp && src->segment.format != GST_FORMAT_TIME)
830     gst_segment_init (&src->segment, GST_FORMAT_TIME);
831   GST_OBJECT_UNLOCK (src);
832 }
833 
834 /**
835  * gst_base_src_get_do_timestamp:
836  * @src: the source
837  *
838  * Query if @src timestamps outgoing buffers based on the current running_time.
839  *
840  * Returns: %TRUE if the base class will automatically timestamp outgoing buffers.
841  */
842 gboolean
gst_base_src_get_do_timestamp(GstBaseSrc * src)843 gst_base_src_get_do_timestamp (GstBaseSrc * src)
844 {
845   gboolean res;
846 
847   g_return_val_if_fail (GST_IS_BASE_SRC (src), FALSE);
848 
849   GST_OBJECT_LOCK (src);
850   res = src->priv->do_timestamp;
851   GST_OBJECT_UNLOCK (src);
852 
853   return res;
854 }
855 
856 /**
857  * gst_base_src_new_seamless_segment:
858  * @src: The source
859  * @start: The new start value for the segment
860  * @stop: Stop value for the new segment
861  * @time: The new time value for the start of the new segment
862  *
863  * Prepare a new seamless segment for emission downstream. This function must
864  * only be called by derived sub-classes, and only from the #GstBaseSrcClass::create function,
865  * as the stream-lock needs to be held.
866  *
867  * The format for the new segment will be the current format of the source, as
868  * configured with gst_base_src_set_format()
869  *
870  * Returns: %TRUE if preparation of the seamless segment succeeded.
871  *
872  * Deprecated: 1.18: Use gst_base_src_new_segment()
873  */
874 gboolean
gst_base_src_new_seamless_segment(GstBaseSrc * src,gint64 start,gint64 stop,gint64 time)875 gst_base_src_new_seamless_segment (GstBaseSrc * src, gint64 start, gint64 stop,
876     gint64 time)
877 {
878   gboolean res = TRUE;
879 
880   GST_OBJECT_LOCK (src);
881 
882   src->segment.base = gst_segment_to_running_time (&src->segment,
883       src->segment.format, src->segment.position);
884   src->segment.position = src->segment.start = start;
885   src->segment.stop = stop;
886   src->segment.time = time;
887 
888   /* Mark pending segment. Will be sent before next data */
889   src->priv->segment_pending = TRUE;
890   src->priv->segment_seqnum = gst_util_seqnum_next ();
891 
892   GST_DEBUG_OBJECT (src,
893       "Starting new seamless segment. Start %" GST_TIME_FORMAT " stop %"
894       GST_TIME_FORMAT " time %" GST_TIME_FORMAT " base %" GST_TIME_FORMAT,
895       GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (time),
896       GST_TIME_ARGS (src->segment.base));
897 
898   GST_OBJECT_UNLOCK (src);
899 
900   src->priv->discont = TRUE;
901   src->running = TRUE;
902 
903   return res;
904 }
905 
906 /**
907  * gst_base_src_new_segment:
908  * @src: a #GstBaseSrc
909  * @segment: a pointer to a #GstSegment
910  *
911  * Prepare a new segment for emission downstream. This function must
912  * only be called by derived sub-classes, and only from the #GstBaseSrcClass::create function,
913  * as the stream-lock needs to be held.
914  *
915  * The format for the @segment must be identical with the current format
916  * of the source, as configured with gst_base_src_set_format().
917  *
918  * The format of @src must not be %GST_FORMAT_UNDEFINED and the format
919  * should be configured via gst_base_src_set_format() before calling this method.
920  *
921  * Returns: %TRUE if preparation of new segment succeeded.
922  *
923  * Since: 1.18
924  */
925 gboolean
gst_base_src_new_segment(GstBaseSrc * src,const GstSegment * segment)926 gst_base_src_new_segment (GstBaseSrc * src, const GstSegment * segment)
927 {
928   g_return_val_if_fail (GST_IS_BASE_SRC (src), FALSE);
929   g_return_val_if_fail (segment != NULL, FALSE);
930 
931   GST_OBJECT_LOCK (src);
932 
933   if (src->segment.format == GST_FORMAT_UNDEFINED) {
934     /* subclass must set valid format before calling this method */
935     GST_WARNING_OBJECT (src, "segment format is not configured yet, ignore");
936     GST_OBJECT_UNLOCK (src);
937     return FALSE;
938   }
939 
940   if (src->segment.format != segment->format) {
941     GST_WARNING_OBJECT (src, "segment format mismatched, ignore");
942     GST_OBJECT_UNLOCK (src);
943     return FALSE;
944   }
945 
946   gst_segment_copy_into (segment, &src->segment);
947 
948   /* Mark pending segment. Will be sent before next data */
949   src->priv->segment_pending = TRUE;
950   src->priv->segment_seqnum = gst_util_seqnum_next ();
951 
952   GST_DEBUG_OBJECT (src, "Starting new segment %" GST_SEGMENT_FORMAT, segment);
953 
954   GST_OBJECT_UNLOCK (src);
955 
956   src->running = TRUE;
957 
958   return TRUE;
959 }
960 
961 /* called with STREAM_LOCK */
962 static gboolean
gst_base_src_send_stream_start(GstBaseSrc * src)963 gst_base_src_send_stream_start (GstBaseSrc * src)
964 {
965   gboolean ret = TRUE;
966 
967   if (src->priv->stream_start_pending) {
968     gchar *stream_id;
969     GstEvent *event;
970 
971     stream_id =
972         gst_pad_create_stream_id (src->srcpad, GST_ELEMENT_CAST (src), NULL);
973 
974     GST_DEBUG_OBJECT (src, "Pushing STREAM_START");
975     event = gst_event_new_stream_start (stream_id);
976     gst_event_set_group_id (event, gst_util_group_id_next ());
977 
978     ret = gst_pad_push_event (src->srcpad, event);
979     src->priv->stream_start_pending = FALSE;
980     g_free (stream_id);
981   }
982 
983   return ret;
984 }
985 
986 /**
987  * gst_base_src_set_caps:
988  * @src: a #GstBaseSrc
989  * @caps: (transfer none): a #GstCaps
990  *
991  * Set new caps on the basesrc source pad.
992  *
993  * Returns: %TRUE if the caps could be set
994  */
995 gboolean
gst_base_src_set_caps(GstBaseSrc * src,GstCaps * caps)996 gst_base_src_set_caps (GstBaseSrc * src, GstCaps * caps)
997 {
998   GstBaseSrcClass *bclass;
999   gboolean res = TRUE;
1000   GstCaps *current_caps;
1001 
1002   bclass = GST_BASE_SRC_GET_CLASS (src);
1003 
1004   gst_base_src_send_stream_start (src);
1005 
1006   current_caps = gst_pad_get_current_caps (GST_BASE_SRC_PAD (src));
1007   if (current_caps && gst_caps_is_equal (current_caps, caps)) {
1008     GST_DEBUG_OBJECT (src, "New caps equal to old ones: %" GST_PTR_FORMAT,
1009         caps);
1010     res = TRUE;
1011   } else {
1012     if (bclass->set_caps)
1013       res = bclass->set_caps (src, caps);
1014 
1015     if (res)
1016       res = gst_pad_push_event (src->srcpad, gst_event_new_caps (caps));
1017   }
1018 
1019   if (current_caps)
1020     gst_caps_unref (current_caps);
1021 
1022   return res;
1023 }
1024 
1025 static GstCaps *
gst_base_src_default_get_caps(GstBaseSrc * bsrc,GstCaps * filter)1026 gst_base_src_default_get_caps (GstBaseSrc * bsrc, GstCaps * filter)
1027 {
1028   GstCaps *caps = NULL;
1029   GstPadTemplate *pad_template;
1030   GstBaseSrcClass *bclass;
1031 
1032   bclass = GST_BASE_SRC_GET_CLASS (bsrc);
1033 
1034   pad_template =
1035       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
1036 
1037   if (pad_template != NULL) {
1038     caps = gst_pad_template_get_caps (pad_template);
1039 
1040     if (filter) {
1041       GstCaps *intersection;
1042 
1043       intersection =
1044           gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
1045       gst_caps_unref (caps);
1046       caps = intersection;
1047     }
1048   }
1049   return caps;
1050 }
1051 
1052 static GstCaps *
gst_base_src_default_fixate(GstBaseSrc * bsrc,GstCaps * caps)1053 gst_base_src_default_fixate (GstBaseSrc * bsrc, GstCaps * caps)
1054 {
1055   GST_DEBUG_OBJECT (bsrc, "using default caps fixate function");
1056   return gst_caps_fixate (caps);
1057 }
1058 
1059 static GstCaps *
gst_base_src_fixate(GstBaseSrc * bsrc,GstCaps * caps)1060 gst_base_src_fixate (GstBaseSrc * bsrc, GstCaps * caps)
1061 {
1062   GstBaseSrcClass *bclass;
1063 
1064   bclass = GST_BASE_SRC_GET_CLASS (bsrc);
1065 
1066   if (bclass->fixate)
1067     caps = bclass->fixate (bsrc, caps);
1068 
1069   return caps;
1070 }
1071 
1072 static gboolean
gst_base_src_default_query(GstBaseSrc * src,GstQuery * query)1073 gst_base_src_default_query (GstBaseSrc * src, GstQuery * query)
1074 {
1075   gboolean res;
1076 
1077   switch (GST_QUERY_TYPE (query)) {
1078     case GST_QUERY_POSITION:
1079     {
1080       GstFormat format;
1081 
1082       gst_query_parse_position (query, &format, NULL);
1083 
1084       GST_DEBUG_OBJECT (src, "position query in format %s",
1085           gst_format_get_name (format));
1086 
1087       switch (format) {
1088         case GST_FORMAT_PERCENT:
1089         {
1090           gint64 percent;
1091           gint64 position;
1092           gint64 duration;
1093 
1094           GST_OBJECT_LOCK (src);
1095           position = src->segment.position;
1096           duration = src->segment.duration;
1097           GST_OBJECT_UNLOCK (src);
1098 
1099           if (position != -1 && duration != -1) {
1100             if (position < duration)
1101               percent = gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX, position,
1102                   duration);
1103             else
1104               percent = GST_FORMAT_PERCENT_MAX;
1105           } else
1106             percent = -1;
1107 
1108           gst_query_set_position (query, GST_FORMAT_PERCENT, percent);
1109           res = TRUE;
1110           break;
1111         }
1112         default:
1113         {
1114           gint64 position;
1115           GstFormat seg_format;
1116 
1117           GST_OBJECT_LOCK (src);
1118           position =
1119               gst_segment_to_stream_time (&src->segment, src->segment.format,
1120               src->segment.position);
1121           seg_format = src->segment.format;
1122           GST_OBJECT_UNLOCK (src);
1123 
1124           if (position != -1) {
1125             /* convert to requested format */
1126             res =
1127                 gst_pad_query_convert (src->srcpad, seg_format,
1128                 position, format, &position);
1129           } else
1130             res = TRUE;
1131 
1132           if (res)
1133             gst_query_set_position (query, format, position);
1134 
1135           break;
1136         }
1137       }
1138       break;
1139     }
1140     case GST_QUERY_DURATION:
1141     {
1142       GstFormat format;
1143 
1144       gst_query_parse_duration (query, &format, NULL);
1145 
1146       GST_DEBUG_OBJECT (src, "duration query in format %s",
1147           gst_format_get_name (format));
1148 
1149       switch (format) {
1150         case GST_FORMAT_PERCENT:
1151           gst_query_set_duration (query, GST_FORMAT_PERCENT,
1152               GST_FORMAT_PERCENT_MAX);
1153           res = TRUE;
1154           break;
1155         default:
1156         {
1157           gint64 duration;
1158           GstFormat seg_format;
1159           guint length = 0;
1160 
1161           /* may have to refresh duration */
1162           gst_base_src_update_length (src, 0, &length,
1163               g_atomic_int_get (&src->priv->dynamic_size));
1164 
1165           /* this is the duration as configured by the subclass. */
1166           GST_OBJECT_LOCK (src);
1167           duration = src->segment.duration;
1168           seg_format = src->segment.format;
1169           GST_OBJECT_UNLOCK (src);
1170 
1171           GST_LOG_OBJECT (src, "duration %" G_GINT64_FORMAT ", format %s",
1172               duration, gst_format_get_name (seg_format));
1173 
1174           if (duration != -1) {
1175             /* convert to requested format, if this fails, we have a duration
1176              * but we cannot answer the query, we must return FALSE. */
1177             res =
1178                 gst_pad_query_convert (src->srcpad, seg_format,
1179                 duration, format, &duration);
1180           } else {
1181             /* The subclass did not configure a duration, we assume that the
1182              * media has an unknown duration then and we return TRUE to report
1183              * this. Note that this is not the same as returning FALSE, which
1184              * means that we cannot report the duration at all. */
1185             res = TRUE;
1186           }
1187 
1188           if (res)
1189             gst_query_set_duration (query, format, duration);
1190 
1191           break;
1192         }
1193       }
1194       break;
1195     }
1196 
1197     case GST_QUERY_SEEKING:
1198     {
1199       GstFormat format, seg_format;
1200       gint64 duration;
1201 
1202       GST_OBJECT_LOCK (src);
1203       duration = src->segment.duration;
1204       seg_format = src->segment.format;
1205       GST_OBJECT_UNLOCK (src);
1206 
1207       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
1208       if (format == seg_format) {
1209         gst_query_set_seeking (query, seg_format,
1210             gst_base_src_seekable (src), 0, duration);
1211         res = TRUE;
1212       } else {
1213         /* FIXME 2.0: return TRUE + seekable=FALSE for SEEKING query here */
1214         /* Don't reply to the query to make up for demuxers which don't
1215          * handle the SEEKING query yet. Players like Totem will fall back
1216          * to the duration when the SEEKING query isn't answered. */
1217         res = FALSE;
1218       }
1219       break;
1220     }
1221     case GST_QUERY_SEGMENT:
1222     {
1223       GstFormat format;
1224       gint64 start, stop;
1225 
1226       GST_OBJECT_LOCK (src);
1227 
1228       format = src->segment.format;
1229 
1230       start =
1231           gst_segment_to_stream_time (&src->segment, format,
1232           src->segment.start);
1233       if ((stop = src->segment.stop) == -1)
1234         stop = src->segment.duration;
1235       else
1236         stop = gst_segment_to_stream_time (&src->segment, format, stop);
1237 
1238       gst_query_set_segment (query, src->segment.rate, format, start, stop);
1239 
1240       GST_OBJECT_UNLOCK (src);
1241       res = TRUE;
1242       break;
1243     }
1244 
1245     case GST_QUERY_FORMATS:
1246     {
1247       gst_query_set_formats (query, 3, GST_FORMAT_DEFAULT,
1248           GST_FORMAT_BYTES, GST_FORMAT_PERCENT);
1249       res = TRUE;
1250       break;
1251     }
1252     case GST_QUERY_CONVERT:
1253     {
1254       GstFormat src_fmt, dest_fmt;
1255       gint64 src_val, dest_val;
1256 
1257       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1258 
1259       /* we can only convert between equal formats... */
1260       if (src_fmt == dest_fmt) {
1261         dest_val = src_val;
1262         res = TRUE;
1263       } else
1264         res = FALSE;
1265 
1266       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1267       break;
1268     }
1269     case GST_QUERY_LATENCY:
1270     {
1271       GstClockTime min, max;
1272       gboolean live;
1273 
1274       /* Subclasses should override and implement something useful */
1275       res = gst_base_src_query_latency (src, &live, &min, &max);
1276 
1277       GST_LOG_OBJECT (src, "report latency: live %d, min %" GST_TIME_FORMAT
1278           ", max %" GST_TIME_FORMAT, live, GST_TIME_ARGS (min),
1279           GST_TIME_ARGS (max));
1280 
1281       gst_query_set_latency (query, live, min, max);
1282       break;
1283     }
1284     case GST_QUERY_JITTER:
1285     case GST_QUERY_RATE:
1286       res = FALSE;
1287       break;
1288     case GST_QUERY_BUFFERING:
1289     {
1290       GstFormat format, seg_format;
1291       gint64 start, stop, estimated;
1292 
1293       gst_query_parse_buffering_range (query, &format, NULL, NULL, NULL);
1294 
1295       GST_DEBUG_OBJECT (src, "buffering query in format %s",
1296           gst_format_get_name (format));
1297 
1298       GST_OBJECT_LOCK (src);
1299       if (src->random_access) {
1300         estimated = 0;
1301         start = 0;
1302         if (format == GST_FORMAT_PERCENT)
1303           stop = GST_FORMAT_PERCENT_MAX;
1304         else
1305           stop = src->segment.duration;
1306       } else {
1307         estimated = -1;
1308         start = -1;
1309         stop = -1;
1310       }
1311       seg_format = src->segment.format;
1312       GST_OBJECT_UNLOCK (src);
1313 
1314       /* convert to required format. When the conversion fails, we can't answer
1315        * the query. When the value is unknown, we can don't perform conversion
1316        * but report TRUE. */
1317       if (format != GST_FORMAT_PERCENT && stop != -1) {
1318         res = gst_pad_query_convert (src->srcpad, seg_format,
1319             stop, format, &stop);
1320       } else {
1321         res = TRUE;
1322       }
1323       if (res && format != GST_FORMAT_PERCENT && start != -1)
1324         res = gst_pad_query_convert (src->srcpad, seg_format,
1325             start, format, &start);
1326 
1327       gst_query_set_buffering_range (query, format, start, stop, estimated);
1328       break;
1329     }
1330     case GST_QUERY_SCHEDULING:
1331     {
1332       gboolean random_access;
1333 
1334       random_access = gst_base_src_is_random_access (src);
1335 
1336       /* we can operate in getrange mode if the native format is bytes
1337        * and we are seekable, this condition is set in the random_access
1338        * flag and is set in the _start() method. */
1339       gst_query_set_scheduling (query, GST_SCHEDULING_FLAG_SEEKABLE, 1, -1, 0);
1340       if (random_access)
1341         gst_query_add_scheduling_mode (query, GST_PAD_MODE_PULL);
1342       gst_query_add_scheduling_mode (query, GST_PAD_MODE_PUSH);
1343 
1344       res = TRUE;
1345       break;
1346     }
1347     case GST_QUERY_CAPS:
1348     {
1349       GstBaseSrcClass *bclass;
1350       GstCaps *caps, *filter;
1351 
1352       bclass = GST_BASE_SRC_GET_CLASS (src);
1353       if (bclass->get_caps) {
1354         gst_query_parse_caps (query, &filter);
1355         if ((caps = bclass->get_caps (src, filter))) {
1356           gst_query_set_caps_result (query, caps);
1357           gst_caps_unref (caps);
1358           res = TRUE;
1359         } else {
1360           res = FALSE;
1361         }
1362       } else
1363         res = FALSE;
1364       break;
1365     }
1366     case GST_QUERY_URI:{
1367       if (GST_IS_URI_HANDLER (src)) {
1368         gchar *uri = gst_uri_handler_get_uri (GST_URI_HANDLER (src));
1369 
1370         if (uri != NULL) {
1371           gst_query_set_uri (query, uri);
1372           g_free (uri);
1373           res = TRUE;
1374         } else {
1375           res = FALSE;
1376         }
1377       } else {
1378         res = FALSE;
1379       }
1380       break;
1381     }
1382     default:
1383       res = FALSE;
1384       break;
1385   }
1386   GST_DEBUG_OBJECT (src, "query %s returns %d", GST_QUERY_TYPE_NAME (query),
1387       res);
1388 
1389   return res;
1390 }
1391 
1392 static gboolean
gst_base_src_query(GstPad * pad,GstObject * parent,GstQuery * query)1393 gst_base_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1394 {
1395   GstBaseSrc *src;
1396   GstBaseSrcClass *bclass;
1397   gboolean result = FALSE;
1398 
1399   src = GST_BASE_SRC (parent);
1400   bclass = GST_BASE_SRC_GET_CLASS (src);
1401 
1402   if (bclass->query)
1403     result = bclass->query (src, query);
1404 
1405   return result;
1406 }
1407 
1408 static gboolean
gst_base_src_default_do_seek(GstBaseSrc * src,GstSegment * segment)1409 gst_base_src_default_do_seek (GstBaseSrc * src, GstSegment * segment)
1410 {
1411   gboolean res = TRUE;
1412 
1413   /* update our offset if the start/stop position was updated */
1414   if (segment->format == GST_FORMAT_BYTES) {
1415     segment->time = segment->start;
1416   } else if (segment->start == 0) {
1417     /* seek to start, we can implement a default for this. */
1418     segment->time = 0;
1419   } else {
1420     res = FALSE;
1421     GST_INFO_OBJECT (src, "Can't do a default seek");
1422   }
1423 
1424   return res;
1425 }
1426 
1427 static gboolean
gst_base_src_do_seek(GstBaseSrc * src,GstSegment * segment)1428 gst_base_src_do_seek (GstBaseSrc * src, GstSegment * segment)
1429 {
1430   GstBaseSrcClass *bclass;
1431   gboolean result = FALSE;
1432 
1433   bclass = GST_BASE_SRC_GET_CLASS (src);
1434 
1435   GST_INFO_OBJECT (src, "seeking: %" GST_SEGMENT_FORMAT, segment);
1436 
1437   if (bclass->do_seek)
1438     result = bclass->do_seek (src, segment);
1439 
1440   return result;
1441 }
1442 
1443 #define SEEK_TYPE_IS_RELATIVE(t) (((t) != GST_SEEK_TYPE_NONE) && ((t) != GST_SEEK_TYPE_SET))
1444 
1445 static gboolean
gst_base_src_default_prepare_seek_segment(GstBaseSrc * src,GstEvent * event,GstSegment * segment)1446 gst_base_src_default_prepare_seek_segment (GstBaseSrc * src, GstEvent * event,
1447     GstSegment * segment)
1448 {
1449   /* By default, we try one of 2 things:
1450    *   - For absolute seek positions, convert the requested position to our
1451    *     configured processing format and place it in the output segment \
1452    *   - For relative seek positions, convert our current (input) values to the
1453    *     seek format, adjust by the relative seek offset and then convert back to
1454    *     the processing format
1455    */
1456   GstSeekType start_type, stop_type;
1457   gint64 start, stop;
1458   GstSeekFlags flags;
1459   GstFormat seek_format, dest_format;
1460   gdouble rate;
1461   gboolean update;
1462   gboolean res = TRUE;
1463 
1464   gst_event_parse_seek (event, &rate, &seek_format, &flags,
1465       &start_type, &start, &stop_type, &stop);
1466   dest_format = segment->format;
1467 
1468   if (seek_format == dest_format) {
1469     gst_segment_do_seek (segment, rate, seek_format, flags,
1470         start_type, start, stop_type, stop, &update);
1471     return TRUE;
1472   }
1473 
1474   if (start_type != GST_SEEK_TYPE_NONE) {
1475     /* FIXME: Handle seek_end by converting the input segment vals */
1476     res =
1477         gst_pad_query_convert (src->srcpad, seek_format, start, dest_format,
1478         &start);
1479     start_type = GST_SEEK_TYPE_SET;
1480   }
1481 
1482   if (res && stop_type != GST_SEEK_TYPE_NONE) {
1483     /* FIXME: Handle seek_end by converting the input segment vals */
1484     res =
1485         gst_pad_query_convert (src->srcpad, seek_format, stop, dest_format,
1486         &stop);
1487     stop_type = GST_SEEK_TYPE_SET;
1488   }
1489 
1490   /* And finally, configure our output segment in the desired format */
1491   if (res) {
1492     res =
1493         gst_segment_do_seek (segment, rate, dest_format, flags, start_type,
1494         start, stop_type, stop, &update);
1495   }
1496 
1497   if (!res)
1498     goto no_format;
1499 
1500   return res;
1501 
1502 no_format:
1503   {
1504     GST_DEBUG_OBJECT (src, "undefined format given, seek aborted.");
1505     return FALSE;
1506   }
1507 }
1508 
1509 static gboolean
gst_base_src_prepare_seek_segment(GstBaseSrc * src,GstEvent * event,GstSegment * seeksegment)1510 gst_base_src_prepare_seek_segment (GstBaseSrc * src, GstEvent * event,
1511     GstSegment * seeksegment)
1512 {
1513   GstBaseSrcClass *bclass;
1514   gboolean result = FALSE;
1515 
1516   bclass = GST_BASE_SRC_GET_CLASS (src);
1517 
1518   if (bclass->prepare_seek_segment)
1519     result = bclass->prepare_seek_segment (src, event, seeksegment);
1520 
1521   return result;
1522 }
1523 
1524 static GstFlowReturn
gst_base_src_default_alloc(GstBaseSrc * src,guint64 offset,guint size,GstBuffer ** buffer)1525 gst_base_src_default_alloc (GstBaseSrc * src, guint64 offset,
1526     guint size, GstBuffer ** buffer)
1527 {
1528   GstFlowReturn ret;
1529   GstBaseSrcPrivate *priv = src->priv;
1530   GstBufferPool *pool = NULL;
1531   GstAllocator *allocator = NULL;
1532   GstAllocationParams params;
1533 
1534   GST_OBJECT_LOCK (src);
1535   if (priv->pool) {
1536     pool = gst_object_ref (priv->pool);
1537   } else if (priv->allocator) {
1538     allocator = gst_object_ref (priv->allocator);
1539   }
1540   params = priv->params;
1541   GST_OBJECT_UNLOCK (src);
1542 
1543   if (pool) {
1544     ret = gst_buffer_pool_acquire_buffer (pool, buffer, NULL);
1545   } else if (size != -1) {
1546     *buffer = gst_buffer_new_allocate (allocator, size, &params);
1547     if (G_UNLIKELY (*buffer == NULL))
1548       goto alloc_failed;
1549 
1550     ret = GST_FLOW_OK;
1551   } else {
1552     GST_WARNING_OBJECT (src, "Not trying to alloc %u bytes. Blocksize not set?",
1553         size);
1554     goto alloc_failed;
1555   }
1556 
1557 done:
1558   if (pool)
1559     gst_object_unref (pool);
1560   if (allocator)
1561     gst_object_unref (allocator);
1562 
1563   return ret;
1564 
1565   /* ERRORS */
1566 alloc_failed:
1567   {
1568     GST_ERROR_OBJECT (src, "Failed to allocate %u bytes", size);
1569     ret = GST_FLOW_ERROR;
1570     goto done;
1571   }
1572 }
1573 
1574 static GstFlowReturn
gst_base_src_default_create(GstBaseSrc * src,guint64 offset,guint size,GstBuffer ** buffer)1575 gst_base_src_default_create (GstBaseSrc * src, guint64 offset,
1576     guint size, GstBuffer ** buffer)
1577 {
1578   GstBaseSrcClass *bclass;
1579   GstFlowReturn ret;
1580   GstBuffer *res_buf;
1581 
1582   bclass = GST_BASE_SRC_GET_CLASS (src);
1583 
1584   if (G_UNLIKELY (!bclass->alloc))
1585     goto no_function;
1586   if (G_UNLIKELY (!bclass->fill))
1587     goto no_function;
1588 
1589   if (*buffer == NULL) {
1590     /* downstream did not provide us with a buffer to fill, allocate one
1591      * ourselves */
1592     ret = bclass->alloc (src, offset, size, &res_buf);
1593     if (G_UNLIKELY (ret != GST_FLOW_OK))
1594       goto alloc_failed;
1595   } else {
1596     res_buf = *buffer;
1597   }
1598 
1599   if (G_LIKELY (size > 0)) {
1600     /* only call fill when there is a size */
1601     ret = bclass->fill (src, offset, size, res_buf);
1602     if (G_UNLIKELY (ret != GST_FLOW_OK))
1603       goto not_ok;
1604   }
1605 
1606   *buffer = res_buf;
1607 
1608   return GST_FLOW_OK;
1609 
1610   /* ERRORS */
1611 no_function:
1612   {
1613     GST_DEBUG_OBJECT (src, "no fill or alloc function");
1614     return GST_FLOW_NOT_SUPPORTED;
1615   }
1616 alloc_failed:
1617   {
1618     GST_DEBUG_OBJECT (src, "Failed to allocate buffer of %u bytes", size);
1619     return ret;
1620   }
1621 not_ok:
1622   {
1623     GST_DEBUG_OBJECT (src, "fill returned %d (%s)", ret,
1624         gst_flow_get_name (ret));
1625     if (*buffer == NULL)
1626       gst_buffer_unref (res_buf);
1627     return ret;
1628   }
1629 }
1630 
1631 /* this code implements the seeking. It is a good example
1632  * handling all cases.
1633  *
1634  * A seek updates the currently configured segment.start
1635  * and segment.stop values based on the SEEK_TYPE. If the
1636  * segment.start value is updated, a seek to this new position
1637  * should be performed.
1638  *
1639  * The seek can only be executed when we are not currently
1640  * streaming any data, to make sure that this is the case, we
1641  * acquire the STREAM_LOCK which is taken when we are in the
1642  * _loop() function or when a getrange() is called. Normally
1643  * we will not receive a seek if we are operating in pull mode
1644  * though. When we operate as a live source we might block on the live
1645  * cond, which does not release the STREAM_LOCK. Therefore we will try
1646  * to grab the LIVE_LOCK instead of the STREAM_LOCK to make sure it is
1647  * safe to perform the seek.
1648  *
1649  * When we are in the loop() function, we might be in the middle
1650  * of pushing a buffer, which might block in a sink. To make sure
1651  * that the push gets unblocked we push out a FLUSH_START event.
1652  * Our loop function will get a FLUSHING return value from
1653  * the push and will pause, effectively releasing the STREAM_LOCK.
1654  *
1655  * For a non-flushing seek, we pause the task, which might eventually
1656  * release the STREAM_LOCK. We say eventually because when the sink
1657  * blocks on the sample we might wait a very long time until the sink
1658  * unblocks the sample. In any case we acquire the STREAM_LOCK and
1659  * can continue the seek. A non-flushing seek is normally done in a
1660  * running pipeline to perform seamless playback, this means that the sink is
1661  * PLAYING and will return from its chain function.
1662  * In the case of a non-flushing seek we need to make sure that the
1663  * data we output after the seek is continuous with the previous data,
1664  * this is because a non-flushing seek does not reset the running-time
1665  * to 0. We do this by closing the currently running segment, ie. sending
1666  * a new_segment event with the stop position set to the last processed
1667  * position.
1668  *
1669  * After updating the segment.start/stop values, we prepare for
1670  * streaming again. We push out a FLUSH_STOP to make the peer pad
1671  * accept data again and we start our task again.
1672  *
1673  * A segment seek posts a message on the bus saying that the playback
1674  * of the segment started. We store the segment flag internally because
1675  * when we reach the segment.stop we have to post a segment.done
1676  * instead of EOS when doing a segment seek.
1677  */
1678 static gboolean
gst_base_src_perform_seek(GstBaseSrc * src,GstEvent * event,gboolean unlock)1679 gst_base_src_perform_seek (GstBaseSrc * src, GstEvent * event, gboolean unlock)
1680 {
1681   gboolean res = TRUE, tres;
1682   gdouble rate;
1683   GstFormat seek_format, dest_format;
1684   GstSeekFlags flags;
1685   GstSeekType start_type, stop_type;
1686   gint64 start, stop;
1687   gboolean flush;
1688   gboolean update;
1689   gboolean relative_seek = FALSE;
1690   gboolean seekseg_configured = FALSE;
1691   GstSegment seeksegment;
1692   guint32 seqnum;
1693   GstEvent *tevent;
1694 
1695   GST_DEBUG_OBJECT (src, "doing seek: %" GST_PTR_FORMAT, event);
1696 
1697   GST_OBJECT_LOCK (src);
1698   dest_format = src->segment.format;
1699   GST_OBJECT_UNLOCK (src);
1700 
1701   if (event) {
1702     gst_event_parse_seek (event, &rate, &seek_format, &flags,
1703         &start_type, &start, &stop_type, &stop);
1704 
1705     relative_seek = SEEK_TYPE_IS_RELATIVE (start_type) ||
1706         SEEK_TYPE_IS_RELATIVE (stop_type);
1707 
1708     if (dest_format != seek_format && !relative_seek) {
1709       /* If we have an ABSOLUTE position (SEEK_SET only), we can convert it
1710        * here before taking the stream lock, otherwise we must convert it later,
1711        * once we have the stream lock and can read the last configures segment
1712        * start and stop positions */
1713       gst_segment_init (&seeksegment, dest_format);
1714 
1715       if (!gst_base_src_prepare_seek_segment (src, event, &seeksegment))
1716         goto prepare_failed;
1717 
1718       seekseg_configured = TRUE;
1719     }
1720 
1721     flush = flags & GST_SEEK_FLAG_FLUSH;
1722     seqnum = gst_event_get_seqnum (event);
1723   } else {
1724     flush = FALSE;
1725     /* get next seqnum */
1726     seqnum = gst_util_seqnum_next ();
1727   }
1728 
1729   /* send flush start */
1730   if (flush) {
1731     tevent = gst_event_new_flush_start ();
1732     gst_event_set_seqnum (tevent, seqnum);
1733     gst_pad_push_event (src->srcpad, tevent);
1734   } else
1735     gst_pad_pause_task (src->srcpad);
1736 
1737   /* unblock streaming thread. */
1738   if (unlock)
1739     gst_base_src_set_flushing (src, TRUE);
1740 
1741   /* grab streaming lock, this should eventually be possible, either
1742    * because the task is paused, our streaming thread stopped
1743    * or because our peer is flushing. */
1744   GST_PAD_STREAM_LOCK (src->srcpad);
1745   if (G_UNLIKELY (src->priv->seqnum == seqnum)) {
1746     /* we have seen this event before, issue a warning for now */
1747     GST_WARNING_OBJECT (src, "duplicate event found %" G_GUINT32_FORMAT,
1748         seqnum);
1749   } else {
1750     src->priv->seqnum = seqnum;
1751     GST_DEBUG_OBJECT (src, "seek with seqnum %" G_GUINT32_FORMAT, seqnum);
1752   }
1753 
1754   if (unlock)
1755     gst_base_src_set_flushing (src, FALSE);
1756 
1757   /* If we configured the seeksegment above, don't overwrite it now. Otherwise
1758    * copy the current segment info into the temp segment that we can actually
1759    * attempt the seek with. We only update the real segment if the seek succeeds. */
1760   if (!seekseg_configured) {
1761     memcpy (&seeksegment, &src->segment, sizeof (GstSegment));
1762 
1763     /* now configure the final seek segment */
1764     if (event) {
1765       if (seeksegment.format != seek_format) {
1766         /* OK, here's where we give the subclass a chance to convert the relative
1767          * seek into an absolute one in the processing format. We set up any
1768          * absolute seek above, before taking the stream lock. */
1769         if (!gst_base_src_prepare_seek_segment (src, event, &seeksegment)) {
1770           GST_DEBUG_OBJECT (src, "Preparing the seek failed after flushing. "
1771               "Aborting seek");
1772           res = FALSE;
1773         }
1774       } else {
1775         /* The seek format matches our processing format, no need to ask the
1776          * the subclass to configure the segment. */
1777         gst_segment_do_seek (&seeksegment, rate, seek_format, flags,
1778             start_type, start, stop_type, stop, &update);
1779       }
1780     }
1781     /* Else, no seek event passed, so we're just (re)starting the
1782        current segment. */
1783   }
1784 
1785   if (res) {
1786     GST_DEBUG_OBJECT (src, "segment configured from %" G_GINT64_FORMAT
1787         " to %" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT,
1788         seeksegment.start, seeksegment.stop, seeksegment.position);
1789 
1790     /* do the seek, segment.position contains the new position. */
1791     res = gst_base_src_do_seek (src, &seeksegment);
1792   }
1793 
1794   /* and prepare to continue streaming */
1795   if (flush) {
1796     tevent = gst_event_new_flush_stop (TRUE);
1797     gst_event_set_seqnum (tevent, seqnum);
1798     /* send flush stop, peer will accept data and events again. We
1799      * are not yet providing data as we still have the STREAM_LOCK. */
1800     gst_pad_push_event (src->srcpad, tevent);
1801   }
1802 
1803   /* The subclass must have converted the segment to the processing format
1804    * by now */
1805   if (res && seeksegment.format != dest_format) {
1806     GST_DEBUG_OBJECT (src, "Subclass failed to prepare a seek segment "
1807         "in the correct format. Aborting seek.");
1808     res = FALSE;
1809   }
1810 
1811   /* if the seek was successful, we update our real segment and push
1812    * out the new segment. */
1813   if (res) {
1814     GST_OBJECT_LOCK (src);
1815     memcpy (&src->segment, &seeksegment, sizeof (GstSegment));
1816     GST_OBJECT_UNLOCK (src);
1817 
1818     if (seeksegment.flags & GST_SEGMENT_FLAG_SEGMENT) {
1819       GstMessage *message;
1820 
1821       message = gst_message_new_segment_start (GST_OBJECT (src),
1822           seeksegment.format, seeksegment.position);
1823       gst_message_set_seqnum (message, seqnum);
1824 
1825       gst_element_post_message (GST_ELEMENT (src), message);
1826     }
1827 
1828     src->priv->segment_pending = TRUE;
1829     src->priv->segment_seqnum = seqnum;
1830   }
1831 
1832   src->priv->discont = TRUE;
1833   src->running = TRUE;
1834   /* and restart the task in case it got paused explicitly or by
1835    * the FLUSH_START event we pushed out. */
1836   tres = gst_pad_start_task (src->srcpad, (GstTaskFunction) gst_base_src_loop,
1837       src->srcpad, NULL);
1838   if (res && !tres)
1839     res = FALSE;
1840 
1841   /* and release the lock again so we can continue streaming */
1842   GST_PAD_STREAM_UNLOCK (src->srcpad);
1843 
1844   return res;
1845 
1846   /* ERROR */
1847 prepare_failed:
1848   GST_DEBUG_OBJECT (src, "Preparing the seek failed before flushing. "
1849       "Aborting seek");
1850   return FALSE;
1851 }
1852 
1853 /* all events send to this element directly. This is mainly done from the
1854  * application.
1855  */
1856 static gboolean
gst_base_src_send_event(GstElement * element,GstEvent * event)1857 gst_base_src_send_event (GstElement * element, GstEvent * event)
1858 {
1859   GstBaseSrc *src;
1860   gboolean result = FALSE;
1861   GstBaseSrcClass *bclass;
1862 
1863   src = GST_BASE_SRC (element);
1864   bclass = GST_BASE_SRC_GET_CLASS (src);
1865 
1866   GST_DEBUG_OBJECT (src, "handling event %p %" GST_PTR_FORMAT, event, event);
1867 
1868   switch (GST_EVENT_TYPE (event)) {
1869       /* bidirectional events */
1870     case GST_EVENT_FLUSH_START:
1871       GST_DEBUG_OBJECT (src, "pushing flush-start event downstream");
1872 
1873       result = gst_pad_push_event (src->srcpad, event);
1874       gst_base_src_set_flushing (src, TRUE);
1875       event = NULL;
1876       break;
1877     case GST_EVENT_FLUSH_STOP:
1878     {
1879       gboolean start;
1880 
1881       GST_PAD_STREAM_LOCK (src->srcpad);
1882       gst_base_src_set_flushing (src, FALSE);
1883 
1884       GST_DEBUG_OBJECT (src, "pushing flush-stop event downstream");
1885       result = gst_pad_push_event (src->srcpad, event);
1886 
1887       /* For external flush, restart the task .. */
1888       GST_LIVE_LOCK (src);
1889       src->priv->segment_pending = TRUE;
1890 
1891       GST_OBJECT_LOCK (src->srcpad);
1892       start = (GST_PAD_MODE (src->srcpad) == GST_PAD_MODE_PUSH);
1893       GST_OBJECT_UNLOCK (src->srcpad);
1894 
1895       /* ... and for live sources, only if in playing state */
1896       if (src->is_live) {
1897         if (!src->live_running)
1898           start = FALSE;
1899       }
1900 
1901       if (start)
1902         gst_pad_start_task (src->srcpad, (GstTaskFunction) gst_base_src_loop,
1903             src->srcpad, NULL);
1904 
1905       GST_LIVE_UNLOCK (src);
1906       GST_PAD_STREAM_UNLOCK (src->srcpad);
1907 
1908       event = NULL;
1909       break;
1910     }
1911 
1912       /* downstream serialized events */
1913     case GST_EVENT_EOS:
1914     {
1915       gboolean push_mode;
1916 
1917       /* queue EOS and make sure the task or pull function performs the EOS
1918        * actions.
1919        *
1920        * For push mode, This will be done in 3 steps. It is required to not
1921        * block here as gst_element_send_event() will hold the STATE_LOCK, hence
1922        * blocking would prevent asynchronous state change to complete.
1923        *
1924        * 1. We stop the streaming thread
1925        * 2. We set the pending eos
1926        * 3. We start the streaming thread again, so it is performed
1927        *    asynchronously.
1928        *
1929        * For pull mode, we simply mark the pending EOS without flushing.
1930        */
1931 
1932       GST_OBJECT_LOCK (src->srcpad);
1933       push_mode = GST_PAD_MODE (src->srcpad) == GST_PAD_MODE_PUSH;
1934       GST_OBJECT_UNLOCK (src->srcpad);
1935 
1936       if (push_mode) {
1937         gst_base_src_set_flushing (src, TRUE);
1938 
1939         GST_PAD_STREAM_LOCK (src->srcpad);
1940         gst_base_src_set_flushing (src, FALSE);
1941 
1942         GST_OBJECT_LOCK (src);
1943         g_atomic_int_set (&src->priv->has_pending_eos, TRUE);
1944         if (src->priv->pending_eos)
1945           gst_event_unref (src->priv->pending_eos);
1946         src->priv->pending_eos = event;
1947         GST_OBJECT_UNLOCK (src);
1948 
1949         GST_DEBUG_OBJECT (src,
1950             "EOS marked, start task for asynchronous handling");
1951         gst_pad_start_task (src->srcpad, (GstTaskFunction) gst_base_src_loop,
1952             src->srcpad, NULL);
1953 
1954         GST_PAD_STREAM_UNLOCK (src->srcpad);
1955       } else {
1956         /* In pull mode, we need not to return flushing to downstream, though
1957          * the stream lock is not kept after getrange was unblocked */
1958         GST_OBJECT_LOCK (src);
1959         g_atomic_int_set (&src->priv->has_pending_eos, TRUE);
1960         if (src->priv->pending_eos)
1961           gst_event_unref (src->priv->pending_eos);
1962         src->priv->pending_eos = event;
1963         GST_OBJECT_UNLOCK (src);
1964 
1965         gst_base_src_set_pool_flushing (src, TRUE);
1966         if (bclass->unlock)
1967           bclass->unlock (src);
1968 
1969         GST_PAD_STREAM_LOCK (src->srcpad);
1970         if (bclass->unlock_stop)
1971           bclass->unlock_stop (src);
1972         gst_base_src_set_pool_flushing (src, TRUE);
1973         GST_PAD_STREAM_UNLOCK (src->srcpad);
1974       }
1975 
1976 
1977       event = NULL;
1978       result = TRUE;
1979       break;
1980     }
1981     case GST_EVENT_SEGMENT:
1982       /* sending random SEGMENT downstream can break sync. */
1983       break;
1984     case GST_EVENT_TAG:
1985     case GST_EVENT_SINK_MESSAGE:
1986     case GST_EVENT_CUSTOM_DOWNSTREAM:
1987     case GST_EVENT_CUSTOM_BOTH:
1988     case GST_EVENT_PROTECTION:
1989       /* Insert TAG, CUSTOM_DOWNSTREAM, CUSTOM_BOTH, PROTECTION in the dataflow */
1990       GST_OBJECT_LOCK (src);
1991       src->priv->pending_events =
1992           g_list_append (src->priv->pending_events, event);
1993       g_atomic_int_set (&src->priv->have_events, TRUE);
1994       GST_OBJECT_UNLOCK (src);
1995       event = NULL;
1996       result = TRUE;
1997       break;
1998     case GST_EVENT_BUFFERSIZE:
1999       /* does not seem to make much sense currently */
2000       break;
2001 
2002       /* upstream events */
2003     case GST_EVENT_QOS:
2004       /* elements should override send_event and do something */
2005       break;
2006     case GST_EVENT_SEEK:
2007     {
2008       gboolean started;
2009 
2010       GST_OBJECT_LOCK (src->srcpad);
2011       if (GST_PAD_MODE (src->srcpad) == GST_PAD_MODE_PULL)
2012         goto wrong_mode;
2013       started = GST_PAD_MODE (src->srcpad) == GST_PAD_MODE_PUSH;
2014       GST_OBJECT_UNLOCK (src->srcpad);
2015 
2016       if (started) {
2017         GST_DEBUG_OBJECT (src, "performing seek");
2018         /* when we are running in push mode, we can execute the
2019          * seek right now. */
2020         result = gst_base_src_perform_seek (src, event, TRUE);
2021       } else {
2022         GstEvent **event_p;
2023 
2024         /* else we store the event and execute the seek when we
2025          * get activated */
2026         GST_OBJECT_LOCK (src);
2027         GST_DEBUG_OBJECT (src, "queueing seek");
2028         event_p = &src->pending_seek;
2029         gst_event_replace ((GstEvent **) event_p, event);
2030         GST_OBJECT_UNLOCK (src);
2031         /* assume the seek will work */
2032         result = TRUE;
2033       }
2034       break;
2035     }
2036     case GST_EVENT_NAVIGATION:
2037       /* could make sense for elements that do something with navigation events
2038        * but then they would need to override the send_event function */
2039       break;
2040     case GST_EVENT_LATENCY:
2041       /* does not seem to make sense currently */
2042       break;
2043 
2044       /* custom events */
2045     case GST_EVENT_CUSTOM_UPSTREAM:
2046       /* override send_event if you want this */
2047       break;
2048     case GST_EVENT_CUSTOM_DOWNSTREAM_OOB:
2049     case GST_EVENT_CUSTOM_BOTH_OOB:
2050       /* insert a random custom event into the pipeline */
2051       GST_DEBUG_OBJECT (src, "pushing custom OOB event downstream");
2052       result = gst_pad_push_event (src->srcpad, event);
2053       /* we gave away the ref to the event in the push */
2054       event = NULL;
2055       break;
2056     default:
2057       break;
2058   }
2059 done:
2060   /* if we still have a ref to the event, unref it now */
2061   if (event)
2062     gst_event_unref (event);
2063 
2064   return result;
2065 
2066   /* ERRORS */
2067 wrong_mode:
2068   {
2069     GST_DEBUG_OBJECT (src, "cannot perform seek when operating in pull mode");
2070     GST_OBJECT_UNLOCK (src->srcpad);
2071     result = FALSE;
2072     goto done;
2073   }
2074 }
2075 
2076 static gboolean
gst_base_src_seekable(GstBaseSrc * src)2077 gst_base_src_seekable (GstBaseSrc * src)
2078 {
2079   GstBaseSrcClass *bclass;
2080   bclass = GST_BASE_SRC_GET_CLASS (src);
2081   if (bclass->is_seekable)
2082     return bclass->is_seekable (src);
2083   else
2084     return FALSE;
2085 }
2086 
2087 static void
gst_base_src_update_qos(GstBaseSrc * src,gdouble proportion,GstClockTimeDiff diff,GstClockTime timestamp)2088 gst_base_src_update_qos (GstBaseSrc * src,
2089     gdouble proportion, GstClockTimeDiff diff, GstClockTime timestamp)
2090 {
2091   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, src,
2092       "qos: proportion: %lf, diff %" G_GINT64_FORMAT ", timestamp %"
2093       GST_TIME_FORMAT, proportion, diff, GST_TIME_ARGS (timestamp));
2094 
2095   GST_OBJECT_LOCK (src);
2096   src->priv->proportion = proportion;
2097   src->priv->earliest_time = timestamp + diff;
2098   GST_OBJECT_UNLOCK (src);
2099 }
2100 
2101 
2102 static gboolean
gst_base_src_default_event(GstBaseSrc * src,GstEvent * event)2103 gst_base_src_default_event (GstBaseSrc * src, GstEvent * event)
2104 {
2105   gboolean result;
2106 
2107   GST_DEBUG_OBJECT (src, "handle event %" GST_PTR_FORMAT, event);
2108 
2109   switch (GST_EVENT_TYPE (event)) {
2110     case GST_EVENT_SEEK:
2111       /* is normally called when in push mode */
2112       if (!gst_base_src_seekable (src))
2113         goto not_seekable;
2114 
2115       result = gst_base_src_perform_seek (src, event, TRUE);
2116       break;
2117     case GST_EVENT_FLUSH_START:
2118       /* cancel any blocking getrange, is normally called
2119        * when in pull mode. */
2120       result = gst_base_src_set_flushing (src, TRUE);
2121       break;
2122     case GST_EVENT_FLUSH_STOP:
2123       result = gst_base_src_set_flushing (src, FALSE);
2124       break;
2125     case GST_EVENT_QOS:
2126     {
2127       gdouble proportion;
2128       GstClockTimeDiff diff;
2129       GstClockTime timestamp;
2130 
2131       gst_event_parse_qos (event, NULL, &proportion, &diff, &timestamp);
2132       gst_base_src_update_qos (src, proportion, diff, timestamp);
2133       result = TRUE;
2134       break;
2135     }
2136     case GST_EVENT_RECONFIGURE:
2137       result = TRUE;
2138       break;
2139     case GST_EVENT_LATENCY:
2140       result = TRUE;
2141       break;
2142     default:
2143       result = FALSE;
2144       break;
2145   }
2146   return result;
2147 
2148   /* ERRORS */
2149 not_seekable:
2150   {
2151     GST_DEBUG_OBJECT (src, "is not seekable");
2152     return FALSE;
2153   }
2154 }
2155 
2156 static gboolean
gst_base_src_event(GstPad * pad,GstObject * parent,GstEvent * event)2157 gst_base_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
2158 {
2159   GstBaseSrc *src;
2160   GstBaseSrcClass *bclass;
2161   gboolean result = FALSE;
2162 
2163   src = GST_BASE_SRC (parent);
2164   bclass = GST_BASE_SRC_GET_CLASS (src);
2165 
2166   if (bclass->event) {
2167     if (!(result = bclass->event (src, event)))
2168       goto subclass_failed;
2169   }
2170 
2171 done:
2172   gst_event_unref (event);
2173 
2174   return result;
2175 
2176   /* ERRORS */
2177 subclass_failed:
2178   {
2179     GST_DEBUG_OBJECT (src, "subclass refused event");
2180     goto done;
2181   }
2182 }
2183 
2184 static void
gst_base_src_set_property(GObject * object,guint prop_id,const GValue * value,GParamSpec * pspec)2185 gst_base_src_set_property (GObject * object, guint prop_id,
2186     const GValue * value, GParamSpec * pspec)
2187 {
2188   GstBaseSrc *src;
2189 
2190   src = GST_BASE_SRC (object);
2191 
2192   switch (prop_id) {
2193     case PROP_BLOCKSIZE:
2194       gst_base_src_set_blocksize (src, g_value_get_uint (value));
2195       break;
2196     case PROP_NUM_BUFFERS:
2197       src->num_buffers = g_value_get_int (value);
2198       break;
2199 #ifndef GST_REMOVE_DEPRECATED
2200     case PROP_TYPEFIND:
2201       src->typefind = g_value_get_boolean (value);
2202       break;
2203 #endif
2204     case PROP_DO_TIMESTAMP:
2205       gst_base_src_set_do_timestamp (src, g_value_get_boolean (value));
2206       break;
2207     default:
2208       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2209       break;
2210   }
2211 }
2212 
2213 static void
gst_base_src_get_property(GObject * object,guint prop_id,GValue * value,GParamSpec * pspec)2214 gst_base_src_get_property (GObject * object, guint prop_id, GValue * value,
2215     GParamSpec * pspec)
2216 {
2217   GstBaseSrc *src;
2218 
2219   src = GST_BASE_SRC (object);
2220 
2221   switch (prop_id) {
2222     case PROP_BLOCKSIZE:
2223       g_value_set_uint (value, gst_base_src_get_blocksize (src));
2224       break;
2225     case PROP_NUM_BUFFERS:
2226       g_value_set_int (value, src->num_buffers);
2227       break;
2228 #ifndef GST_REMOVE_DEPRECATED
2229     case PROP_TYPEFIND:
2230       g_value_set_boolean (value, src->typefind);
2231       break;
2232 #endif
2233     case PROP_DO_TIMESTAMP:
2234       g_value_set_boolean (value, gst_base_src_get_do_timestamp (src));
2235       break;
2236     default:
2237       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2238       break;
2239   }
2240 }
2241 
2242 /* with STREAM_LOCK and LOCK */
2243 static GstClockReturn
gst_base_src_wait(GstBaseSrc * basesrc,GstClock * clock,GstClockTime time)2244 gst_base_src_wait (GstBaseSrc * basesrc, GstClock * clock, GstClockTime time)
2245 {
2246   GstClockReturn ret;
2247   GstClockID id;
2248 
2249   id = gst_clock_new_single_shot_id (clock, time);
2250 
2251   basesrc->clock_id = id;
2252   /* release the live lock while waiting */
2253   GST_LIVE_UNLOCK (basesrc);
2254 
2255   ret = gst_clock_id_wait (id, NULL);
2256 
2257   GST_LIVE_LOCK (basesrc);
2258   gst_clock_id_unref (id);
2259   basesrc->clock_id = NULL;
2260 
2261   return ret;
2262 }
2263 
2264 /* perform synchronisation on a buffer.
2265  * with STREAM_LOCK.
2266  */
2267 static GstClockReturn
gst_base_src_do_sync(GstBaseSrc * basesrc,GstBuffer * buffer)2268 gst_base_src_do_sync (GstBaseSrc * basesrc, GstBuffer * buffer)
2269 {
2270   GstClockReturn result;
2271   GstClockTime start, end;
2272   GstBaseSrcClass *bclass;
2273   GstClockTime base_time;
2274   GstClock *clock;
2275   GstClockTime now = GST_CLOCK_TIME_NONE, pts, dts, timestamp;
2276   gboolean do_timestamp, first, pseudo_live, is_live;
2277 
2278   bclass = GST_BASE_SRC_GET_CLASS (basesrc);
2279 
2280   start = end = -1;
2281   if (bclass->get_times)
2282     bclass->get_times (basesrc, buffer, &start, &end);
2283 
2284   /* get buffer timestamp */
2285   dts = GST_BUFFER_DTS (buffer);
2286   pts = GST_BUFFER_PTS (buffer);
2287 
2288   if (GST_CLOCK_TIME_IS_VALID (dts))
2289     timestamp = dts;
2290   else
2291     timestamp = pts;
2292 
2293   /* grab the lock to prepare for clocking and calculate the startup
2294    * latency. */
2295   GST_OBJECT_LOCK (basesrc);
2296 
2297   is_live = basesrc->is_live;
2298   /* if we are asked to sync against the clock we are a pseudo live element */
2299   pseudo_live = (start != -1 && is_live);
2300   /* check for the first buffer */
2301   first = (basesrc->priv->latency == -1);
2302 
2303   if (timestamp != -1 && pseudo_live) {
2304     GstClockTime latency;
2305 
2306     /* we have a timestamp and a sync time, latency is the diff */
2307     if (timestamp <= start)
2308       latency = start - timestamp;
2309     else
2310       latency = 0;
2311 
2312     if (first) {
2313       GST_DEBUG_OBJECT (basesrc, "pseudo_live with latency %" GST_TIME_FORMAT,
2314           GST_TIME_ARGS (latency));
2315       /* first time we calculate latency, just configure */
2316       basesrc->priv->latency = latency;
2317     } else {
2318       if (basesrc->priv->latency != latency) {
2319         /* we have a new latency, FIXME post latency message */
2320         basesrc->priv->latency = latency;
2321         GST_DEBUG_OBJECT (basesrc, "latency changed to %" GST_TIME_FORMAT,
2322             GST_TIME_ARGS (latency));
2323       }
2324     }
2325   } else if (first) {
2326     GST_DEBUG_OBJECT (basesrc, "no latency needed, live %d, sync %d",
2327         is_live, start != -1);
2328     basesrc->priv->latency = 0;
2329   }
2330 
2331   /* get clock, if no clock, we can't sync or do timestamps */
2332   if ((clock = GST_ELEMENT_CLOCK (basesrc)) == NULL)
2333     goto no_clock;
2334   else
2335     gst_object_ref (clock);
2336 
2337   base_time = GST_ELEMENT_CAST (basesrc)->base_time;
2338 
2339   do_timestamp = basesrc->priv->do_timestamp;
2340   GST_OBJECT_UNLOCK (basesrc);
2341 
2342   /* first buffer, calculate the timestamp offset */
2343   if (first) {
2344     GstClockTime running_time;
2345 
2346     now = gst_clock_get_time (clock);
2347     running_time = now - base_time;
2348 
2349     GST_LOG_OBJECT (basesrc,
2350         "startup PTS: %" GST_TIME_FORMAT ", DTS %" GST_TIME_FORMAT
2351         ", running_time %" GST_TIME_FORMAT, GST_TIME_ARGS (pts),
2352         GST_TIME_ARGS (dts), GST_TIME_ARGS (running_time));
2353 
2354     if (pseudo_live && timestamp != -1) {
2355       /* live source and we need to sync, add startup latency to all timestamps
2356        * to get the real running_time. Live sources should always timestamp
2357        * according to the current running time. */
2358       basesrc->priv->ts_offset = GST_CLOCK_DIFF (timestamp, running_time);
2359 
2360       GST_LOG_OBJECT (basesrc, "live with sync, ts_offset %" GST_TIME_FORMAT,
2361           GST_TIME_ARGS (basesrc->priv->ts_offset));
2362     } else {
2363       basesrc->priv->ts_offset = 0;
2364       GST_LOG_OBJECT (basesrc, "no timestamp offset needed");
2365     }
2366 
2367     if (!GST_CLOCK_TIME_IS_VALID (dts)) {
2368       if (do_timestamp) {
2369         dts = running_time;
2370       } else if (!GST_CLOCK_TIME_IS_VALID (pts)) {
2371         if (GST_CLOCK_TIME_IS_VALID (basesrc->segment.start)) {
2372           dts = basesrc->segment.start;
2373         } else {
2374           dts = 0;
2375         }
2376       }
2377       GST_BUFFER_DTS (buffer) = dts;
2378 
2379       GST_LOG_OBJECT (basesrc, "created DTS %" GST_TIME_FORMAT,
2380           GST_TIME_ARGS (dts));
2381     }
2382   } else {
2383     /* not the first buffer, the timestamp is the diff between the clock and
2384      * base_time */
2385     if (do_timestamp && !GST_CLOCK_TIME_IS_VALID (dts)) {
2386       now = gst_clock_get_time (clock);
2387 
2388       dts = now - base_time;
2389       GST_BUFFER_DTS (buffer) = dts;
2390 
2391       GST_LOG_OBJECT (basesrc, "created DTS %" GST_TIME_FORMAT,
2392           GST_TIME_ARGS (dts));
2393     }
2394   }
2395   if (!GST_CLOCK_TIME_IS_VALID (pts)) {
2396     if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT))
2397       pts = dts;
2398 
2399     GST_BUFFER_PTS (buffer) = dts;
2400 
2401     GST_LOG_OBJECT (basesrc, "created PTS %" GST_TIME_FORMAT,
2402         GST_TIME_ARGS (pts));
2403   }
2404 
2405   /* if we don't have a buffer timestamp, we don't sync */
2406   if (!GST_CLOCK_TIME_IS_VALID (start))
2407     goto no_sync;
2408 
2409   if (is_live) {
2410     /* for pseudo live sources, add our ts_offset to the timestamp */
2411     if (GST_CLOCK_TIME_IS_VALID (pts))
2412       GST_BUFFER_PTS (buffer) += basesrc->priv->ts_offset;
2413     if (GST_CLOCK_TIME_IS_VALID (dts))
2414       GST_BUFFER_DTS (buffer) += basesrc->priv->ts_offset;
2415     start += basesrc->priv->ts_offset;
2416   }
2417 
2418   GST_LOG_OBJECT (basesrc,
2419       "waiting for clock, base time %" GST_TIME_FORMAT
2420       ", stream_start %" GST_TIME_FORMAT,
2421       GST_TIME_ARGS (base_time), GST_TIME_ARGS (start));
2422 
2423   result = gst_base_src_wait (basesrc, clock, start + base_time);
2424 
2425   gst_object_unref (clock);
2426 
2427   GST_LOG_OBJECT (basesrc, "clock entry done: %d", result);
2428 
2429   return result;
2430 
2431   /* special cases */
2432 no_clock:
2433   {
2434     GST_DEBUG_OBJECT (basesrc, "we have no clock");
2435     GST_OBJECT_UNLOCK (basesrc);
2436     return GST_CLOCK_OK;
2437   }
2438 no_sync:
2439   {
2440     GST_DEBUG_OBJECT (basesrc, "no sync needed");
2441     gst_object_unref (clock);
2442     return GST_CLOCK_OK;
2443   }
2444 }
2445 
2446 /* Called with STREAM_LOCK and LIVE_LOCK */
2447 static gboolean
gst_base_src_update_length(GstBaseSrc * src,guint64 offset,guint * length,gboolean force)2448 gst_base_src_update_length (GstBaseSrc * src, guint64 offset, guint * length,
2449     gboolean force)
2450 {
2451   guint64 size, maxsize;
2452   GstBaseSrcClass *bclass;
2453   gint64 stop;
2454 
2455   /* only operate if we are working with bytes */
2456   if (src->segment.format != GST_FORMAT_BYTES)
2457     return TRUE;
2458 
2459   bclass = GST_BASE_SRC_GET_CLASS (src);
2460 
2461   stop = src->segment.stop;
2462   /* get total file size */
2463   size = src->segment.duration;
2464 
2465   /* when not doing automatic EOS, just use the stop position. We don't use
2466    * the size to check for EOS */
2467   if (!g_atomic_int_get (&src->priv->automatic_eos))
2468     maxsize = stop;
2469   /* Otherwise, the max amount of bytes to read is the total
2470    * size or up to the segment.stop if present. */
2471   else if (stop != -1)
2472     maxsize = size != -1 ? MIN (size, stop) : stop;
2473   else
2474     maxsize = size;
2475 
2476   GST_DEBUG_OBJECT (src,
2477       "reading offset %" G_GUINT64_FORMAT ", length %u, size %" G_GINT64_FORMAT
2478       ", segment.stop %" G_GINT64_FORMAT ", maxsize %" G_GINT64_FORMAT, offset,
2479       *length, size, stop, maxsize);
2480 
2481   /* check size if we have one */
2482   if (maxsize != -1) {
2483     /* if we run past the end, check if the file became bigger and
2484      * retry.  Mind wrap when checking. */
2485     if (G_UNLIKELY (offset >= maxsize || offset + *length >= maxsize || force)) {
2486       /* see if length of the file changed */
2487       if (bclass->get_size)
2488         if (!bclass->get_size (src, &size))
2489           size = -1;
2490 
2491       /* when not doing automatic EOS, just use the stop position. We don't use
2492        * the size to check for EOS */
2493       if (!g_atomic_int_get (&src->priv->automatic_eos))
2494         maxsize = stop;
2495       /* Otherwise, the max amount of bytes to read is the total
2496        * size or up to the segment.stop if present. */
2497       else if (stop != -1)
2498         maxsize = size != -1 ? MIN (size, stop) : stop;
2499       else
2500         maxsize = size;
2501 
2502       if (maxsize != -1) {
2503         /* if we are at or past the end, EOS */
2504         if (G_UNLIKELY (offset >= maxsize))
2505           goto unexpected_length;
2506 
2507         /* else we can clip to the end */
2508         if (G_UNLIKELY (offset + *length >= maxsize))
2509           *length = maxsize - offset;
2510       }
2511     }
2512   }
2513 
2514   /* keep track of current duration. segment is in bytes, we checked
2515    * that above. */
2516   GST_OBJECT_LOCK (src);
2517   src->segment.duration = size;
2518   GST_OBJECT_UNLOCK (src);
2519 
2520   return TRUE;
2521 
2522   /* ERRORS */
2523 unexpected_length:
2524   {
2525     GST_DEBUG_OBJECT (src, "processing at or past EOS");
2526     return FALSE;
2527   }
2528 }
2529 
2530 /* must be called with LIVE_LOCK */
2531 static GstFlowReturn
gst_base_src_get_range(GstBaseSrc * src,guint64 offset,guint length,GstBuffer ** buf)2532 gst_base_src_get_range (GstBaseSrc * src, guint64 offset, guint length,
2533     GstBuffer ** buf)
2534 {
2535   GstFlowReturn ret;
2536   GstBaseSrcClass *bclass;
2537   GstClockReturn status;
2538   GstBuffer *res_buf;
2539   GstBuffer *in_buf;
2540   gboolean own_res_buf;
2541 
2542   bclass = GST_BASE_SRC_GET_CLASS (src);
2543 
2544 again:
2545   if (src->is_live) {
2546     if (G_UNLIKELY (!src->live_running)) {
2547       ret = gst_base_src_wait_playing_unlocked (src);
2548       if (ret != GST_FLOW_OK)
2549         goto stopped;
2550     }
2551   }
2552 
2553   if (G_UNLIKELY (!GST_BASE_SRC_IS_STARTED (src)
2554           && !GST_BASE_SRC_IS_STARTING (src)))
2555     goto not_started;
2556 
2557   if (G_UNLIKELY (!bclass->create))
2558     goto no_function;
2559 
2560   if (G_UNLIKELY (!gst_base_src_update_length (src, offset, &length, FALSE)))
2561     goto unexpected_length;
2562 
2563   /* track position */
2564   GST_OBJECT_LOCK (src);
2565   if (src->segment.format == GST_FORMAT_BYTES)
2566     src->segment.position = offset;
2567   GST_OBJECT_UNLOCK (src);
2568 
2569   /* normally we don't count buffers */
2570   if (G_UNLIKELY (src->num_buffers_left >= 0)) {
2571     if (src->num_buffers_left == 0)
2572       goto reached_num_buffers;
2573     else
2574       src->num_buffers_left--;
2575   }
2576 
2577   /* don't enter the create function if a pending EOS event was set. For the
2578    * logic of the has_pending_eos, check the event function of this class. */
2579   if (G_UNLIKELY (g_atomic_int_get (&src->priv->has_pending_eos))) {
2580     src->priv->forced_eos = TRUE;
2581     goto eos;
2582   }
2583 
2584   GST_DEBUG_OBJECT (src,
2585       "calling create offset %" G_GUINT64_FORMAT " length %u, time %"
2586       G_GINT64_FORMAT, offset, length, src->segment.time);
2587 
2588   res_buf = in_buf = *buf;
2589   own_res_buf = (*buf == NULL);
2590 
2591   GST_LIVE_UNLOCK (src);
2592   ret = bclass->create (src, offset, length, &res_buf);
2593   GST_LIVE_LOCK (src);
2594 
2595 #ifdef OHOS_EXT_FUNC
2596   /**
2597    * ohos.ext.func.0033
2598    * Support reconnection after disconnection in gstcurl.
2599    */
2600   if (G_UNLIKELY (ret == GST_FLOW_RECONNECTION_TIMEOUT)) {
2601     return GST_FLOW_RECONNECTION_TIMEOUT;
2602   }
2603 #endif
2604 
2605   /* As we released the LIVE_LOCK, the state may have changed */
2606   if (src->is_live) {
2607     if (G_UNLIKELY (!src->live_running)) {
2608       GstFlowReturn wait_ret;
2609       wait_ret = gst_base_src_wait_playing_unlocked (src);
2610       if (wait_ret != GST_FLOW_OK) {
2611         if (ret == GST_FLOW_OK && own_res_buf)
2612           gst_buffer_unref (res_buf);
2613         ret = wait_ret;
2614         goto stopped;
2615       }
2616     }
2617   }
2618 
2619   /* The create function could be unlocked because we have a pending EOS. It's
2620    * possible that we have a valid buffer from create that we need to
2621    * discard when the create function returned _OK. */
2622   if (G_UNLIKELY (g_atomic_int_get (&src->priv->has_pending_eos))) {
2623     if (ret == GST_FLOW_OK) {
2624       if (own_res_buf)
2625         gst_buffer_unref (res_buf);
2626     }
2627     src->priv->forced_eos = TRUE;
2628     goto eos;
2629   }
2630 
2631   if (G_UNLIKELY (ret != GST_FLOW_OK))
2632     goto not_ok;
2633 
2634   /* fallback in case the create function didn't fill a provided buffer */
2635   if (in_buf != NULL && res_buf != in_buf) {
2636     GstMapInfo info;
2637     gsize copied_size;
2638 
2639     GST_CAT_DEBUG_OBJECT (GST_CAT_PERFORMANCE, src, "create function didn't "
2640         "fill the provided buffer, copying");
2641 
2642     if (!gst_buffer_map (in_buf, &info, GST_MAP_WRITE))
2643       goto map_failed;
2644 
2645     copied_size = gst_buffer_extract (res_buf, 0, info.data, info.size);
2646     gst_buffer_unmap (in_buf, &info);
2647     gst_buffer_set_size (in_buf, copied_size);
2648 
2649     gst_buffer_copy_into (in_buf, res_buf, GST_BUFFER_COPY_METADATA, 0, -1);
2650 
2651     gst_buffer_unref (res_buf);
2652     res_buf = in_buf;
2653   }
2654 
2655   if (res_buf == NULL) {
2656     GstBufferList *pending_list = src->priv->pending_bufferlist;
2657 
2658     if (pending_list == NULL || gst_buffer_list_length (pending_list) == 0)
2659       goto null_buffer;
2660 
2661     res_buf = gst_buffer_list_get_writable (pending_list, 0);
2662     own_res_buf = FALSE;
2663   }
2664 
2665   /* no timestamp set and we are at offset 0, we can timestamp with 0 */
2666   if (offset == 0 && src->segment.time == 0
2667       && GST_BUFFER_DTS (res_buf) == -1 && !src->is_live) {
2668     GST_DEBUG_OBJECT (src, "setting first timestamp to 0");
2669     res_buf = gst_buffer_make_writable (res_buf);
2670     GST_BUFFER_DTS (res_buf) = 0;
2671   }
2672 
2673   /* now sync before pushing the buffer */
2674   status = gst_base_src_do_sync (src, res_buf);
2675 
2676   /* waiting for the clock could have made us flushing */
2677   if (G_UNLIKELY (src->priv->flushing))
2678     goto flushing;
2679 
2680   switch (status) {
2681     case GST_CLOCK_EARLY:
2682       /* the buffer is too late. We currently don't drop the buffer. */
2683       GST_DEBUG_OBJECT (src, "buffer too late!, returning anyway");
2684       break;
2685     case GST_CLOCK_OK:
2686       /* buffer synchronised properly */
2687       GST_DEBUG_OBJECT (src, "buffer ok");
2688       break;
2689     case GST_CLOCK_UNSCHEDULED:
2690       /* this case is triggered when we were waiting for the clock and
2691        * it got unlocked because we did a state change. In any case, get rid of
2692        * the buffer. */
2693       if (own_res_buf)
2694         gst_buffer_unref (res_buf);
2695 
2696       if (!src->live_running) {
2697         /* We return FLUSHING when we are not running to stop the dataflow also
2698          * get rid of the produced buffer. */
2699         GST_DEBUG_OBJECT (src,
2700             "clock was unscheduled (%d), returning FLUSHING", status);
2701         ret = GST_FLOW_FLUSHING;
2702       } else {
2703         /* If we are running when this happens, we quickly switched between
2704          * pause and playing. We try to produce a new buffer */
2705         GST_DEBUG_OBJECT (src,
2706             "clock was unscheduled (%d), but we are running", status);
2707         goto again;
2708       }
2709       break;
2710     default:
2711       /* all other result values are unexpected and errors */
2712       GST_ELEMENT_ERROR (src, CORE, CLOCK,
2713           (_("Internal clock error.")),
2714           ("clock returned unexpected return value %d", status));
2715       if (own_res_buf)
2716         gst_buffer_unref (res_buf);
2717       ret = GST_FLOW_ERROR;
2718       break;
2719   }
2720   if (G_LIKELY (ret == GST_FLOW_OK))
2721     *buf = res_buf;
2722 
2723   return ret;
2724 
2725   /* ERROR */
2726 stopped:
2727   {
2728     GST_DEBUG_OBJECT (src, "wait_playing returned %d (%s)", ret,
2729         gst_flow_get_name (ret));
2730     return ret;
2731   }
2732 not_ok:
2733   {
2734     GST_DEBUG_OBJECT (src, "create returned %d (%s)", ret,
2735         gst_flow_get_name (ret));
2736     return ret;
2737   }
2738 map_failed:
2739   {
2740     GST_ELEMENT_ERROR (src, RESOURCE, BUSY,
2741         (_("Failed to map buffer.")),
2742         ("failed to map result buffer in WRITE mode"));
2743     if (own_res_buf)
2744       gst_buffer_unref (res_buf);
2745     return GST_FLOW_ERROR;
2746   }
2747 not_started:
2748   {
2749     GST_DEBUG_OBJECT (src, "getrange but not started");
2750     return GST_FLOW_FLUSHING;
2751   }
2752 no_function:
2753   {
2754     GST_DEBUG_OBJECT (src, "no create function");
2755     return GST_FLOW_NOT_SUPPORTED;
2756   }
2757 unexpected_length:
2758   {
2759     GST_DEBUG_OBJECT (src, "unexpected length %u (offset=%" G_GUINT64_FORMAT
2760         ", size=%" G_GINT64_FORMAT ")", length, offset, src->segment.duration);
2761     return GST_FLOW_EOS;
2762   }
2763 reached_num_buffers:
2764   {
2765     GST_DEBUG_OBJECT (src, "sent all buffers");
2766     return GST_FLOW_EOS;
2767   }
2768 flushing:
2769   {
2770     GST_DEBUG_OBJECT (src, "we are flushing");
2771     if (own_res_buf)
2772       gst_buffer_unref (res_buf);
2773     return GST_FLOW_FLUSHING;
2774   }
2775 eos:
2776   {
2777     GST_DEBUG_OBJECT (src, "we are EOS");
2778     return GST_FLOW_EOS;
2779   }
2780 null_buffer:
2781   {
2782     GST_ELEMENT_ERROR (src, STREAM, FAILED,
2783         (_("Internal data flow error.")),
2784         ("Subclass %s neither returned a buffer nor submitted a buffer list "
2785             "from its create function", G_OBJECT_TYPE_NAME (src)));
2786     return GST_FLOW_ERROR;
2787   }
2788 }
2789 
2790 static GstFlowReturn
gst_base_src_getrange(GstPad * pad,GstObject * parent,guint64 offset,guint length,GstBuffer ** buf)2791 gst_base_src_getrange (GstPad * pad, GstObject * parent, guint64 offset,
2792     guint length, GstBuffer ** buf)
2793 {
2794   GstBaseSrc *src;
2795   GstFlowReturn res;
2796 
2797   src = GST_BASE_SRC_CAST (parent);
2798 
2799   GST_LIVE_LOCK (src);
2800   if (G_UNLIKELY (src->priv->flushing))
2801     goto flushing;
2802 
2803 #ifdef OHOS_OPT_PERFORMANCE
2804 // ohos.opt.performance.0005
2805 // add trace
2806   {
2807     GstStartTrace("Src:get_range");
2808     res = gst_base_src_get_range (src, offset, length, buf);
2809     GstFinishTrace();
2810   }
2811 #else
2812   res = gst_base_src_get_range (src, offset, length, buf);
2813 #endif
2814 
2815 done:
2816   GST_LIVE_UNLOCK (src);
2817 
2818   return res;
2819 
2820   /* ERRORS */
2821 flushing:
2822   {
2823     GST_DEBUG_OBJECT (src, "we are flushing");
2824     res = GST_FLOW_FLUSHING;
2825     goto done;
2826   }
2827 }
2828 
2829 static gboolean
gst_base_src_is_random_access(GstBaseSrc * src)2830 gst_base_src_is_random_access (GstBaseSrc * src)
2831 {
2832   /* we need to start the basesrc to check random access */
2833   if (!GST_BASE_SRC_IS_STARTED (src)) {
2834     GST_LOG_OBJECT (src, "doing start/stop to check get_range support");
2835     if (G_LIKELY (gst_base_src_start (src))) {
2836       if (gst_base_src_start_wait (src) != GST_FLOW_OK)
2837         goto start_failed;
2838       gst_base_src_stop (src);
2839     }
2840   }
2841 
2842   return src->random_access;
2843 
2844   /* ERRORS */
2845 start_failed:
2846   {
2847     GST_DEBUG_OBJECT (src, "failed to start");
2848     return FALSE;
2849   }
2850 }
2851 
2852 /* Called with STREAM_LOCK */
2853 static void
gst_base_src_loop(GstPad * pad)2854 gst_base_src_loop (GstPad * pad)
2855 {
2856   GstBaseSrc *src;
2857   GstBuffer *buf = NULL;
2858   GstFlowReturn ret;
2859   gint64 position;
2860   gboolean eos;
2861   guint blocksize;
2862   GList *pending_events = NULL, *tmp;
2863 
2864   eos = FALSE;
2865 
2866   src = GST_BASE_SRC (GST_OBJECT_PARENT (pad));
2867 
2868   /* Just leave immediately if we're flushing */
2869   GST_LIVE_LOCK (src);
2870   if (G_UNLIKELY (src->priv->flushing || GST_PAD_IS_FLUSHING (pad)))
2871     goto flushing;
2872   GST_LIVE_UNLOCK (src);
2873 
2874   /* Just return if EOS is pushed again, as the app might be unaware that an
2875    * EOS have been sent already */
2876   if (GST_PAD_IS_EOS (pad)) {
2877     GST_DEBUG_OBJECT (src, "Pad is marked as EOS, pause the task");
2878     gst_pad_pause_task (pad);
2879     goto done;
2880   }
2881 
2882   gst_base_src_send_stream_start (src);
2883 
2884   /* The stream-start event could've caused something to flush us */
2885   GST_LIVE_LOCK (src);
2886   if (G_UNLIKELY (src->priv->flushing || GST_PAD_IS_FLUSHING (pad)))
2887     goto flushing;
2888   GST_LIVE_UNLOCK (src);
2889 
2890   /* check if we need to renegotiate */
2891   if (gst_pad_check_reconfigure (pad)) {
2892     if (!gst_base_src_negotiate_unlocked (src)) {
2893       gst_pad_mark_reconfigure (pad);
2894       if (GST_PAD_IS_FLUSHING (pad)) {
2895         GST_LIVE_LOCK (src);
2896         goto flushing;
2897       } else {
2898         goto negotiate_failed;
2899       }
2900     }
2901   }
2902 
2903   GST_LIVE_LOCK (src);
2904 
2905   if (G_UNLIKELY (src->priv->flushing || GST_PAD_IS_FLUSHING (pad)))
2906     goto flushing;
2907 
2908   blocksize = src->blocksize;
2909 
2910   /* if we operate in bytes, we can calculate an offset */
2911   if (src->segment.format == GST_FORMAT_BYTES) {
2912     position = src->segment.position;
2913     /* for negative rates, start with subtracting the blocksize */
2914     if (src->segment.rate < 0.0) {
2915       /* we cannot go below segment.start */
2916       if (position > src->segment.start + blocksize)
2917         position -= blocksize;
2918       else {
2919         /* last block, remainder up to segment.start */
2920         blocksize = position - src->segment.start;
2921         position = src->segment.start;
2922       }
2923     }
2924   } else
2925     position = -1;
2926 
2927   GST_LOG_OBJECT (src, "next_ts %" GST_TIME_FORMAT " size %u",
2928       GST_TIME_ARGS (position), blocksize);
2929 
2930   /* clean up just in case we got interrupted or so last time round */
2931   if (src->priv->pending_bufferlist != NULL) {
2932     gst_buffer_list_unref (src->priv->pending_bufferlist);
2933     src->priv->pending_bufferlist = NULL;
2934   }
2935 
2936 #ifdef OHOS_OPT_PERFORMANCE
2937 // ohos.opt.performance.0005
2938 // add trace
2939   {
2940     GstStartTrace("Src:get_range");
2941     ret = gst_base_src_get_range (src, position, blocksize, &buf);
2942     GstFinishTrace();
2943   }
2944 #else
2945   ret = gst_base_src_get_range (src, position, blocksize, &buf);
2946 #endif
2947 #ifdef OHOS_EXT_FUNC
2948   /**
2949    * ohos.ext.func.0033
2950    * Support reconnection after disconnection in gstcurl.
2951    */
2952   if (G_UNLIKELY (ret == GST_FLOW_RECONNECTION_TIMEOUT)) {
2953     GST_LIVE_UNLOCK (src);
2954     goto timeout;
2955   }
2956 #endif
2957 
2958   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2959     GST_INFO_OBJECT (src, "pausing after gst_base_src_get_range() = %s",
2960         gst_flow_get_name (ret));
2961     GST_LIVE_UNLOCK (src);
2962     goto pause;
2963   }
2964 
2965   /* Note: at this point buf might be a single buf returned which we own or
2966    * the first buf of a pending buffer list submitted via submit_buffer_list(),
2967    * in which case the buffer is owned by the pending buffer list and not us. */
2968   g_assert (buf != NULL);
2969 
2970   /* push events to close/start our segment before we push the buffer. */
2971   if (G_UNLIKELY (src->priv->segment_pending)) {
2972     GstEvent *seg_event = gst_event_new_segment (&src->segment);
2973 
2974     gst_event_set_seqnum (seg_event, src->priv->segment_seqnum);
2975     src->priv->segment_seqnum = gst_util_seqnum_next ();
2976     gst_pad_push_event (pad, seg_event);
2977     src->priv->segment_pending = FALSE;
2978   }
2979 
2980   if (g_atomic_int_get (&src->priv->have_events)) {
2981     GST_OBJECT_LOCK (src);
2982     /* take the events */
2983     pending_events = src->priv->pending_events;
2984     src->priv->pending_events = NULL;
2985     g_atomic_int_set (&src->priv->have_events, FALSE);
2986     GST_OBJECT_UNLOCK (src);
2987   }
2988 
2989   /* Push out pending events if any */
2990   if (G_UNLIKELY (pending_events != NULL)) {
2991     for (tmp = pending_events; tmp; tmp = g_list_next (tmp)) {
2992       GstEvent *ev = (GstEvent *) tmp->data;
2993       gst_pad_push_event (pad, ev);
2994     }
2995     g_list_free (pending_events);
2996   }
2997 
2998   /* figure out the new position */
2999   switch (src->segment.format) {
3000     case GST_FORMAT_BYTES:
3001     {
3002       guint bufsize = gst_buffer_get_size (buf);
3003 
3004       /* we subtracted above for negative rates */
3005       if (src->segment.rate >= 0.0)
3006         position += bufsize;
3007       break;
3008     }
3009     case GST_FORMAT_TIME:
3010     {
3011       GstClockTime start, duration;
3012 
3013       start = GST_BUFFER_TIMESTAMP (buf);
3014       duration = GST_BUFFER_DURATION (buf);
3015 
3016       if (GST_CLOCK_TIME_IS_VALID (start))
3017         position = start;
3018       else
3019         position = src->segment.position;
3020 
3021       if (GST_CLOCK_TIME_IS_VALID (duration)) {
3022         if (src->segment.rate >= 0.0)
3023           position += duration;
3024       }
3025       break;
3026     }
3027     case GST_FORMAT_DEFAULT:
3028       if (src->segment.rate >= 0.0)
3029         position = GST_BUFFER_OFFSET_END (buf);
3030       else
3031         position = GST_BUFFER_OFFSET (buf);
3032       break;
3033     default:
3034       position = -1;
3035       break;
3036   }
3037   if (position != -1) {
3038     if (src->segment.rate >= 0.0) {
3039       /* positive rate, check if we reached the stop */
3040       if (src->segment.stop != -1) {
3041         if (position >= src->segment.stop) {
3042           if (g_atomic_int_get (&src->priv->automatic_eos))
3043             eos = TRUE;
3044           position = src->segment.stop;
3045         }
3046       }
3047     } else {
3048       /* negative rate, check if we reached the start. start is always set to
3049        * something different from -1 */
3050       if (position <= src->segment.start) {
3051         if (g_atomic_int_get (&src->priv->automatic_eos))
3052           eos = TRUE;
3053         position = src->segment.start;
3054       }
3055       /* when going reverse, all buffers are DISCONT */
3056       src->priv->discont = TRUE;
3057     }
3058     GST_OBJECT_LOCK (src);
3059     src->segment.position = position;
3060     GST_OBJECT_UNLOCK (src);
3061   }
3062 
3063   if (G_UNLIKELY (src->priv->discont)) {
3064     GST_INFO_OBJECT (src, "marking pending DISCONT");
3065     buf = gst_buffer_make_writable (buf);
3066     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
3067     src->priv->discont = FALSE;
3068   }
3069   GST_LIVE_UNLOCK (src);
3070 
3071   /* push buffer or buffer list */
3072   if (src->priv->pending_bufferlist != NULL) {
3073     ret = gst_pad_push_list (pad, src->priv->pending_bufferlist);
3074     src->priv->pending_bufferlist = NULL;
3075   } else {
3076     ret = gst_pad_push (pad, buf);
3077   }
3078 
3079   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
3080     if (ret == GST_FLOW_NOT_NEGOTIATED) {
3081       goto not_negotiated;
3082     }
3083     GST_INFO_OBJECT (src, "pausing after gst_pad_push() = %s",
3084         gst_flow_get_name (ret));
3085     goto pause;
3086   }
3087 
3088   /* Segment pending means that a new segment was configured
3089    * during this loop run */
3090   if (G_UNLIKELY (eos && !src->priv->segment_pending)) {
3091     GST_INFO_OBJECT (src, "pausing after end of segment");
3092     ret = GST_FLOW_EOS;
3093     goto pause;
3094   }
3095 
3096 done:
3097   return;
3098 
3099   /* special cases */
3100 not_negotiated:
3101   {
3102     if (gst_pad_needs_reconfigure (pad)) {
3103       GST_DEBUG_OBJECT (src, "Retrying to renegotiate");
3104       return;
3105     }
3106     /* fallthrough when push returns NOT_NEGOTIATED and we don't have
3107      * a pending negotiation request on our srcpad */
3108   }
3109 negotiate_failed:
3110   {
3111     GST_DEBUG_OBJECT (src, "Not negotiated");
3112     ret = GST_FLOW_NOT_NEGOTIATED;
3113 /*
3114  * ohos.ext.func.0003: Errors need to be reported when negotiation fails.
3115  */
3116 #ifdef OHOS_EXT_FUNC
3117       GST_ELEMENT_FLOW_ERROR (src, ret);
3118 #endif
3119     goto pause;
3120   }
3121 flushing:
3122   {
3123     GST_DEBUG_OBJECT (src, "we are flushing");
3124     GST_LIVE_UNLOCK (src);
3125     ret = GST_FLOW_FLUSHING;
3126     goto pause;
3127   }
3128 pause:
3129   {
3130     GstEvent *event;
3131 
3132     GST_DEBUG_OBJECT (src, "pausing task, reason %s", gst_flow_get_name (ret));
3133     src->running = FALSE;
3134     gst_pad_pause_task (pad);
3135     if (ret == GST_FLOW_EOS) {
3136       gboolean flag_segment;
3137       GstFormat format;
3138       gint64 position;
3139 
3140       flag_segment = (src->segment.flags & GST_SEGMENT_FLAG_SEGMENT) != 0;
3141       format = src->segment.format;
3142       position = src->segment.position;
3143 
3144       /* perform EOS logic */
3145       if (src->priv->forced_eos) {
3146         g_assert (g_atomic_int_get (&src->priv->has_pending_eos));
3147         GST_OBJECT_LOCK (src);
3148         event = src->priv->pending_eos;
3149         src->priv->pending_eos = NULL;
3150         GST_OBJECT_UNLOCK (src);
3151 
3152       } else if (flag_segment) {
3153         GstMessage *message;
3154 
3155         message = gst_message_new_segment_done (GST_OBJECT_CAST (src),
3156             format, position);
3157         gst_message_set_seqnum (message, src->priv->seqnum);
3158         gst_element_post_message (GST_ELEMENT_CAST (src), message);
3159         event = gst_event_new_segment_done (format, position);
3160         gst_event_set_seqnum (event, src->priv->seqnum);
3161 
3162       } else {
3163         event = gst_event_new_eos ();
3164         gst_event_set_seqnum (event, src->priv->seqnum);
3165       }
3166 
3167       gst_pad_push_event (pad, event);
3168       src->priv->forced_eos = FALSE;
3169 
3170     } else if (ret == GST_FLOW_NOT_LINKED || ret <= GST_FLOW_EOS) {
3171       event = gst_event_new_eos ();
3172       gst_event_set_seqnum (event, src->priv->seqnum);
3173 
3174 /* ohos.ext.func.0003: The media recorder service must support bypassing the abnormal streams to continue
3175  * recording normal streams. However, the gstpipeline cannot work properly if an error message is reported.
3176  * Some error messages are changed to warning messages. Then the media recording service can detects abnormal
3177  * streams by matching expected warning messages.
3178  */
3179 #ifdef OHOS_EXT_FUNC
3180       GST_ELEMENT_WARNING_WITH_DETAILS (src, STREAM, FAILED, ("Internal data stream error."),
3181         ("streaming stopped, reason %s (%d)", gst_flow_get_name (ret), ret),
3182         ("flow-return", G_TYPE_INT, ret, NULL));
3183 #else
3184       /* for fatal errors we post an error message, post the error
3185        * first so the app knows about the error first.
3186        * Also don't do this for FLUSHING because it happens
3187        * due to flushing and posting an error message because of
3188        * that is the wrong thing to do, e.g. when we're doing
3189        * a flushing seek. */
3190       GST_ELEMENT_FLOW_ERROR (src, ret);
3191 #endif
3192       gst_pad_push_event (pad, event);
3193     }
3194     goto done;
3195   }
3196 #ifdef OHOS_EXT_FUNC
3197   /**
3198    * ohos.ext.func.0033
3199    * Support reconnection after disconnection in gstcurl.
3200    * Do not push eos when reconnection timeout.
3201    */
3202   timeout:
3203   {
3204     GST_DEBUG_OBJECT (src, "reconnection timeout, pausing task");
3205     src->running = FALSE;
3206     gst_pad_pause_task (pad);
3207     goto done;
3208   }
3209 #endif
3210 }
3211 
3212 static gboolean
gst_base_src_set_allocation(GstBaseSrc * basesrc,GstBufferPool * pool,GstAllocator * allocator,const GstAllocationParams * params)3213 gst_base_src_set_allocation (GstBaseSrc * basesrc, GstBufferPool * pool,
3214     GstAllocator * allocator, const GstAllocationParams * params)
3215 {
3216   GstAllocator *oldalloc;
3217   GstBufferPool *oldpool;
3218   GstBaseSrcPrivate *priv = basesrc->priv;
3219 
3220   if (pool) {
3221     GST_DEBUG_OBJECT (basesrc, "activate pool");
3222     if (!gst_buffer_pool_set_active (pool, TRUE))
3223       goto activate_failed;
3224   }
3225 
3226   GST_OBJECT_LOCK (basesrc);
3227   oldpool = priv->pool;
3228   priv->pool = pool;
3229 
3230   oldalloc = priv->allocator;
3231   priv->allocator = allocator;
3232 
3233   if (priv->pool)
3234     gst_object_ref (priv->pool);
3235   if (priv->allocator)
3236     gst_object_ref (priv->allocator);
3237 
3238   if (params)
3239     priv->params = *params;
3240   else
3241     gst_allocation_params_init (&priv->params);
3242   GST_OBJECT_UNLOCK (basesrc);
3243 
3244   if (oldpool) {
3245     /* only deactivate if the pool is not the one we're using */
3246     if (oldpool != pool) {
3247       GST_DEBUG_OBJECT (basesrc, "deactivate old pool");
3248       gst_buffer_pool_set_active (oldpool, FALSE);
3249     }
3250     gst_object_unref (oldpool);
3251   }
3252   if (oldalloc) {
3253     gst_object_unref (oldalloc);
3254   }
3255   return TRUE;
3256 
3257   /* ERRORS */
3258 activate_failed:
3259   {
3260     GST_ERROR_OBJECT (basesrc, "failed to activate bufferpool.");
3261     return FALSE;
3262   }
3263 }
3264 
3265 static void
gst_base_src_set_pool_flushing(GstBaseSrc * basesrc,gboolean flushing)3266 gst_base_src_set_pool_flushing (GstBaseSrc * basesrc, gboolean flushing)
3267 {
3268   GstBaseSrcPrivate *priv = basesrc->priv;
3269   GstBufferPool *pool;
3270 
3271   GST_OBJECT_LOCK (basesrc);
3272   if ((pool = priv->pool))
3273     pool = gst_object_ref (pool);
3274   GST_OBJECT_UNLOCK (basesrc);
3275 
3276   if (pool) {
3277     gst_buffer_pool_set_flushing (pool, flushing);
3278     gst_object_unref (pool);
3279   }
3280 }
3281 
3282 
3283 static gboolean
gst_base_src_decide_allocation_default(GstBaseSrc * basesrc,GstQuery * query)3284 gst_base_src_decide_allocation_default (GstBaseSrc * basesrc, GstQuery * query)
3285 {
3286   GstCaps *outcaps;
3287   GstBufferPool *pool;
3288   guint size, min, max;
3289   GstAllocator *allocator;
3290   GstAllocationParams params;
3291   GstStructure *config;
3292   gboolean update_allocator;
3293 
3294   gst_query_parse_allocation (query, &outcaps, NULL);
3295 
3296   /* we got configuration from our peer or the decide_allocation method,
3297    * parse them */
3298   if (gst_query_get_n_allocation_params (query) > 0) {
3299     /* try the allocator */
3300     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
3301     update_allocator = TRUE;
3302   } else {
3303     allocator = NULL;
3304     gst_allocation_params_init (&params);
3305     update_allocator = FALSE;
3306   }
3307 
3308   if (gst_query_get_n_allocation_pools (query) > 0) {
3309     gst_query_parse_nth_allocation_pool (query, 0, &pool, &size, &min, &max);
3310 
3311     if (pool == NULL) {
3312       /* no pool, we can make our own */
3313       GST_DEBUG_OBJECT (basesrc, "no pool, making new pool");
3314       pool = gst_buffer_pool_new ();
3315     }
3316   } else {
3317     pool = NULL;
3318     size = min = max = 0;
3319   }
3320 
3321   /* now configure */
3322   if (pool) {
3323     config = gst_buffer_pool_get_config (pool);
3324     gst_buffer_pool_config_set_params (config, outcaps, size, min, max);
3325     gst_buffer_pool_config_set_allocator (config, allocator, &params);
3326 
3327     /* buffer pool may have to do some changes */
3328     if (!gst_buffer_pool_set_config (pool, config)) {
3329       config = gst_buffer_pool_get_config (pool);
3330 
3331       /* If change are not acceptable, fallback to generic pool */
3332       if (!gst_buffer_pool_config_validate_params (config, outcaps, size, min,
3333               max)) {
3334         GST_DEBUG_OBJECT (basesrc, "unsupported pool, making new pool");
3335 
3336         gst_object_unref (pool);
3337         pool = gst_buffer_pool_new ();
3338         gst_buffer_pool_config_set_params (config, outcaps, size, min, max);
3339         gst_buffer_pool_config_set_allocator (config, allocator, &params);
3340       }
3341 
3342       if (!gst_buffer_pool_set_config (pool, config))
3343         goto config_failed;
3344     }
3345   }
3346 
3347   if (update_allocator)
3348     gst_query_set_nth_allocation_param (query, 0, allocator, &params);
3349   else
3350     gst_query_add_allocation_param (query, allocator, &params);
3351   if (allocator)
3352     gst_object_unref (allocator);
3353 
3354   if (pool) {
3355     gst_query_set_nth_allocation_pool (query, 0, pool, size, min, max);
3356     gst_object_unref (pool);
3357   }
3358 
3359   return TRUE;
3360 
3361 config_failed:
3362   GST_ELEMENT_ERROR (basesrc, RESOURCE, SETTINGS,
3363       ("Failed to configure the buffer pool"),
3364       ("Configuration is most likely invalid, please report this issue."));
3365   gst_object_unref (pool);
3366   return FALSE;
3367 }
3368 
3369 static gboolean
gst_base_src_prepare_allocation(GstBaseSrc * basesrc,GstCaps * caps)3370 gst_base_src_prepare_allocation (GstBaseSrc * basesrc, GstCaps * caps)
3371 {
3372   GstBaseSrcClass *bclass;
3373   gboolean result = TRUE;
3374   GstQuery *query;
3375   GstBufferPool *pool = NULL;
3376   GstAllocator *allocator = NULL;
3377   GstAllocationParams params;
3378 
3379   bclass = GST_BASE_SRC_GET_CLASS (basesrc);
3380 
3381   /* make query and let peer pad answer, we don't really care if it worked or
3382    * not, if it failed, the allocation query would contain defaults and the
3383    * subclass would then set better values if needed */
3384   query = gst_query_new_allocation (caps, TRUE);
3385   if (!gst_pad_peer_query (basesrc->srcpad, query)) {
3386     /* not a problem, just debug a little */
3387     GST_DEBUG_OBJECT (basesrc, "peer ALLOCATION query failed");
3388   }
3389 
3390   g_assert (bclass->decide_allocation != NULL);
3391   result = bclass->decide_allocation (basesrc, query);
3392 
3393   GST_DEBUG_OBJECT (basesrc, "ALLOCATION (%d) params: %" GST_PTR_FORMAT, result,
3394       query);
3395 
3396   if (!result)
3397     goto no_decide_allocation;
3398 
3399   /* we got configuration from our peer or the decide_allocation method,
3400    * parse them */
3401   if (gst_query_get_n_allocation_params (query) > 0) {
3402     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
3403   } else {
3404     allocator = NULL;
3405     gst_allocation_params_init (&params);
3406   }
3407 
3408   if (gst_query_get_n_allocation_pools (query) > 0)
3409     gst_query_parse_nth_allocation_pool (query, 0, &pool, NULL, NULL, NULL);
3410 
3411   result = gst_base_src_set_allocation (basesrc, pool, allocator, &params);
3412 
3413   if (allocator)
3414     gst_object_unref (allocator);
3415   if (pool)
3416     gst_object_unref (pool);
3417 
3418   gst_query_unref (query);
3419 
3420   return result;
3421 
3422   /* Errors */
3423 no_decide_allocation:
3424   {
3425     GST_WARNING_OBJECT (basesrc, "Subclass failed to decide allocation");
3426     gst_query_unref (query);
3427 
3428     return result;
3429   }
3430 }
3431 
3432 /* default negotiation code.
3433  *
3434  * Take intersection between src and sink pads, take first
3435  * caps and fixate.
3436  */
3437 static gboolean
gst_base_src_default_negotiate(GstBaseSrc * basesrc)3438 gst_base_src_default_negotiate (GstBaseSrc * basesrc)
3439 {
3440   GstCaps *thiscaps;
3441   GstCaps *caps = NULL;
3442   GstCaps *peercaps = NULL;
3443   gboolean result = FALSE;
3444 
3445   /* first see what is possible on our source pad */
3446   thiscaps = gst_pad_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
3447   GST_DEBUG_OBJECT (basesrc, "caps of src: %" GST_PTR_FORMAT, thiscaps);
3448   /* nothing or anything is allowed, we're done */
3449   if (thiscaps == NULL || gst_caps_is_any (thiscaps))
3450     goto no_nego_needed;
3451 
3452   if (G_UNLIKELY (gst_caps_is_empty (thiscaps)))
3453     goto no_caps;
3454 
3455   /* get the peer caps */
3456   peercaps = gst_pad_peer_query_caps (GST_BASE_SRC_PAD (basesrc), thiscaps);
3457   GST_DEBUG_OBJECT (basesrc, "caps of peer: %" GST_PTR_FORMAT, peercaps);
3458   if (peercaps) {
3459     /* The result is already a subset of our caps */
3460     caps = peercaps;
3461     gst_caps_unref (thiscaps);
3462   } else {
3463     /* no peer, work with our own caps then */
3464     caps = thiscaps;
3465   }
3466   if (caps && !gst_caps_is_empty (caps)) {
3467     /* now fixate */
3468     GST_DEBUG_OBJECT (basesrc, "have caps: %" GST_PTR_FORMAT, caps);
3469     if (gst_caps_is_any (caps)) {
3470       GST_DEBUG_OBJECT (basesrc, "any caps, we stop");
3471       /* hmm, still anything, so element can do anything and
3472        * nego is not needed */
3473       result = TRUE;
3474     } else {
3475       caps = gst_base_src_fixate (basesrc, caps);
3476       GST_DEBUG_OBJECT (basesrc, "fixated to: %" GST_PTR_FORMAT, caps);
3477       if (gst_caps_is_fixed (caps)) {
3478         /* yay, fixed caps, use those then, it's possible that the subclass does
3479          * not accept this caps after all and we have to fail. */
3480         result = gst_base_src_set_caps (basesrc, caps);
3481       }
3482     }
3483     gst_caps_unref (caps);
3484   } else {
3485     if (caps)
3486       gst_caps_unref (caps);
3487     GST_DEBUG_OBJECT (basesrc, "no common caps");
3488   }
3489   return result;
3490 
3491 no_nego_needed:
3492   {
3493     GST_DEBUG_OBJECT (basesrc, "no negotiation needed");
3494     if (thiscaps)
3495       gst_caps_unref (thiscaps);
3496     return TRUE;
3497   }
3498 no_caps:
3499   {
3500     GST_ELEMENT_ERROR (basesrc, STREAM, FORMAT,
3501         ("No supported formats found"),
3502         ("This element did not produce valid caps"));
3503     if (thiscaps)
3504       gst_caps_unref (thiscaps);
3505     return TRUE;
3506   }
3507 }
3508 
3509 static gboolean
gst_base_src_negotiate_unlocked(GstBaseSrc * basesrc)3510 gst_base_src_negotiate_unlocked (GstBaseSrc * basesrc)
3511 {
3512   GstBaseSrcClass *bclass;
3513   gboolean result;
3514 
3515   bclass = GST_BASE_SRC_GET_CLASS (basesrc);
3516 
3517   GST_DEBUG_OBJECT (basesrc, "starting negotiation");
3518 
3519   if (G_LIKELY (bclass->negotiate))
3520     result = bclass->negotiate (basesrc);
3521   else
3522     result = TRUE;
3523 
3524   if (G_LIKELY (result)) {
3525     GstCaps *caps;
3526 
3527     caps = gst_pad_get_current_caps (basesrc->srcpad);
3528 
3529     result = gst_base_src_prepare_allocation (basesrc, caps);
3530 
3531     if (caps)
3532       gst_caps_unref (caps);
3533   }
3534   return result;
3535 }
3536 
3537 /**
3538  * gst_base_src_negotiate:
3539  * @src: base source instance
3540  *
3541  * Negotiates src pad caps with downstream elements.
3542  * Unmarks GST_PAD_FLAG_NEED_RECONFIGURE in any case. But marks it again
3543  * if #GstBaseSrcClass::negotiate fails.
3544  *
3545  * Do not call this in the #GstBaseSrcClass::fill vmethod. Call this in
3546  * #GstBaseSrcClass::create or in #GstBaseSrcClass::alloc, _before_ any
3547  * buffer is allocated.
3548  *
3549  * Returns: %TRUE if the negotiation succeeded, else %FALSE.
3550  *
3551  * Since: 1.18
3552  */
3553 gboolean
gst_base_src_negotiate(GstBaseSrc * src)3554 gst_base_src_negotiate (GstBaseSrc * src)
3555 {
3556   gboolean ret = TRUE;
3557 
3558   g_return_val_if_fail (GST_IS_BASE_SRC (src), FALSE);
3559 
3560   GST_PAD_STREAM_LOCK (src->srcpad);
3561   gst_pad_check_reconfigure (src->srcpad);
3562   ret = gst_base_src_negotiate_unlocked (src);
3563   if (!ret)
3564     gst_pad_mark_reconfigure (src->srcpad);
3565   GST_PAD_STREAM_UNLOCK (src->srcpad);
3566 
3567   return ret;
3568 }
3569 
3570 static gboolean
gst_base_src_start(GstBaseSrc * basesrc)3571 gst_base_src_start (GstBaseSrc * basesrc)
3572 {
3573   GstBaseSrcClass *bclass;
3574   gboolean result;
3575 
3576   GST_LIVE_LOCK (basesrc);
3577 
3578   GST_OBJECT_LOCK (basesrc);
3579   if (GST_BASE_SRC_IS_STARTING (basesrc))
3580     goto was_starting;
3581   if (GST_BASE_SRC_IS_STARTED (basesrc))
3582     goto was_started;
3583 
3584   basesrc->priv->start_result = GST_FLOW_FLUSHING;
3585   GST_OBJECT_FLAG_SET (basesrc, GST_BASE_SRC_FLAG_STARTING);
3586   gst_segment_init (&basesrc->segment, basesrc->segment.format);
3587   GST_OBJECT_UNLOCK (basesrc);
3588 
3589   basesrc->num_buffers_left = basesrc->num_buffers;
3590   basesrc->running = FALSE;
3591   basesrc->priv->segment_pending = FALSE;
3592   basesrc->priv->segment_seqnum = gst_util_seqnum_next ();
3593   basesrc->priv->forced_eos = FALSE;
3594   GST_LIVE_UNLOCK (basesrc);
3595 
3596   bclass = GST_BASE_SRC_GET_CLASS (basesrc);
3597   if (bclass->start)
3598     result = bclass->start (basesrc);
3599   else
3600     result = TRUE;
3601 
3602   if (!result)
3603     goto could_not_start;
3604 
3605   if (!gst_base_src_is_async (basesrc)) {
3606     gst_base_src_start_complete (basesrc, GST_FLOW_OK);
3607     /* not really waiting here, we call this to get the result
3608      * from the start_complete call */
3609     result = gst_base_src_start_wait (basesrc) == GST_FLOW_OK;
3610   }
3611 
3612   return result;
3613 
3614   /* ERROR */
3615 was_starting:
3616   {
3617     GST_DEBUG_OBJECT (basesrc, "was starting");
3618     GST_OBJECT_UNLOCK (basesrc);
3619     GST_LIVE_UNLOCK (basesrc);
3620     return TRUE;
3621   }
3622 was_started:
3623   {
3624     GST_DEBUG_OBJECT (basesrc, "was started");
3625     GST_OBJECT_UNLOCK (basesrc);
3626     GST_LIVE_UNLOCK (basesrc);
3627     return TRUE;
3628   }
3629 could_not_start:
3630   {
3631     GST_DEBUG_OBJECT (basesrc, "could not start");
3632     /* subclass is supposed to post a message but we post one as a fallback
3633      * just in case. We don't have to call _stop. */
3634     GST_ELEMENT_ERROR (basesrc, CORE, STATE_CHANGE, (NULL),
3635         ("Failed to start"));
3636     gst_base_src_start_complete (basesrc, GST_FLOW_ERROR);
3637     return FALSE;
3638   }
3639 }
3640 
3641 /**
3642  * gst_base_src_start_complete:
3643  * @basesrc: base source instance
3644  * @ret: a #GstFlowReturn
3645  *
3646  * Complete an asynchronous start operation. When the subclass overrides the
3647  * start method, it should call gst_base_src_start_complete() when the start
3648  * operation completes either from the same thread or from an asynchronous
3649  * helper thread.
3650  */
3651 void
gst_base_src_start_complete(GstBaseSrc * basesrc,GstFlowReturn ret)3652 gst_base_src_start_complete (GstBaseSrc * basesrc, GstFlowReturn ret)
3653 {
3654   gboolean have_size;
3655   guint64 size;
3656   gboolean seekable;
3657   GstFormat format;
3658   GstPadMode mode;
3659   GstEvent *event;
3660 
3661   if (ret != GST_FLOW_OK)
3662     goto error;
3663 
3664   GST_DEBUG_OBJECT (basesrc, "starting source");
3665   format = basesrc->segment.format;
3666 
3667   /* figure out the size */
3668   have_size = FALSE;
3669   size = -1;
3670   if (format == GST_FORMAT_BYTES) {
3671     GstBaseSrcClass *bclass = GST_BASE_SRC_GET_CLASS (basesrc);
3672 
3673     if (bclass->get_size) {
3674       if (!(have_size = bclass->get_size (basesrc, &size)))
3675         size = -1;
3676     }
3677     GST_DEBUG_OBJECT (basesrc, "setting size %" G_GUINT64_FORMAT, size);
3678     /* only update the size when operating in bytes, subclass is supposed
3679      * to set duration in the start method for other formats */
3680     GST_OBJECT_LOCK (basesrc);
3681     basesrc->segment.duration = size;
3682     GST_OBJECT_UNLOCK (basesrc);
3683   }
3684 
3685   GST_DEBUG_OBJECT (basesrc,
3686       "format: %s, have size: %d, size: %" G_GUINT64_FORMAT ", duration: %"
3687       G_GINT64_FORMAT, gst_format_get_name (format), have_size, size,
3688       basesrc->segment.duration);
3689 
3690   seekable = gst_base_src_seekable (basesrc);
3691   GST_DEBUG_OBJECT (basesrc, "is seekable: %d", seekable);
3692 
3693   /* update for random access flag */
3694   basesrc->random_access = seekable && format == GST_FORMAT_BYTES;
3695 
3696   GST_DEBUG_OBJECT (basesrc, "is random_access: %d", basesrc->random_access);
3697 
3698   gst_pad_mark_reconfigure (GST_BASE_SRC_PAD (basesrc));
3699 
3700   GST_OBJECT_LOCK (basesrc->srcpad);
3701   mode = GST_PAD_MODE (basesrc->srcpad);
3702   GST_OBJECT_UNLOCK (basesrc->srcpad);
3703 
3704   /* take the stream lock here, we only want to let the task run when we have
3705    * set the STARTED flag */
3706   GST_PAD_STREAM_LOCK (basesrc->srcpad);
3707   switch (mode) {
3708     case GST_PAD_MODE_PUSH:
3709       /* do initial seek, which will start the task */
3710       GST_OBJECT_LOCK (basesrc);
3711       event = basesrc->pending_seek;
3712       basesrc->pending_seek = NULL;
3713       GST_OBJECT_UNLOCK (basesrc);
3714 
3715       /* The perform seek code will start the task when finished. We don't have to
3716        * unlock the streaming thread because it is not running yet */
3717       if (G_UNLIKELY (!gst_base_src_perform_seek (basesrc, event, FALSE)))
3718         goto seek_failed;
3719 
3720       if (event)
3721         gst_event_unref (event);
3722       break;
3723     case GST_PAD_MODE_PULL:
3724       /* if not random_access, we cannot operate in pull mode for now */
3725       if (G_UNLIKELY (!basesrc->random_access))
3726         goto no_get_range;
3727       break;
3728     default:
3729       goto not_activated_yet;
3730       break;
3731   }
3732 
3733   GST_OBJECT_LOCK (basesrc);
3734   GST_OBJECT_FLAG_SET (basesrc, GST_BASE_SRC_FLAG_STARTED);
3735   GST_OBJECT_FLAG_UNSET (basesrc, GST_BASE_SRC_FLAG_STARTING);
3736   basesrc->priv->start_result = ret;
3737   GST_ASYNC_SIGNAL (basesrc);
3738   GST_OBJECT_UNLOCK (basesrc);
3739 
3740   GST_PAD_STREAM_UNLOCK (basesrc->srcpad);
3741 
3742   return;
3743 
3744 seek_failed:
3745   {
3746     GST_PAD_STREAM_UNLOCK (basesrc->srcpad);
3747     GST_ERROR_OBJECT (basesrc, "Failed to perform initial seek");
3748     gst_base_src_stop (basesrc);
3749     if (event)
3750       gst_event_unref (event);
3751     ret = GST_FLOW_ERROR;
3752     goto error;
3753   }
3754 no_get_range:
3755   {
3756     GST_PAD_STREAM_UNLOCK (basesrc->srcpad);
3757     gst_base_src_stop (basesrc);
3758     GST_ERROR_OBJECT (basesrc, "Cannot operate in pull mode, stopping");
3759     ret = GST_FLOW_ERROR;
3760     goto error;
3761   }
3762 not_activated_yet:
3763   {
3764     GST_PAD_STREAM_UNLOCK (basesrc->srcpad);
3765     gst_base_src_stop (basesrc);
3766     GST_WARNING_OBJECT (basesrc, "pad not activated yet");
3767     ret = GST_FLOW_ERROR;
3768     goto error;
3769   }
3770 error:
3771   {
3772     GST_OBJECT_LOCK (basesrc);
3773     basesrc->priv->start_result = ret;
3774     GST_OBJECT_FLAG_UNSET (basesrc, GST_BASE_SRC_FLAG_STARTING);
3775     GST_ASYNC_SIGNAL (basesrc);
3776     GST_OBJECT_UNLOCK (basesrc);
3777     return;
3778   }
3779 }
3780 
3781 /**
3782  * gst_base_src_start_wait:
3783  * @basesrc: base source instance
3784  *
3785  * Wait until the start operation completes.
3786  *
3787  * Returns: a #GstFlowReturn.
3788  */
3789 GstFlowReturn
gst_base_src_start_wait(GstBaseSrc * basesrc)3790 gst_base_src_start_wait (GstBaseSrc * basesrc)
3791 {
3792   GstFlowReturn result;
3793 
3794   GST_OBJECT_LOCK (basesrc);
3795   while (GST_BASE_SRC_IS_STARTING (basesrc)) {
3796     GST_ASYNC_WAIT (basesrc);
3797   }
3798   result = basesrc->priv->start_result;
3799   GST_OBJECT_UNLOCK (basesrc);
3800 
3801   GST_DEBUG_OBJECT (basesrc, "got %s", gst_flow_get_name (result));
3802 
3803   return result;
3804 }
3805 
3806 static gboolean
gst_base_src_stop(GstBaseSrc * basesrc)3807 gst_base_src_stop (GstBaseSrc * basesrc)
3808 {
3809   GstBaseSrcClass *bclass;
3810   gboolean result = TRUE;
3811 
3812   GST_DEBUG_OBJECT (basesrc, "stopping source");
3813 
3814   /* flush all */
3815   gst_base_src_set_flushing (basesrc, TRUE);
3816 
3817   /* stop the task */
3818   gst_pad_stop_task (basesrc->srcpad);
3819   /* stop flushing, this will balance unlock/unlock_stop calls */
3820   gst_base_src_set_flushing (basesrc, FALSE);
3821 
3822   GST_OBJECT_LOCK (basesrc);
3823   if (!GST_BASE_SRC_IS_STARTED (basesrc) && !GST_BASE_SRC_IS_STARTING (basesrc))
3824     goto was_stopped;
3825 
3826   GST_OBJECT_FLAG_UNSET (basesrc, GST_BASE_SRC_FLAG_STARTING);
3827   GST_OBJECT_FLAG_UNSET (basesrc, GST_BASE_SRC_FLAG_STARTED);
3828   basesrc->priv->start_result = GST_FLOW_FLUSHING;
3829   GST_ASYNC_SIGNAL (basesrc);
3830   GST_OBJECT_UNLOCK (basesrc);
3831 
3832   bclass = GST_BASE_SRC_GET_CLASS (basesrc);
3833   if (bclass->stop)
3834     result = bclass->stop (basesrc);
3835 
3836   if (basesrc->priv->pending_bufferlist != NULL) {
3837     gst_buffer_list_unref (basesrc->priv->pending_bufferlist);
3838     basesrc->priv->pending_bufferlist = NULL;
3839   }
3840 
3841   gst_base_src_set_allocation (basesrc, NULL, NULL, NULL);
3842 
3843   return result;
3844 
3845 was_stopped:
3846   {
3847     GST_DEBUG_OBJECT (basesrc, "was stopped");
3848     GST_OBJECT_UNLOCK (basesrc);
3849     return TRUE;
3850   }
3851 }
3852 
3853 /* start or stop flushing dataprocessing
3854  */
3855 static gboolean
gst_base_src_set_flushing(GstBaseSrc * basesrc,gboolean flushing)3856 gst_base_src_set_flushing (GstBaseSrc * basesrc, gboolean flushing)
3857 {
3858   GstBaseSrcClass *bclass;
3859 
3860   bclass = GST_BASE_SRC_GET_CLASS (basesrc);
3861 
3862   GST_DEBUG_OBJECT (basesrc, "flushing %d", flushing);
3863 
3864   if (flushing) {
3865     gst_base_src_set_pool_flushing (basesrc, TRUE);
3866     /* unlock any subclasses to allow turning off the streaming thread */
3867     if (bclass->unlock)
3868       bclass->unlock (basesrc);
3869   }
3870 
3871   /* the live lock is released when we are blocked, waiting for playing,
3872    * when we sync to the clock or creating a buffer */
3873   GST_LIVE_LOCK (basesrc);
3874   basesrc->priv->flushing = flushing;
3875   if (flushing) {
3876     /* clear pending EOS if any */
3877     if (g_atomic_int_get (&basesrc->priv->has_pending_eos)) {
3878       GST_OBJECT_LOCK (basesrc);
3879       CLEAR_PENDING_EOS (basesrc);
3880       basesrc->priv->forced_eos = FALSE;
3881       GST_OBJECT_UNLOCK (basesrc);
3882     }
3883 
3884     /* unblock clock sync (if any) or any other blocking thing */
3885     if (basesrc->clock_id)
3886       gst_clock_id_unschedule (basesrc->clock_id);
3887   } else {
3888     gst_base_src_set_pool_flushing (basesrc, FALSE);
3889 
3890     /* Drop all delayed events */
3891     GST_OBJECT_LOCK (basesrc);
3892     if (basesrc->priv->pending_events) {
3893       g_list_foreach (basesrc->priv->pending_events, (GFunc) gst_event_unref,
3894           NULL);
3895       g_list_free (basesrc->priv->pending_events);
3896       basesrc->priv->pending_events = NULL;
3897       g_atomic_int_set (&basesrc->priv->have_events, FALSE);
3898     }
3899     GST_OBJECT_UNLOCK (basesrc);
3900   }
3901 
3902   GST_LIVE_SIGNAL (basesrc);
3903   GST_LIVE_UNLOCK (basesrc);
3904 
3905   if (!flushing) {
3906     /* Now wait for the stream lock to be released and clear our unlock request */
3907     GST_PAD_STREAM_LOCK (basesrc->srcpad);
3908     if (bclass->unlock_stop)
3909       bclass->unlock_stop (basesrc);
3910     GST_PAD_STREAM_UNLOCK (basesrc->srcpad);
3911   }
3912 
3913   return TRUE;
3914 }
3915 
3916 /* the purpose of this function is to make sure that a live source blocks in the
3917  * LIVE lock or leaves the LIVE lock and continues playing. */
3918 static gboolean
gst_base_src_set_playing(GstBaseSrc * basesrc,gboolean live_play)3919 gst_base_src_set_playing (GstBaseSrc * basesrc, gboolean live_play)
3920 {
3921   /* we are now able to grab the LIVE lock, when we get it, we can be
3922    * waiting for PLAYING while blocked in the LIVE cond or we can be waiting
3923    * for the clock. */
3924   GST_LIVE_LOCK (basesrc);
3925   GST_DEBUG_OBJECT (basesrc, "unschedule clock");
3926 
3927   /* unblock clock sync (if any) */
3928   if (basesrc->clock_id)
3929     gst_clock_id_unschedule (basesrc->clock_id);
3930 
3931   /* configure what to do when we get to the LIVE lock. */
3932   GST_DEBUG_OBJECT (basesrc, "live running %d", live_play);
3933   basesrc->live_running = live_play;
3934 
3935   if (live_play) {
3936     gboolean start;
3937 
3938     /* for live sources we restart the timestamp correction */
3939     GST_OBJECT_LOCK (basesrc);
3940     basesrc->priv->latency = -1;
3941     GST_OBJECT_UNLOCK (basesrc);
3942     /* have to restart the task in case it stopped because of the unlock when
3943      * we went to PAUSED. Only do this if we operating in push mode. */
3944     GST_OBJECT_LOCK (basesrc->srcpad);
3945     start = (GST_PAD_MODE (basesrc->srcpad) == GST_PAD_MODE_PUSH);
3946     GST_OBJECT_UNLOCK (basesrc->srcpad);
3947     if (start)
3948       gst_pad_start_task (basesrc->srcpad, (GstTaskFunction) gst_base_src_loop,
3949           basesrc->srcpad, NULL);
3950     GST_DEBUG_OBJECT (basesrc, "signal");
3951     GST_LIVE_SIGNAL (basesrc);
3952   }
3953   GST_LIVE_UNLOCK (basesrc);
3954 
3955   return TRUE;
3956 }
3957 
3958 static gboolean
gst_base_src_activate_push(GstPad * pad,GstObject * parent,gboolean active)3959 gst_base_src_activate_push (GstPad * pad, GstObject * parent, gboolean active)
3960 {
3961   GstBaseSrc *basesrc;
3962 
3963   basesrc = GST_BASE_SRC (parent);
3964 
3965   /* prepare subclass first */
3966   if (active) {
3967     GST_DEBUG_OBJECT (basesrc, "Activating in push mode");
3968 
3969     if (G_UNLIKELY (!basesrc->can_activate_push))
3970       goto no_push_activation;
3971 
3972     if (G_UNLIKELY (!gst_base_src_start (basesrc)))
3973       goto error_start;
3974   } else {
3975     GST_DEBUG_OBJECT (basesrc, "Deactivating in push mode");
3976     /* now we can stop the source */
3977     if (G_UNLIKELY (!gst_base_src_stop (basesrc)))
3978       goto error_stop;
3979   }
3980   return TRUE;
3981 
3982   /* ERRORS */
3983 no_push_activation:
3984   {
3985     GST_WARNING_OBJECT (basesrc, "Subclass disabled push-mode activation");
3986     return FALSE;
3987   }
3988 error_start:
3989   {
3990     GST_WARNING_OBJECT (basesrc, "Failed to start in push mode");
3991     return FALSE;
3992   }
3993 error_stop:
3994   {
3995     GST_DEBUG_OBJECT (basesrc, "Failed to stop in push mode");
3996     return FALSE;
3997   }
3998 }
3999 
4000 static gboolean
gst_base_src_activate_pull(GstPad * pad,GstObject * parent,gboolean active)4001 gst_base_src_activate_pull (GstPad * pad, GstObject * parent, gboolean active)
4002 {
4003   GstBaseSrc *basesrc;
4004 
4005   basesrc = GST_BASE_SRC (parent);
4006 
4007   /* prepare subclass first */
4008   if (active) {
4009     GST_DEBUG_OBJECT (basesrc, "Activating in pull mode");
4010     if (G_UNLIKELY (!gst_base_src_start (basesrc)))
4011       goto error_start;
4012   } else {
4013     GST_DEBUG_OBJECT (basesrc, "Deactivating in pull mode");
4014     if (G_UNLIKELY (!gst_base_src_stop (basesrc)))
4015       goto error_stop;
4016   }
4017   return TRUE;
4018 
4019   /* ERRORS */
4020 error_start:
4021   {
4022     GST_ERROR_OBJECT (basesrc, "Failed to start in pull mode");
4023     return FALSE;
4024   }
4025 error_stop:
4026   {
4027     GST_ERROR_OBJECT (basesrc, "Failed to stop in pull mode");
4028     return FALSE;
4029   }
4030 }
4031 
4032 static gboolean
gst_base_src_activate_mode(GstPad * pad,GstObject * parent,GstPadMode mode,gboolean active)4033 gst_base_src_activate_mode (GstPad * pad, GstObject * parent,
4034     GstPadMode mode, gboolean active)
4035 {
4036   gboolean res;
4037   GstBaseSrc *src = GST_BASE_SRC (parent);
4038 
4039   src->priv->stream_start_pending = FALSE;
4040 
4041   GST_DEBUG_OBJECT (pad, "activating in mode %d", mode);
4042 
4043   switch (mode) {
4044     case GST_PAD_MODE_PULL:
4045       res = gst_base_src_activate_pull (pad, parent, active);
4046       break;
4047     case GST_PAD_MODE_PUSH:
4048       src->priv->stream_start_pending = active;
4049       res = gst_base_src_activate_push (pad, parent, active);
4050       break;
4051     default:
4052       GST_LOG_OBJECT (pad, "unknown activation mode %d", mode);
4053       res = FALSE;
4054       break;
4055   }
4056   return res;
4057 }
4058 
4059 
4060 static GstStateChangeReturn
gst_base_src_change_state(GstElement * element,GstStateChange transition)4061 gst_base_src_change_state (GstElement * element, GstStateChange transition)
4062 {
4063   GstBaseSrc *basesrc;
4064   GstStateChangeReturn result;
4065   gboolean no_preroll = FALSE;
4066 
4067   basesrc = GST_BASE_SRC (element);
4068 
4069   switch (transition) {
4070     case GST_STATE_CHANGE_NULL_TO_READY:
4071       break;
4072     case GST_STATE_CHANGE_READY_TO_PAUSED:
4073       no_preroll = gst_base_src_is_live (basesrc);
4074       break;
4075     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
4076       GST_DEBUG_OBJECT (basesrc, "PAUSED->PLAYING");
4077       if (gst_base_src_is_live (basesrc)) {
4078         /* now we can start playback */
4079         gst_base_src_set_playing (basesrc, TRUE);
4080       }
4081       break;
4082     default:
4083       break;
4084   }
4085 
4086   if ((result =
4087           GST_ELEMENT_CLASS (parent_class)->change_state (element,
4088               transition)) == GST_STATE_CHANGE_FAILURE)
4089     goto failure;
4090 
4091   switch (transition) {
4092     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
4093       GST_DEBUG_OBJECT (basesrc, "PLAYING->PAUSED");
4094       if (gst_base_src_is_live (basesrc)) {
4095         /* make sure we block in the live cond in PAUSED */
4096         gst_base_src_set_playing (basesrc, FALSE);
4097         no_preroll = TRUE;
4098       }
4099       break;
4100     case GST_STATE_CHANGE_PAUSED_TO_READY:
4101     {
4102       /* we don't need to unblock anything here, the pad deactivation code
4103        * already did this */
4104       if (g_atomic_int_get (&basesrc->priv->has_pending_eos)) {
4105         GST_OBJECT_LOCK (basesrc);
4106         CLEAR_PENDING_EOS (basesrc);
4107         GST_OBJECT_UNLOCK (basesrc);
4108       }
4109       gst_event_replace (&basesrc->pending_seek, NULL);
4110       break;
4111     }
4112     case GST_STATE_CHANGE_READY_TO_NULL:
4113       break;
4114     default:
4115       break;
4116   }
4117 
4118   if (no_preroll && result == GST_STATE_CHANGE_SUCCESS)
4119     result = GST_STATE_CHANGE_NO_PREROLL;
4120 
4121   return result;
4122 
4123   /* ERRORS */
4124 failure:
4125   {
4126     GST_DEBUG_OBJECT (basesrc, "parent failed state change");
4127     return result;
4128   }
4129 }
4130 
4131 /**
4132  * gst_base_src_get_buffer_pool:
4133  * @src: a #GstBaseSrc
4134  *
4135  * Returns: (nullable) (transfer full): the instance of the #GstBufferPool used
4136  * by the src; unref it after usage.
4137  */
4138 GstBufferPool *
gst_base_src_get_buffer_pool(GstBaseSrc * src)4139 gst_base_src_get_buffer_pool (GstBaseSrc * src)
4140 {
4141   GstBufferPool *ret = NULL;
4142 
4143   g_return_val_if_fail (GST_IS_BASE_SRC (src), NULL);
4144 
4145   GST_OBJECT_LOCK (src);
4146   if (src->priv->pool)
4147     ret = gst_object_ref (src->priv->pool);
4148   GST_OBJECT_UNLOCK (src);
4149 
4150   return ret;
4151 }
4152 
4153 /**
4154  * gst_base_src_get_allocator:
4155  * @src: a #GstBaseSrc
4156  * @allocator: (out) (optional) (nullable) (transfer full): the #GstAllocator
4157  * used
4158  * @params: (out caller-allocates) (optional): the #GstAllocationParams of @allocator
4159  *
4160  * Lets #GstBaseSrc sub-classes to know the memory @allocator
4161  * used by the base class and its @params.
4162  *
4163  * Unref the @allocator after usage.
4164  */
4165 void
gst_base_src_get_allocator(GstBaseSrc * src,GstAllocator ** allocator,GstAllocationParams * params)4166 gst_base_src_get_allocator (GstBaseSrc * src,
4167     GstAllocator ** allocator, GstAllocationParams * params)
4168 {
4169   g_return_if_fail (GST_IS_BASE_SRC (src));
4170 
4171   GST_OBJECT_LOCK (src);
4172   if (allocator)
4173     *allocator = src->priv->allocator ?
4174         gst_object_ref (src->priv->allocator) : NULL;
4175 
4176   if (params)
4177     *params = src->priv->params;
4178   GST_OBJECT_UNLOCK (src);
4179 }
4180 
4181 /**
4182  * gst_base_src_submit_buffer_list:
4183  * @src: a #GstBaseSrc
4184  * @buffer_list: (transfer full): a #GstBufferList
4185  *
4186  * Subclasses can call this from their create virtual method implementation
4187  * to submit a buffer list to be pushed out later. This is useful in
4188  * cases where the create function wants to produce multiple buffers to be
4189  * pushed out in one go in form of a #GstBufferList, which can reduce overhead
4190  * drastically, especially for packetised inputs (for data streams where
4191  * the packetisation/chunking is not important it is usually more efficient
4192  * to return larger buffers instead).
4193  *
4194  * Subclasses that use this function from their create function must return
4195  * %GST_FLOW_OK and no buffer from their create virtual method implementation.
4196  * If a buffer is returned after a buffer list has also been submitted via this
4197  * function the behaviour is undefined.
4198  *
4199  * Subclasses must only call this function once per create function call and
4200  * subclasses must only call this function when the source operates in push
4201  * mode.
4202  *
4203  * Since: 1.14
4204  */
4205 void
gst_base_src_submit_buffer_list(GstBaseSrc * src,GstBufferList * buffer_list)4206 gst_base_src_submit_buffer_list (GstBaseSrc * src, GstBufferList * buffer_list)
4207 {
4208   g_return_if_fail (GST_IS_BASE_SRC (src));
4209   g_return_if_fail (GST_IS_BUFFER_LIST (buffer_list));
4210   g_return_if_fail (BASE_SRC_HAS_PENDING_BUFFER_LIST (src) == FALSE);
4211 
4212   /* we need it to be writable later in get_range() where we use get_writable */
4213   src->priv->pending_bufferlist = gst_buffer_list_make_writable (buffer_list);
4214 
4215   GST_LOG_OBJECT (src, "%u buffers submitted in buffer list",
4216       gst_buffer_list_length (buffer_list));
4217 }
4218