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