4624b1d3c4f67efef23f05a6b802315ea2a09dd2
[platform/upstream/gstreamer.git] / ext / ogg / gstoggmux.c
1 /* OGG muxer plugin for GStreamer
2  * Copyright (C) 2004 Wim Taymans <wim@fluendo.com>
3  * Copyright (C) 2006 Thomas Vander Stichele <thomas at apestaart dot org>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * SECTION:element-oggmux
23  * @see_also: <link linkend="gst-plugins-base-plugins-deoggmux">oggdemux</link>
24  *
25  * This element merges streams (audio and video) into ogg files.
26  *
27  * <refsect2>
28  * <title>Example pipelines</title>
29  * |[
30  * gst-launch v4l2src num-buffers=500 ! video/x-raw-yuv,width=320,height=240 ! ffmpegcolorspace ! theoraenc ! oggmux ! filesink location=video.ogg
31  * ]| Encodes a video stream captured from a v4l2-compatible camera to Ogg/Theora
32  * (the encoding will stop automatically after 500 frames)
33  * </refsect2>
34  *
35  * Last reviewed on 2008-02-06 (0.10.17)
36  */
37
38 #ifdef HAVE_CONFIG_H
39 #include "config.h"
40 #endif
41
42 #include <gst/gst.h>
43 #include <gst/base/gstcollectpads.h>
44
45 #include "gstoggmux.h"
46
47 /* memcpy - if someone knows a way to get rid of it, please speak up
48  * note: the ogg docs even say you need this... */
49 #include <string.h>
50 #include <time.h>
51 #include <stdlib.h>             /* rand, srand, atoi */
52
53 GST_DEBUG_CATEGORY_STATIC (gst_ogg_mux_debug);
54 #define GST_CAT_DEFAULT gst_ogg_mux_debug
55
56 /* This isn't generally what you'd want with an end-time macro, because
57    technically the end time of a buffer with invalid duration is invalid. But
58    for sorting ogg pages this is what we want. */
59 #define GST_BUFFER_END_TIME(buf) \
60     (GST_BUFFER_DURATION_IS_VALID (buf) \
61     ? GST_BUFFER_TIMESTAMP (buf) + GST_BUFFER_DURATION (buf) \
62     : GST_BUFFER_TIMESTAMP (buf))
63
64 #define GST_GP_FORMAT "[gp %8" G_GINT64_FORMAT "]"
65
66 typedef enum
67 {
68   GST_OGG_FLAG_BOS = GST_ELEMENT_FLAG_LAST,
69   GST_OGG_FLAG_EOS
70 }
71 GstOggFlag;
72
73 /* elementfactory information */
74 static const GstElementDetails gst_ogg_mux_details =
75 GST_ELEMENT_DETAILS ("Ogg muxer",
76     "Codec/Muxer",
77     "mux ogg streams (info about ogg: http://xiph.org)",
78     "Wim Taymans <wim@fluendo.com>");
79
80 /* OggMux signals and args */
81 enum
82 {
83   /* FILL ME */
84   LAST_SIGNAL
85 };
86
87 /* set to 0.5 seconds by default */
88 #define DEFAULT_MAX_DELAY       G_GINT64_CONSTANT(500000000)
89 #define DEFAULT_MAX_PAGE_DELAY  G_GINT64_CONSTANT(500000000)
90 enum
91 {
92   ARG_0,
93   ARG_MAX_DELAY,
94   ARG_MAX_PAGE_DELAY,
95 };
96
97 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
98     GST_PAD_SRC,
99     GST_PAD_ALWAYS,
100     GST_STATIC_CAPS ("application/ogg")
101     );
102
103 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink_%d",
104     GST_PAD_SINK,
105     GST_PAD_REQUEST,
106     GST_STATIC_CAPS ("video/x-theora; "
107         "audio/x-vorbis; audio/x-flac; audio/x-speex; audio/x-celt; "
108         "application/x-ogm-video; application/x-ogm-audio; video/x-dirac; "
109         "video/x-smoke; text/x-cmml, encoded = (boolean) TRUE; "
110         "subtitle/x-kate; application/x-kate")
111     );
112
113 static void gst_ogg_mux_base_init (gpointer g_class);
114 static void gst_ogg_mux_class_init (GstOggMuxClass * klass);
115 static void gst_ogg_mux_init (GstOggMux * ogg_mux);
116 static void gst_ogg_mux_finalize (GObject * object);
117
118 static GstFlowReturn
119 gst_ogg_mux_collected (GstCollectPads * pads, GstOggMux * ogg_mux);
120 static gboolean gst_ogg_mux_handle_src_event (GstPad * pad, GstEvent * event);
121 static GstPad *gst_ogg_mux_request_new_pad (GstElement * element,
122     GstPadTemplate * templ, const gchar * name);
123 static void gst_ogg_mux_release_pad (GstElement * element, GstPad * pad);
124
125 static void gst_ogg_mux_set_property (GObject * object,
126     guint prop_id, const GValue * value, GParamSpec * pspec);
127 static void gst_ogg_mux_get_property (GObject * object,
128     guint prop_id, GValue * value, GParamSpec * pspec);
129 static GstStateChangeReturn gst_ogg_mux_change_state (GstElement * element,
130     GstStateChange transition);
131
132 static GstElementClass *parent_class = NULL;
133
134 /*static guint gst_ogg_mux_signals[LAST_SIGNAL] = { 0 }; */
135
136 GType
137 gst_ogg_mux_get_type (void)
138 {
139   static GType ogg_mux_type = 0;
140
141   if (G_UNLIKELY (ogg_mux_type == 0)) {
142     static const GTypeInfo ogg_mux_info = {
143       sizeof (GstOggMuxClass),
144       gst_ogg_mux_base_init,
145       NULL,
146       (GClassInitFunc) gst_ogg_mux_class_init,
147       NULL,
148       NULL,
149       sizeof (GstOggMux),
150       0,
151       (GInstanceInitFunc) gst_ogg_mux_init,
152     };
153     static const GInterfaceInfo preset_info = {
154       NULL,
155       NULL,
156       NULL
157     };
158
159     ogg_mux_type =
160         g_type_register_static (GST_TYPE_ELEMENT, "GstOggMux", &ogg_mux_info,
161         0);
162
163     g_type_add_interface_static (ogg_mux_type, GST_TYPE_PRESET, &preset_info);
164   }
165   return ogg_mux_type;
166 }
167
168 static void
169 gst_ogg_mux_base_init (gpointer g_class)
170 {
171   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
172
173   gst_element_class_add_pad_template (element_class,
174       gst_static_pad_template_get (&src_factory));
175   gst_element_class_add_pad_template (element_class,
176       gst_static_pad_template_get (&sink_factory));
177
178   gst_element_class_set_details (element_class, &gst_ogg_mux_details);
179 }
180
181 static void
182 gst_ogg_mux_class_init (GstOggMuxClass * klass)
183 {
184   GObjectClass *gobject_class;
185   GstElementClass *gstelement_class;
186
187   gobject_class = (GObjectClass *) klass;
188   gstelement_class = (GstElementClass *) klass;
189
190   parent_class = g_type_class_peek_parent (klass);
191
192   gobject_class->finalize = gst_ogg_mux_finalize;
193   gobject_class->get_property = gst_ogg_mux_get_property;
194   gobject_class->set_property = gst_ogg_mux_set_property;
195
196   gstelement_class->request_new_pad = gst_ogg_mux_request_new_pad;
197   gstelement_class->release_pad = gst_ogg_mux_release_pad;
198
199   g_object_class_install_property (gobject_class, ARG_MAX_DELAY,
200       g_param_spec_uint64 ("max-delay", "Max delay",
201           "Maximum delay in multiplexing streams", 0, G_MAXUINT64,
202           DEFAULT_MAX_DELAY,
203           (GParamFlags) G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
204   g_object_class_install_property (gobject_class, ARG_MAX_PAGE_DELAY,
205       g_param_spec_uint64 ("max-page-delay", "Max page delay",
206           "Maximum delay for sending out a page", 0, G_MAXUINT64,
207           DEFAULT_MAX_PAGE_DELAY,
208           (GParamFlags) G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
209
210   gstelement_class->change_state = gst_ogg_mux_change_state;
211
212 }
213
214 #if 0
215 static const GstEventMask *
216 gst_ogg_mux_get_sink_event_masks (GstPad * pad)
217 {
218   static const GstEventMask gst_ogg_mux_sink_event_masks[] = {
219     {GST_EVENT_EOS, 0},
220     {GST_EVENT_DISCONTINUOUS, 0},
221     {0,}
222   };
223
224   return gst_ogg_mux_sink_event_masks;
225 }
226 #endif
227
228 static void
229 gst_ogg_mux_clear (GstOggMux * ogg_mux)
230 {
231   ogg_mux->pulling = NULL;
232   ogg_mux->need_headers = TRUE;
233   ogg_mux->max_delay = DEFAULT_MAX_DELAY;
234   ogg_mux->max_page_delay = DEFAULT_MAX_PAGE_DELAY;
235   ogg_mux->delta_pad = NULL;
236   ogg_mux->offset = 0;
237   ogg_mux->next_ts = 0;
238   ogg_mux->last_ts = GST_CLOCK_TIME_NONE;
239 }
240
241 static void
242 gst_ogg_mux_init (GstOggMux * ogg_mux)
243 {
244   GstElementClass *klass = GST_ELEMENT_GET_CLASS (ogg_mux);
245
246   ogg_mux->srcpad =
247       gst_pad_new_from_template (gst_element_class_get_pad_template (klass,
248           "src"), "src");
249   gst_pad_set_event_function (ogg_mux->srcpad, gst_ogg_mux_handle_src_event);
250   gst_element_add_pad (GST_ELEMENT (ogg_mux), ogg_mux->srcpad);
251
252   GST_OBJECT_FLAG_SET (GST_ELEMENT (ogg_mux), GST_OGG_FLAG_BOS);
253
254   /* seed random number generator for creation of serial numbers */
255   srand (time (NULL));
256
257   ogg_mux->collect = gst_collect_pads_new ();
258   gst_collect_pads_set_function (ogg_mux->collect,
259       (GstCollectPadsFunction) GST_DEBUG_FUNCPTR (gst_ogg_mux_collected),
260       ogg_mux);
261
262   gst_ogg_mux_clear (ogg_mux);
263 }
264
265 static void
266 gst_ogg_mux_finalize (GObject * object)
267 {
268   GstOggMux *ogg_mux;
269
270   ogg_mux = GST_OGG_MUX (object);
271
272   if (ogg_mux->collect) {
273     gst_object_unref (ogg_mux->collect);
274     ogg_mux->collect = NULL;
275   }
276
277   G_OBJECT_CLASS (parent_class)->finalize (object);
278 }
279
280 static void
281 gst_ogg_mux_ogg_pad_destroy_notify (GstCollectData * data)
282 {
283   GstOggPad *oggpad = (GstOggPad *) data;
284   GstBuffer *buf;
285
286   ogg_stream_clear (&oggpad->stream);
287
288   if (oggpad->pagebuffers) {
289     while ((buf = g_queue_pop_head (oggpad->pagebuffers)) != NULL) {
290       gst_buffer_unref (buf);
291     }
292     g_queue_free (oggpad->pagebuffers);
293     oggpad->pagebuffers = NULL;
294   }
295 }
296
297 static GstPadLinkReturn
298 gst_ogg_mux_sinkconnect (GstPad * pad, GstPad * peer)
299 {
300   GstOggMux *ogg_mux;
301
302   ogg_mux = GST_OGG_MUX (gst_pad_get_parent (pad));
303
304   GST_DEBUG_OBJECT (ogg_mux, "sinkconnect triggered on %s", GST_PAD_NAME (pad));
305
306   gst_object_unref (ogg_mux);
307
308   return GST_PAD_LINK_OK;
309 }
310
311 static gboolean
312 gst_ogg_mux_sink_event (GstPad * pad, GstEvent * event)
313 {
314   GstOggMux *ogg_mux = GST_OGG_MUX (gst_pad_get_parent (pad));
315   GstOggPad *ogg_pad = (GstOggPad *) gst_pad_get_element_private (pad);
316   gboolean ret;
317
318   GST_DEBUG ("Got %s event on pad %s:%s", GST_EVENT_TYPE_NAME (event),
319       GST_DEBUG_PAD_NAME (pad));
320
321   switch (GST_EVENT_TYPE (event)) {
322     case GST_EVENT_NEWSEGMENT:
323       /* We don't support NEWSEGMENT events */
324       gst_event_unref (event);
325       ret = FALSE;
326       break;
327     default:
328       ret = TRUE;
329       break;
330   }
331
332   /* now GstCollectPads can take care of the rest, e.g. EOS */
333   if (ret)
334     ret = ogg_pad->collect_event (pad, event);
335
336   gst_object_unref (ogg_mux);
337   return ret;
338 }
339
340 static GstPad *
341 gst_ogg_mux_request_new_pad (GstElement * element,
342     GstPadTemplate * templ, const gchar * req_name)
343 {
344   GstOggMux *ogg_mux;
345   GstPad *newpad;
346   GstElementClass *klass;
347
348   g_return_val_if_fail (templ != NULL, NULL);
349
350   if (templ->direction != GST_PAD_SINK)
351     goto wrong_direction;
352
353   g_return_val_if_fail (GST_IS_OGG_MUX (element), NULL);
354   ogg_mux = GST_OGG_MUX (element);
355
356   klass = GST_ELEMENT_GET_CLASS (element);
357
358   if (templ != gst_element_class_get_pad_template (klass, "sink_%d"))
359     goto wrong_template;
360
361   {
362     gint serial;
363     gchar *name;
364
365     if (req_name == NULL || strlen (req_name) < 6) {
366       /* no name given when requesting the pad, use random serial number */
367       serial = rand ();
368     } else {
369       /* parse serial number from requested padname */
370       serial = atoi (&req_name[5]);
371     }
372     /* create new pad with the name */
373     GST_DEBUG_OBJECT (ogg_mux, "Creating new pad for serial %d", serial);
374     name = g_strdup_printf ("sink_%d", serial);
375     newpad = gst_pad_new_from_template (templ, name);
376     g_free (name);
377
378     /* construct our own wrapper data structure for the pad to
379      * keep track of its status */
380     {
381       GstOggPad *oggpad;
382
383       oggpad = (GstOggPad *)
384           gst_collect_pads_add_pad_full (ogg_mux->collect, newpad,
385           sizeof (GstOggPad), gst_ogg_mux_ogg_pad_destroy_notify);
386       ogg_mux->active_pads++;
387
388       oggpad->serial = serial;
389       ogg_stream_init (&oggpad->stream, serial);
390       oggpad->packetno = 0;
391       oggpad->pageno = 0;
392       oggpad->eos = FALSE;
393       /* we assume there will be some control data first for this pad */
394       oggpad->state = GST_OGG_PAD_STATE_CONTROL;
395       oggpad->new_page = TRUE;
396       oggpad->first_delta = FALSE;
397       oggpad->prev_delta = FALSE;
398       oggpad->pagebuffers = g_queue_new ();
399
400       oggpad->collect_event = (GstPadEventFunction) GST_PAD_EVENTFUNC (newpad);
401       gst_pad_set_event_function (newpad,
402           GST_DEBUG_FUNCPTR (gst_ogg_mux_sink_event));
403     }
404   }
405
406   /* setup some pad functions */
407   gst_pad_set_link_function (newpad, gst_ogg_mux_sinkconnect);
408
409   /* dd the pad to the element */
410   gst_element_add_pad (element, newpad);
411
412   return newpad;
413
414   /* ERRORS */
415 wrong_direction:
416   {
417     g_warning ("ogg_mux: request pad that is not a SINK pad\n");
418     return NULL;
419   }
420 wrong_template:
421   {
422     g_warning ("ogg_mux: this is not our template!\n");
423     return NULL;
424   }
425 }
426
427 static void
428 gst_ogg_mux_release_pad (GstElement * element, GstPad * pad)
429 {
430   GstOggMux *ogg_mux;
431
432   ogg_mux = GST_OGG_MUX (gst_pad_get_parent (pad));
433
434   gst_collect_pads_remove_pad (ogg_mux->collect, pad);
435   gst_element_remove_pad (element, pad);
436
437   gst_object_unref (ogg_mux);
438 }
439
440 /* handle events */
441 static gboolean
442 gst_ogg_mux_handle_src_event (GstPad * pad, GstEvent * event)
443 {
444   GstEventType type;
445
446   type = event ? GST_EVENT_TYPE (event) : GST_EVENT_UNKNOWN;
447
448   switch (type) {
449     case GST_EVENT_SEEK:
450       /* disable seeking for now */
451       return FALSE;
452     default:
453       break;
454   }
455
456   return gst_pad_event_default (pad, event);
457 }
458
459 static GstBuffer *
460 gst_ogg_mux_buffer_from_page (GstOggMux * mux, ogg_page * page, gboolean delta)
461 {
462   GstBuffer *buffer;
463
464   /* allocate space for header and body */
465   buffer = gst_buffer_new_and_alloc (page->header_len + page->body_len);
466   memcpy (GST_BUFFER_DATA (buffer), page->header, page->header_len);
467   memcpy (GST_BUFFER_DATA (buffer) + page->header_len,
468       page->body, page->body_len);
469
470   /* Here we set granulepos as our OFFSET_END to give easy direct access to
471    * this value later. Before we push it, we reset this to OFFSET + SIZE
472    * (see gst_ogg_mux_push_buffer). */
473   GST_BUFFER_OFFSET_END (buffer) = ogg_page_granulepos (page);
474   if (delta)
475     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
476
477   GST_LOG_OBJECT (mux, GST_GP_FORMAT
478       " created buffer %p from ogg page", ogg_page_granulepos (page), buffer);
479
480   return buffer;
481 }
482
483 static GstFlowReturn
484 gst_ogg_mux_push_buffer (GstOggMux * mux, GstBuffer * buffer)
485 {
486   GstCaps *caps;
487
488   /* fix up OFFSET and OFFSET_END again */
489   GST_BUFFER_OFFSET (buffer) = mux->offset;
490   mux->offset += GST_BUFFER_SIZE (buffer);
491   GST_BUFFER_OFFSET_END (buffer) = mux->offset;
492
493   /* Ensure we have monotonically increasing timestamps in the output. */
494   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) {
495     if (mux->last_ts != GST_CLOCK_TIME_NONE &&
496         GST_BUFFER_TIMESTAMP (buffer) < mux->last_ts)
497       GST_BUFFER_TIMESTAMP (buffer) = mux->last_ts;
498     else
499       mux->last_ts = GST_BUFFER_TIMESTAMP (buffer);
500   }
501
502   caps = gst_static_pad_template_get_caps (&src_factory);
503   gst_buffer_set_caps (buffer, caps);
504   gst_caps_unref (caps);
505
506   return gst_pad_push (mux->srcpad, buffer);
507 }
508
509 /* if all queues have at least one page, dequeue the page with the lowest
510  * timestamp */
511 static gboolean
512 gst_ogg_mux_dequeue_page (GstOggMux * mux, GstFlowReturn * flowret)
513 {
514   GSList *walk;
515   GstOggPad *opad = NULL;       /* "oldest" pad */
516   GstClockTime oldest = GST_CLOCK_TIME_NONE;
517   GstBuffer *buf = NULL;
518   gboolean ret = FALSE;
519
520   *flowret = GST_FLOW_OK;
521
522   walk = mux->collect->data;
523   while (walk) {
524     GstOggPad *pad = (GstOggPad *) walk->data;
525
526     /* We need each queue to either be at EOS, or have one or more pages
527      * available with a set granulepos (i.e. not -1), otherwise we don't have
528      * enough data yet to determine which stream needs to go next for correct
529      * time ordering. */
530     if (pad->pagebuffers->length == 0) {
531       if (pad->eos) {
532         GST_LOG_OBJECT (pad->collect.pad,
533             "pad is EOS, skipping for dequeue decision");
534       } else {
535         GST_LOG_OBJECT (pad->collect.pad,
536             "no pages in this queue, can't dequeue");
537         return FALSE;
538       }
539     } else {
540       /* We then need to check for a non-negative granulepos */
541       int i;
542       gboolean valid = FALSE;
543
544       for (i = 0; i < pad->pagebuffers->length; i++) {
545         buf = g_queue_peek_nth (pad->pagebuffers, i);
546         /* Here we check the OFFSET_END, which is actually temporarily the
547          * granulepos value for this buffer */
548         if (GST_BUFFER_OFFSET_END (buf) != -1) {
549           valid = TRUE;
550           break;
551         }
552       }
553       if (!valid) {
554         GST_LOG_OBJECT (pad->collect.pad,
555             "No page timestamps in queue, can't dequeue");
556         return FALSE;
557       }
558     }
559
560     walk = g_slist_next (walk);
561   }
562
563   walk = mux->collect->data;
564   while (walk) {
565     GstOggPad *pad = (GstOggPad *) walk->data;
566
567     /* any page with a granulepos of -1 can be pushed immediately.
568      * TODO: it CAN be, but it seems silly to do so? */
569     buf = g_queue_peek_head (pad->pagebuffers);
570     while (buf && GST_BUFFER_OFFSET_END (buf) == -1) {
571       GST_LOG_OBJECT (pad->collect.pad, "[gp        -1] pushing page");
572       g_queue_pop_head (pad->pagebuffers);
573       *flowret = gst_ogg_mux_push_buffer (mux, buf);
574       buf = g_queue_peek_head (pad->pagebuffers);
575       ret = TRUE;
576     }
577
578     if (buf) {
579       /* if no oldest buffer yet, take this one */
580       if (oldest == GST_CLOCK_TIME_NONE) {
581         GST_LOG_OBJECT (mux, "no oldest yet, taking buffer %p from pad %"
582             GST_PTR_FORMAT " with gp time %" GST_TIME_FORMAT,
583             buf, pad->collect.pad, GST_TIME_ARGS (GST_BUFFER_OFFSET (buf)));
584         oldest = GST_BUFFER_OFFSET (buf);
585         opad = pad;
586       } else {
587         /* if we have an oldest, compare with this one */
588         if (GST_BUFFER_OFFSET (buf) < oldest) {
589           GST_LOG_OBJECT (mux, "older buffer %p, taking from pad %"
590               GST_PTR_FORMAT " with gp time %" GST_TIME_FORMAT,
591               buf, pad->collect.pad, GST_TIME_ARGS (GST_BUFFER_OFFSET (buf)));
592           oldest = GST_BUFFER_OFFSET (buf);
593           opad = pad;
594         }
595       }
596     }
597     walk = g_slist_next (walk);
598   }
599
600   if (oldest != GST_CLOCK_TIME_NONE) {
601     g_assert (opad);
602     buf = g_queue_pop_head (opad->pagebuffers);
603     GST_LOG_OBJECT (opad->collect.pad,
604         GST_GP_FORMAT " pushing oldest page buffer %p (granulepos time %"
605         GST_TIME_FORMAT ")", GST_BUFFER_OFFSET_END (buf), buf,
606         GST_TIME_ARGS (GST_BUFFER_OFFSET (buf)));
607     *flowret = gst_ogg_mux_push_buffer (mux, buf);
608     ret = TRUE;
609   }
610
611   return ret;
612 }
613
614 /* put the given ogg page on a per-pad queue, timestamping it correctly.
615  * after that, dequeue and push as many pages as possible.
616  * Caller should make sure:
617  * pad->timestamp     was set with the timestamp of the first packet put
618  *                    on the page
619  * pad->timestamp_end was set with the timestamp + duration of the last packet
620  *                    put on the page
621  * pad->gp_time       was set with the time matching the gp of the last
622  *                    packet put on the page
623  *
624  * will also reset timestamp and timestamp_end, so caller func can restart
625  * counting.
626  */
627 static GstFlowReturn
628 gst_ogg_mux_pad_queue_page (GstOggMux * mux, GstOggPad * pad, ogg_page * page,
629     gboolean delta)
630 {
631   GstFlowReturn ret;
632   GstBuffer *buffer = gst_ogg_mux_buffer_from_page (mux, page, delta);
633
634   /* take the timestamp of the first packet on this page */
635   GST_BUFFER_TIMESTAMP (buffer) = pad->timestamp;
636   GST_BUFFER_DURATION (buffer) = pad->timestamp_end - pad->timestamp;
637   /* take the gp time of the last completed packet on this page */
638   GST_BUFFER_OFFSET (buffer) = pad->gp_time;
639
640   /* the next page will start where the current page's end time leaves off */
641   pad->timestamp = pad->timestamp_end;
642
643   g_queue_push_tail (pad->pagebuffers, buffer);
644   GST_LOG_OBJECT (pad->collect.pad, GST_GP_FORMAT
645       " queued buffer page %p (gp time %"
646       GST_TIME_FORMAT ", timestamp %" GST_TIME_FORMAT
647       "), %d page buffers queued", ogg_page_granulepos (page),
648       buffer, GST_TIME_ARGS (GST_BUFFER_OFFSET (buffer)),
649       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
650       g_queue_get_length (pad->pagebuffers));
651
652   while (gst_ogg_mux_dequeue_page (mux, &ret)) {
653     if (ret != GST_FLOW_OK)
654       break;
655   }
656
657   return ret;
658 }
659
660 /*
661  * Given two pads, compare the buffers queued on it.
662  * Returns:
663  *  0 if they have an equal priority
664  * -1 if the first is better
665  *  1 if the second is better
666  * Priority decided by: a) validity, b) older timestamp, c) smaller number
667  * of muxed pages
668  */
669 static gint
670 gst_ogg_mux_compare_pads (GstOggMux * ogg_mux, GstOggPad * first,
671     GstOggPad * second)
672 {
673   guint64 firsttime, secondtime;
674
675   /* if the first pad doesn't contain anything or is even NULL, return
676    * the second pad as best candidate and vice versa */
677   if (first == NULL || (first->buffer == NULL && first->next_buffer == NULL))
678     return 1;
679   if (second == NULL || (second->buffer == NULL && second->next_buffer == NULL))
680     return -1;
681
682   /* no timestamp on first buffer, it must go first */
683   if (first->buffer)
684     firsttime = GST_BUFFER_TIMESTAMP (first->buffer);
685   else
686     firsttime = GST_BUFFER_TIMESTAMP (first->next_buffer);
687   if (firsttime == GST_CLOCK_TIME_NONE)
688     return -1;
689
690   /* no timestamp on second buffer, it must go first */
691   if (second->buffer)
692     secondtime = GST_BUFFER_TIMESTAMP (second->buffer);
693   else
694     secondtime = GST_BUFFER_TIMESTAMP (second->next_buffer);
695   if (secondtime == GST_CLOCK_TIME_NONE)
696     return 1;
697
698   /* first buffer has higher timestamp, second one should go first */
699   if (secondtime < firsttime)
700     return 1;
701   /* second buffer has higher timestamp, first one should go first */
702   else if (secondtime > firsttime)
703     return -1;
704   else {
705     /* buffers with equal timestamps, prefer the pad that has the
706      * least number of pages muxed */
707     if (second->pageno < first->pageno)
708       return 1;
709     else if (second->pageno > first->pageno)
710       return -1;
711   }
712
713   /* same priority if all of the above failed */
714   return 0;
715 }
716
717 /* make sure at least one buffer is queued on all pads, two if possible
718  * 
719  * if pad->buffer == NULL, pad->next_buffer !=  NULL, then
720  *   we do not know if the buffer is the last or not
721  * if pad->buffer != NULL, pad->next_buffer != NULL, then
722  *   pad->buffer is not the last buffer for the pad
723  * if pad->buffer != NULL, pad->next_buffer == NULL, then
724  *   pad->buffer if the last buffer for the pad
725  * 
726  * returns a pointer to an oggpad that holds the best buffer, or
727  * NULL when no pad was usable. "best" means the buffer marked
728  * with the lowest timestamp. If best->buffer == NULL then nothing
729  * should be done until more data arrives */
730 static GstOggPad *
731 gst_ogg_mux_queue_pads (GstOggMux * ogg_mux)
732 {
733   GstOggPad *bestpad = NULL, *still_hungry = NULL;
734   GSList *walk;
735
736   /* try to make sure we have a buffer from each usable pad first */
737   walk = ogg_mux->collect->data;
738   while (walk) {
739     GstOggPad *pad;
740     GstCollectData *data;
741
742     data = (GstCollectData *) walk->data;
743     pad = (GstOggPad *) data;
744
745     walk = g_slist_next (walk);
746
747     GST_LOG_OBJECT (data->pad, "looking at pad for buffer");
748
749     /* try to get a new buffer for this pad if needed and possible */
750     if (pad->buffer == NULL) {
751       GstBuffer *buf;
752       gboolean incaps;
753
754       /* shift the buffer along if needed (it's okay if next_buffer is NULL) */
755       if (pad->buffer == NULL) {
756         GST_LOG_OBJECT (data->pad, "shifting buffer %" GST_PTR_FORMAT,
757             pad->next_buffer);
758         pad->buffer = pad->next_buffer;
759         pad->next_buffer = NULL;
760       }
761
762       buf = gst_collect_pads_pop (ogg_mux->collect, data);
763       GST_LOG_OBJECT (data->pad, "popped buffer %" GST_PTR_FORMAT, buf);
764
765       /* On EOS we get a NULL buffer */
766       if (buf != NULL) {
767         if (ogg_mux->delta_pad == NULL &&
768             GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT))
769           ogg_mux->delta_pad = pad;
770
771         incaps = GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_IN_CAPS);
772         /* if we need headers */
773         if (pad->state == GST_OGG_PAD_STATE_CONTROL) {
774           /* and we have one */
775           if (incaps) {
776             GST_DEBUG_OBJECT (ogg_mux,
777                 "got incaps buffer in control state, ignoring");
778             /* just ignore */
779             gst_buffer_unref (buf);
780             buf = NULL;
781           } else {
782             GST_DEBUG_OBJECT (ogg_mux,
783                 "got data buffer in control state, switching " "to data mode");
784             /* this is a data buffer so switch to data state */
785             pad->state = GST_OGG_PAD_STATE_DATA;
786           }
787         }
788       } else {
789         GST_DEBUG_OBJECT (data->pad, "EOS on pad");
790         if (!pad->eos) {
791           ogg_page page;
792           GstFlowReturn ret;
793
794           /* it's no longer active */
795           ogg_mux->active_pads--;
796
797           /* Just gone to EOS. Flush existing page(s) */
798           pad->eos = TRUE;
799
800           while (ogg_stream_flush (&pad->stream, &page)) {
801             /* Place page into the per-pad queue */
802             ret = gst_ogg_mux_pad_queue_page (ogg_mux, pad, &page,
803                 pad->first_delta);
804             /* increment the page number counter */
805             pad->pageno++;
806             /* mark other pages as delta */
807             pad->first_delta = TRUE;
808           }
809         }
810       }
811
812       pad->next_buffer = buf;
813     }
814
815     /* we should have a buffer now, see if it is the best pad to
816      * pull on */
817     if (pad->buffer || pad->next_buffer) {
818       if (gst_ogg_mux_compare_pads (ogg_mux, bestpad, pad) > 0) {
819         GST_LOG_OBJECT (data->pad,
820             "new best pad, with buffers %" GST_PTR_FORMAT
821             " and %" GST_PTR_FORMAT, pad->buffer, pad->next_buffer);
822
823         bestpad = pad;
824       }
825     } else if (!pad->eos) {
826       GST_LOG_OBJECT (data->pad, "hungry pad");
827       still_hungry = pad;
828     }
829   }
830
831   if (still_hungry)
832     /* drop back into collectpads... */
833     return still_hungry;
834   else
835     return bestpad;
836 }
837
838 static GList *
839 gst_ogg_mux_get_headers (GstOggPad * pad)
840 {
841   GList *res = NULL;
842   GstOggMux *ogg_mux;
843   GstStructure *structure;
844   GstCaps *caps;
845   GstPad *thepad;
846
847   thepad = pad->collect.pad;
848
849   ogg_mux = GST_OGG_MUX (GST_PAD_PARENT (thepad));
850
851   GST_LOG_OBJECT (thepad, "getting headers");
852
853   caps = gst_pad_get_negotiated_caps (thepad);
854   if (caps != NULL) {
855     const GValue *streamheader;
856
857     structure = gst_caps_get_structure (caps, 0);
858     streamheader = gst_structure_get_value (structure, "streamheader");
859     if (streamheader != NULL) {
860       GST_LOG_OBJECT (thepad, "got header");
861       if (G_VALUE_TYPE (streamheader) == GST_TYPE_ARRAY) {
862         GArray *bufarr = g_value_peek_pointer (streamheader);
863         gint i;
864
865         GST_LOG_OBJECT (thepad, "got fixed list");
866
867         for (i = 0; i < bufarr->len; i++) {
868           GValue *bufval = &g_array_index (bufarr, GValue, i);
869
870           GST_LOG_OBJECT (thepad, "item %d", i);
871           if (G_VALUE_TYPE (bufval) == GST_TYPE_BUFFER) {
872             GstBuffer *buf = g_value_peek_pointer (bufval);
873
874             GST_LOG_OBJECT (thepad, "adding item %d to header list", i);
875
876             gst_buffer_ref (buf);
877             res = g_list_append (res, buf);
878           }
879         }
880       } else {
881         GST_LOG_OBJECT (thepad, "streamheader is not fixed list");
882       }
883     } else if (gst_structure_has_name (structure, "video/x-dirac")) {
884       res = g_list_append (res, pad->buffer);
885       pad->buffer = pad->next_buffer;
886       pad->next_buffer = NULL;
887       pad->always_flush_page = TRUE;
888     } else {
889       GST_LOG_OBJECT (thepad, "caps don't have streamheader");
890     }
891     gst_caps_unref (caps);
892   } else {
893     GST_LOG_OBJECT (thepad, "got empty caps as negotiated format");
894   }
895   return res;
896 }
897
898 static GstCaps *
899 gst_ogg_mux_set_header_on_caps (GstCaps * caps, GList * buffers)
900 {
901   GstStructure *structure;
902   GValue array = { 0 };
903   GList *walk = buffers;
904
905   caps = gst_caps_make_writable (caps);
906
907   structure = gst_caps_get_structure (caps, 0);
908
909   /* put buffers in a fixed list */
910   g_value_init (&array, GST_TYPE_ARRAY);
911
912   while (walk) {
913     GstBuffer *buf = GST_BUFFER (walk->data);
914     GstBuffer *copy;
915     GValue value = { 0 };
916
917     walk = walk->next;
918
919     /* mark buffer */
920     GST_LOG ("Setting IN_CAPS on buffer of length %d", GST_BUFFER_SIZE (buf));
921     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_IN_CAPS);
922
923     g_value_init (&value, GST_TYPE_BUFFER);
924     copy = gst_buffer_copy (buf);
925     gst_value_set_buffer (&value, copy);
926     gst_buffer_unref (copy);
927     gst_value_array_append_value (&array, &value);
928     g_value_unset (&value);
929   }
930   gst_structure_set_value (structure, "streamheader", &array);
931   g_value_unset (&array);
932
933   return caps;
934 }
935
936 /*
937  * For each pad we need to write out one (small) header in one
938  * page that allows decoders to identify the type of the stream.
939  * After that we need to write out all extra info for the decoders.
940  * In the case of a codec that also needs data as configuration, we can
941  * find that info in the streamcaps. 
942  * After writing the headers we must start a new page for the data.
943  */
944 static GstFlowReturn
945 gst_ogg_mux_send_headers (GstOggMux * mux)
946 {
947   GSList *walk;
948   GList *hbufs, *hwalk;
949   GstCaps *caps;
950   GstFlowReturn ret;
951
952   hbufs = NULL;
953   ret = GST_FLOW_OK;
954
955   GST_LOG_OBJECT (mux, "collecting headers");
956
957   walk = mux->collect->data;
958   while (walk) {
959     GstOggPad *pad;
960     GstPad *thepad;
961
962     pad = (GstOggPad *) walk->data;
963     thepad = pad->collect.pad;
964
965     walk = g_slist_next (walk);
966
967     GST_LOG_OBJECT (mux, "looking at pad %s:%s", GST_DEBUG_PAD_NAME (thepad));
968
969     /* if the pad has no buffer, we don't care */
970     if (pad->buffer == NULL && pad->next_buffer == NULL)
971       continue;
972
973     /* now figure out the headers */
974     pad->headers = gst_ogg_mux_get_headers (pad);
975   }
976
977   GST_LOG_OBJECT (mux, "creating BOS pages");
978   walk = mux->collect->data;
979   while (walk) {
980     GstOggPad *pad;
981     GstBuffer *buf;
982     ogg_packet packet;
983     ogg_page page;
984     GstPad *thepad;
985     GstCaps *caps;
986     GstStructure *structure;
987     GstBuffer *hbuf;
988
989     pad = (GstOggPad *) walk->data;
990     thepad = pad->collect.pad;
991     caps = gst_pad_get_negotiated_caps (thepad);
992     structure = gst_caps_get_structure (caps, 0);
993
994     walk = walk->next;
995
996     pad->packetno = 0;
997
998     GST_LOG_OBJECT (thepad, "looping over headers");
999
1000     if (pad->headers) {
1001       buf = GST_BUFFER (pad->headers->data);
1002       pad->headers = g_list_remove (pad->headers, buf);
1003     } else if (pad->buffer) {
1004       buf = pad->buffer;
1005       gst_buffer_ref (buf);
1006     } else if (pad->next_buffer) {
1007       buf = pad->next_buffer;
1008       gst_buffer_ref (buf);
1009     } else {
1010       /* fixme -- should be caught in the previous list traversal. */
1011       GST_OBJECT_LOCK (pad);
1012       g_critical ("No headers or buffers on pad %s:%s",
1013           GST_DEBUG_PAD_NAME (pad));
1014       GST_OBJECT_UNLOCK (pad);
1015       continue;
1016     }
1017
1018     /* create a packet from the buffer */
1019     packet.packet = GST_BUFFER_DATA (buf);
1020     packet.bytes = GST_BUFFER_SIZE (buf);
1021     packet.granulepos = GST_BUFFER_OFFSET_END (buf);
1022     if (packet.granulepos == -1)
1023       packet.granulepos = 0;
1024     /* mark BOS and packet number */
1025     packet.b_o_s = (pad->packetno == 0);
1026     packet.packetno = pad->packetno++;
1027     /* mark EOS */
1028     packet.e_o_s = 0;
1029
1030     /* swap the packet in */
1031     ogg_stream_packetin (&pad->stream, &packet);
1032     gst_buffer_unref (buf);
1033
1034     GST_LOG_OBJECT (thepad, "flushing out BOS page");
1035     if (!ogg_stream_flush (&pad->stream, &page))
1036       g_critical ("Could not flush BOS page");
1037
1038     hbuf = gst_ogg_mux_buffer_from_page (mux, &page, FALSE);
1039
1040     GST_LOG_OBJECT (mux, "swapped out page with mime type %s",
1041         gst_structure_get_name (structure));
1042
1043     /* quick hack: put Theora and Dirac video pages at the front.
1044      * Ideally, we would have a settable enum for which Ogg
1045      * profile we work with, and order based on that.
1046      * (FIXME: if there is more than one video stream, shouldn't we only put
1047      * one's BOS into the first page, followed by an audio stream's BOS, and
1048      * only then followed by the remaining video and audio streams?) */
1049     if (gst_structure_has_name (structure, "video/x-theora")) {
1050       GST_DEBUG_OBJECT (thepad, "putting %s page at the front", "Theora");
1051       hbufs = g_list_prepend (hbufs, hbuf);
1052       pad->always_flush_page = TRUE;
1053     } else if (gst_structure_has_name (structure, "video/x-dirac")) {
1054       GST_DEBUG_OBJECT (thepad, "putting %s page at the front", "Dirac");
1055       hbufs = g_list_prepend (hbufs, hbuf);
1056       pad->always_flush_page = TRUE;
1057     } else {
1058       hbufs = g_list_append (hbufs, hbuf);
1059     }
1060     gst_caps_unref (caps);
1061   }
1062
1063   GST_LOG_OBJECT (mux, "creating next headers");
1064   walk = mux->collect->data;
1065   while (walk) {
1066     GstOggPad *pad;
1067     GstPad *thepad;
1068
1069     pad = (GstOggPad *) walk->data;
1070     thepad = pad->collect.pad;
1071
1072     walk = walk->next;
1073
1074     GST_LOG_OBJECT (mux, "looping over headers for pad %s:%s",
1075         GST_DEBUG_PAD_NAME (thepad));
1076
1077     hwalk = pad->headers;
1078     while (hwalk) {
1079       GstBuffer *buf = GST_BUFFER (hwalk->data);
1080       ogg_packet packet;
1081       ogg_page page;
1082
1083       hwalk = hwalk->next;
1084
1085       /* create a packet from the buffer */
1086       packet.packet = GST_BUFFER_DATA (buf);
1087       packet.bytes = GST_BUFFER_SIZE (buf);
1088       packet.granulepos = GST_BUFFER_OFFSET_END (buf);
1089       if (packet.granulepos == -1)
1090         packet.granulepos = 0;
1091       /* mark BOS and packet number */
1092       packet.b_o_s = (pad->packetno == 0);
1093       packet.packetno = pad->packetno++;
1094       /* mark EOS */
1095       packet.e_o_s = 0;
1096
1097       /* swap the packet in */
1098       ogg_stream_packetin (&pad->stream, &packet);
1099       gst_buffer_unref (buf);
1100
1101       /* if last header, flush page */
1102       if (hwalk == NULL) {
1103         GST_LOG_OBJECT (mux,
1104             "flushing page as packet %" G_GUINT64_FORMAT " is first or "
1105             "last packet", pad->packetno);
1106         while (ogg_stream_flush (&pad->stream, &page)) {
1107           GstBuffer *hbuf = gst_ogg_mux_buffer_from_page (mux, &page, FALSE);
1108
1109           GST_LOG_OBJECT (mux, "swapped out page");
1110           hbufs = g_list_append (hbufs, hbuf);
1111         }
1112       } else {
1113         GST_LOG_OBJECT (mux, "try to swap out page");
1114         /* just try to swap out a page then */
1115         while (ogg_stream_pageout (&pad->stream, &page) > 0) {
1116           GstBuffer *hbuf = gst_ogg_mux_buffer_from_page (mux, &page, FALSE);
1117
1118           GST_LOG_OBJECT (mux, "swapped out page");
1119           hbufs = g_list_append (hbufs, hbuf);
1120         }
1121       }
1122     }
1123     g_list_free (pad->headers);
1124     pad->headers = NULL;
1125   }
1126   /* hbufs holds all buffers for the headers now */
1127
1128   /* create caps with the buffers */
1129   caps = gst_pad_get_caps (mux->srcpad);
1130   if (caps) {
1131     caps = gst_ogg_mux_set_header_on_caps (caps, hbufs);
1132     gst_pad_set_caps (mux->srcpad, caps);
1133     gst_caps_unref (caps);
1134   }
1135   /* and send the buffers */
1136   hwalk = hbufs;
1137   while (hwalk) {
1138     GstBuffer *buf = GST_BUFFER (hwalk->data);
1139
1140     hwalk = hwalk->next;
1141
1142     if ((ret = gst_ogg_mux_push_buffer (mux, buf)) != GST_FLOW_OK)
1143       break;
1144   }
1145   g_list_free (hbufs);
1146
1147   return ret;
1148 }
1149
1150 /* this function is called to process data on the best pending pad.
1151  *
1152  * basic idea:
1153  *
1154  * 1) store the selected pad and keep on pulling until we fill a
1155  *    complete ogg page or the ogg page is filled above the max-delay
1156  *    threshold. This is needed because the ogg spec says that
1157  *    you should fill a complete page with data from the same logical
1158  *    stream. When the page is filled, go back to 1).
1159  * 2) before filling a page, read ahead one more buffer to see if this
1160  *    packet is the last of the stream. We need to do this because the ogg
1161  *    spec mandates that the last packet should have the EOS flag set before
1162  *    sending it to ogg. if pad->buffer is NULL we need to wait to find out
1163  *    whether there are any more buffers.
1164  * 3) pages get queued on a per-pad queue. Every time a page is queued, a
1165  *    dequeue is called, which will dequeue the oldest page on any pad, provided
1166  *    that ALL pads have at least one marked page in the queue (or remaining
1167  *    pads are at EOS)
1168  */
1169 static GstFlowReturn
1170 gst_ogg_mux_process_best_pad (GstOggMux * ogg_mux, GstOggPad * best)
1171 {
1172   GstFlowReturn ret = GST_FLOW_OK;
1173   gboolean delta_unit;
1174   gint64 granulepos = 0;
1175   GstClockTime timestamp, gp_time;
1176
1177   GST_LOG_OBJECT (ogg_mux, "best pad %" GST_PTR_FORMAT
1178       ", currently pulling from %" GST_PTR_FORMAT, best->collect.pad,
1179       ogg_mux->pulling);
1180
1181   /* best->buffer is non-NULL, either the pad is EOS's or there is a next 
1182    * buffer */
1183   if (best->next_buffer == NULL && !best->eos) {
1184     GST_WARNING_OBJECT (ogg_mux, "no subsequent buffer and EOS not reached");
1185     return GST_FLOW_WRONG_STATE;
1186   }
1187
1188   /* if we were already pulling from one pad, but the new "best" buffer is
1189    * from another pad, we need to check if we have reason to flush a page
1190    * for the pad we were pulling from before */
1191   if (ogg_mux->pulling && best &&
1192       ogg_mux->pulling != best && ogg_mux->pulling->buffer) {
1193     GstOggPad *pad = ogg_mux->pulling;
1194
1195     GstClockTime last_ts = GST_BUFFER_END_TIME (pad->buffer);
1196
1197     /* if the next packet in the current page is going to make the page
1198      * too long, we need to flush */
1199     if (last_ts > ogg_mux->next_ts + ogg_mux->max_delay) {
1200       ogg_page page;
1201
1202       GST_LOG_OBJECT (pad->collect.pad,
1203           GST_GP_FORMAT " stored packet %" G_GINT64_FORMAT
1204           " will make page too long, flushing",
1205           GST_BUFFER_OFFSET_END (pad->buffer), pad->stream.packetno);
1206
1207       while (ogg_stream_flush (&pad->stream, &page)) {
1208         /* end time of this page is the timestamp of the next buffer */
1209         ogg_mux->pulling->timestamp_end = GST_BUFFER_TIMESTAMP (pad->buffer);
1210         /* Place page into the per-pad queue */
1211         ret = gst_ogg_mux_pad_queue_page (ogg_mux, pad, &page,
1212             pad->first_delta);
1213         /* increment the page number counter */
1214         pad->pageno++;
1215         /* mark other pages as delta */
1216         pad->first_delta = TRUE;
1217       }
1218       pad->new_page = TRUE;
1219       ogg_mux->pulling = NULL;
1220     }
1221   }
1222
1223   /* if we don't know which pad to pull on, use the best one */
1224   if (ogg_mux->pulling == NULL) {
1225     ogg_mux->pulling = best;
1226     GST_LOG_OBJECT (ogg_mux->pulling->collect.pad, "pulling from best pad");
1227
1228     /* remember timestamp and gp time of first buffer for this new pad */
1229     if (ogg_mux->pulling != NULL) {
1230       ogg_mux->next_ts = GST_BUFFER_TIMESTAMP (ogg_mux->pulling->buffer);
1231       GST_LOG_OBJECT (ogg_mux->pulling->collect.pad, "updated times, next ts %"
1232           GST_TIME_FORMAT, GST_TIME_ARGS (ogg_mux->next_ts));
1233     } else {
1234       /* no pad to pull on, send EOS */
1235       gst_pad_push_event (ogg_mux->srcpad, gst_event_new_eos ());
1236       return GST_FLOW_WRONG_STATE;
1237     }
1238   }
1239
1240   if (ogg_mux->need_headers) {
1241     ret = gst_ogg_mux_send_headers (ogg_mux);
1242     ogg_mux->need_headers = FALSE;
1243   }
1244
1245   /* we are pulling from a pad, continue to do so until a page
1246    * has been filled and queued */
1247   if (ogg_mux->pulling != NULL) {
1248     ogg_packet packet;
1249     ogg_page page;
1250     GstBuffer *buf, *tmpbuf;
1251     GstOggPad *pad = ogg_mux->pulling;
1252     gint64 duration;
1253     gboolean force_flush;
1254
1255     GST_LOG_OBJECT (ogg_mux->pulling->collect.pad, "pulling from pad");
1256
1257     /* now see if we have a buffer */
1258     buf = pad->buffer;
1259     if (buf == NULL) {
1260       GST_DEBUG_OBJECT (ogg_mux, "pad was EOS");
1261       ogg_mux->pulling = NULL;
1262       return GST_FLOW_OK;
1263     }
1264
1265     delta_unit = GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
1266     duration = GST_BUFFER_DURATION (buf);
1267
1268     /* if the current "next timestamp" on the pad is unset, then this is the
1269      * first packet on the new page.  Update our pad's page timestamp */
1270     if (ogg_mux->pulling->timestamp == GST_CLOCK_TIME_NONE) {
1271       ogg_mux->pulling->timestamp = GST_BUFFER_TIMESTAMP (buf);
1272       GST_LOG_OBJECT (ogg_mux->pulling->collect.pad,
1273           "updated pad timestamp to %" GST_TIME_FORMAT,
1274           GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
1275     }
1276     /* create a packet from the buffer */
1277     packet.packet = GST_BUFFER_DATA (buf);
1278     packet.bytes = GST_BUFFER_SIZE (buf);
1279     packet.granulepos = GST_BUFFER_OFFSET_END (buf);
1280     if (packet.granulepos == -1)
1281       packet.granulepos = 0;
1282     /* mark BOS and packet number */
1283     packet.b_o_s = (pad->packetno == 0);
1284     packet.packetno = pad->packetno++;
1285     GST_LOG_OBJECT (pad->collect.pad, GST_GP_FORMAT
1286         " packet %" G_GINT64_FORMAT " (%ld bytes) created from buffer",
1287         packet.granulepos, packet.packetno, packet.bytes);
1288
1289     packet.e_o_s = (pad->eos ? 1 : 0);
1290     tmpbuf = NULL;
1291
1292     /* we flush when we see a new keyframe */
1293     force_flush = (pad->prev_delta && !delta_unit) || pad->always_flush_page;
1294     if (duration != -1) {
1295       pad->duration += duration;
1296       /* if page duration exceeds max, flush page */
1297       if (pad->duration > ogg_mux->max_page_delay) {
1298         force_flush = TRUE;
1299         pad->duration = 0;
1300       }
1301     }
1302
1303     if (GST_BUFFER_IS_DISCONT (buf)) {
1304       GST_LOG_OBJECT (pad->collect.pad, "got discont");
1305       packet.packetno++;
1306       /* No public API for this; hack things in */
1307       pad->stream.pageno++;
1308       force_flush = TRUE;
1309     }
1310
1311     /* flush the currently built page if necessary */
1312     if (force_flush) {
1313       GST_LOG_OBJECT (pad->collect.pad,
1314           GST_GP_FORMAT " forced flush of page before this packet",
1315           GST_BUFFER_OFFSET_END (pad->buffer));
1316       while (ogg_stream_flush (&pad->stream, &page)) {
1317         /* end time of this page is the timestamp of the next buffer */
1318         ogg_mux->pulling->timestamp_end = GST_BUFFER_TIMESTAMP (pad->buffer);
1319         ret = gst_ogg_mux_pad_queue_page (ogg_mux, pad, &page,
1320             pad->first_delta);
1321
1322         /* increment the page number counter */
1323         pad->pageno++;
1324         /* mark other pages as delta */
1325         pad->first_delta = TRUE;
1326       }
1327       pad->new_page = TRUE;
1328     }
1329
1330     /* if this is the first packet of a new page figure out the delta flag */
1331     if (pad->new_page) {
1332       if (delta_unit) {
1333         /* mark the page as delta */
1334         pad->first_delta = TRUE;
1335       } else {
1336         /* got a keyframe */
1337         if (ogg_mux->delta_pad == pad) {
1338           /* if we get it on the pad with deltaunits,
1339            * we mark the page as non delta */
1340           pad->first_delta = FALSE;
1341         } else if (ogg_mux->delta_pad != NULL) {
1342           /* if there are pads with delta frames, we
1343            * must mark this one as delta */
1344           pad->first_delta = TRUE;
1345         } else {
1346           pad->first_delta = FALSE;
1347         }
1348       }
1349       pad->new_page = FALSE;
1350     }
1351
1352     /* save key unit to track delta->key unit transitions */
1353     pad->prev_delta = delta_unit;
1354
1355     /* swap the packet in */
1356     if (packet.e_o_s == 1)
1357       GST_DEBUG_OBJECT (pad->collect.pad, "swapping in EOS packet");
1358     if (packet.b_o_s == 1)
1359       GST_DEBUG_OBJECT (pad->collect.pad, "swapping in BOS packet");
1360
1361     ogg_stream_packetin (&pad->stream, &packet);
1362
1363     gp_time = GST_BUFFER_OFFSET (pad->buffer);
1364     granulepos = GST_BUFFER_OFFSET_END (pad->buffer);
1365     timestamp = GST_BUFFER_TIMESTAMP (pad->buffer);
1366
1367     GST_LOG_OBJECT (pad->collect.pad,
1368         GST_GP_FORMAT " packet %" G_GINT64_FORMAT ", gp time %"
1369         GST_TIME_FORMAT ", timestamp %" GST_TIME_FORMAT " packetin'd",
1370         granulepos, packet.packetno, GST_TIME_ARGS (gp_time),
1371         GST_TIME_ARGS (timestamp));
1372     /* don't need the old buffer anymore */
1373     gst_buffer_unref (pad->buffer);
1374     /* store new readahead buffer */
1375     pad->buffer = tmpbuf;
1376
1377     /* let ogg write out the pages now. The packet we got could end
1378      * up in more than one page so we need to write them all */
1379     if (ogg_stream_pageout (&pad->stream, &page) > 0) {
1380       /* we have a new page, so we need to timestamp it correctly.
1381        * if this fresh packet ends on this page, then the page's granulepos
1382        * comes from that packet, and we should set this buffer's timestamp */
1383
1384       GST_LOG_OBJECT (pad->collect.pad,
1385           GST_GP_FORMAT " packet %" G_GINT64_FORMAT ", time %"
1386           GST_TIME_FORMAT ") caused new page",
1387           granulepos, packet.packetno, GST_TIME_ARGS (timestamp));
1388       GST_LOG_OBJECT (pad->collect.pad,
1389           GST_GP_FORMAT " new page %ld", ogg_page_granulepos (&page),
1390           pad->stream.pageno);
1391
1392       if (ogg_page_granulepos (&page) == granulepos) {
1393         /* the packet we streamed in finishes on the current page,
1394          * because the page's granulepos is the granulepos of the last
1395          * packet completed on that page,
1396          * so update the timestamp that we will give to the page */
1397         GST_LOG_OBJECT (pad->collect.pad,
1398             GST_GP_FORMAT
1399             " packet finishes on current page, updating gp time to %"
1400             GST_TIME_FORMAT, granulepos, GST_TIME_ARGS (gp_time));
1401         pad->gp_time = gp_time;
1402       } else {
1403         GST_LOG_OBJECT (pad->collect.pad,
1404             GST_GP_FORMAT
1405             " packet spans beyond current page, keeping old gp time %"
1406             GST_TIME_FORMAT, granulepos, GST_TIME_ARGS (pad->gp_time));
1407       }
1408
1409       /* push the page */
1410       /* end time of this page is the timestamp of the next buffer */
1411       pad->timestamp_end = timestamp;
1412       ret = gst_ogg_mux_pad_queue_page (ogg_mux, pad, &page, pad->first_delta);
1413       pad->pageno++;
1414       /* mark next pages as delta */
1415       pad->first_delta = TRUE;
1416
1417       /* use an inner loop here to flush the remaining pages and
1418        * mark them as delta frames as well */
1419       while (ogg_stream_pageout (&pad->stream, &page) > 0) {
1420         if (ogg_page_granulepos (&page) == granulepos) {
1421           /* the page has taken up the new packet completely, which means
1422            * the packet ends the page and we can update the gp time
1423            * before pushing out */
1424           pad->gp_time = gp_time;
1425         }
1426
1427         /* we have a complete page now, we can push the page
1428          * and make sure to pull on a new pad the next time around */
1429         ret = gst_ogg_mux_pad_queue_page (ogg_mux, pad, &page,
1430             pad->first_delta);
1431         /* increment the page number counter */
1432         pad->pageno++;
1433       }
1434       /* need a new page as well */
1435       pad->new_page = TRUE;
1436       pad->duration = 0;
1437       /* we're done pulling on this pad, make sure to choose a new
1438        * pad for pulling in the next iteration */
1439       ogg_mux->pulling = NULL;
1440     }
1441
1442     /* Update the gp time, if necessary, since any future page will have at
1443      * least this gp time.
1444      */
1445     if (pad->gp_time < gp_time) {
1446       pad->gp_time = gp_time;
1447       GST_LOG_OBJECT (pad->collect.pad,
1448           "Updated running gp time of pad %" GST_PTR_FORMAT
1449           " to %" GST_TIME_FORMAT, pad->collect.pad, GST_TIME_ARGS (gp_time));
1450     }
1451   }
1452
1453   return ret;
1454 }
1455
1456 /* all_pads_eos:
1457  *
1458  * Checks if all pads are EOS'd by peeking.
1459  *
1460  * Returns TRUE if all pads are EOS.
1461  */
1462 static gboolean
1463 all_pads_eos (GstCollectPads * pads)
1464 {
1465   GSList *walk;
1466   gboolean alleos = TRUE;
1467
1468   walk = pads->data;
1469   while (walk) {
1470     GstBuffer *buf;
1471     GstCollectData *data = (GstCollectData *) walk->data;
1472
1473     buf = gst_collect_pads_peek (pads, data);
1474     if (buf) {
1475       alleos = FALSE;
1476       gst_buffer_unref (buf);
1477       goto beach;
1478     }
1479     walk = walk->next;
1480   }
1481 beach:
1482   return alleos;
1483 }
1484
1485 /* This function is called when there is data on all pads.
1486  * 
1487  * It finds a pad to pull on, this is done by looking at the buffers
1488  * to decide which one to use, and using the 'oldest' one first. It then calls
1489  * gst_ogg_mux_process_best_pad() to process as much data as possible.
1490  * 
1491  * If all the pads have received EOS, it flushes out all data by continually
1492  * getting the best pad and calling gst_ogg_mux_process_best_pad() until they
1493  * are all empty, and then sends EOS.
1494  */
1495 static GstFlowReturn
1496 gst_ogg_mux_collected (GstCollectPads * pads, GstOggMux * ogg_mux)
1497 {
1498   GstOggPad *best;
1499   GstFlowReturn ret;
1500   gint activebefore;
1501
1502   GST_LOG_OBJECT (ogg_mux, "collected");
1503
1504   activebefore = ogg_mux->active_pads;
1505
1506   /* queue buffers on all pads; find a buffer with the lowest timestamp */
1507   best = gst_ogg_mux_queue_pads (ogg_mux);
1508   if (best && !best->buffer) {
1509     GST_DEBUG_OBJECT (ogg_mux, "No buffer available on best pad");
1510     return GST_FLOW_OK;
1511   }
1512
1513   if (!best) {
1514     return GST_FLOW_WRONG_STATE;
1515   }
1516
1517   ret = gst_ogg_mux_process_best_pad (ogg_mux, best);
1518
1519   if (ogg_mux->active_pads < activebefore) {
1520     /* If the active pad count went down, this mean at least one pad has gone
1521      * EOS. Since CollectPads only calls _collected() once when all pads are
1522      * EOS, and our code doesn't _pop() from all pads we need to check that by
1523      * peeking on all pads, else we won't be called again and the muxing will
1524      * not terminate (push out EOS). */
1525
1526     /* if all the pads have been removed, flush all pending data */
1527     if ((ret == GST_FLOW_OK) && all_pads_eos (pads)) {
1528       GST_LOG_OBJECT (ogg_mux, "no pads remaining, flushing data");
1529
1530       do {
1531         best = gst_ogg_mux_queue_pads (ogg_mux);
1532         if (best)
1533           ret = gst_ogg_mux_process_best_pad (ogg_mux, best);
1534       } while ((ret == GST_FLOW_OK) && (best != NULL));
1535
1536       GST_DEBUG_OBJECT (ogg_mux, "Pushing EOS");
1537       gst_pad_push_event (ogg_mux->srcpad, gst_event_new_eos ());
1538     }
1539   }
1540
1541   return ret;
1542 }
1543
1544 static void
1545 gst_ogg_mux_get_property (GObject * object,
1546     guint prop_id, GValue * value, GParamSpec * pspec)
1547 {
1548   GstOggMux *ogg_mux;
1549
1550   ogg_mux = GST_OGG_MUX (object);
1551
1552   switch (prop_id) {
1553     case ARG_MAX_DELAY:
1554       g_value_set_uint64 (value, ogg_mux->max_delay);
1555       break;
1556     case ARG_MAX_PAGE_DELAY:
1557       g_value_set_uint64 (value, ogg_mux->max_page_delay);
1558       break;
1559     default:
1560       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1561       break;
1562   }
1563 }
1564
1565 static void
1566 gst_ogg_mux_set_property (GObject * object,
1567     guint prop_id, const GValue * value, GParamSpec * pspec)
1568 {
1569   GstOggMux *ogg_mux;
1570
1571   ogg_mux = GST_OGG_MUX (object);
1572
1573   switch (prop_id) {
1574     case ARG_MAX_DELAY:
1575       ogg_mux->max_delay = g_value_get_uint64 (value);
1576       break;
1577     case ARG_MAX_PAGE_DELAY:
1578       ogg_mux->max_page_delay = g_value_get_uint64 (value);
1579       break;
1580     default:
1581       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1582       break;
1583   }
1584 }
1585
1586 /* reset all variables in the ogg pads. */
1587 static void
1588 gst_ogg_mux_init_collectpads (GstCollectPads * collect)
1589 {
1590   GSList *walk;
1591
1592   walk = collect->data;
1593   while (walk) {
1594     GstOggPad *oggpad = (GstOggPad *) walk->data;
1595
1596     ogg_stream_init (&oggpad->stream, oggpad->serial);
1597     oggpad->packetno = 0;
1598     oggpad->pageno = 0;
1599     oggpad->eos = FALSE;
1600     /* we assume there will be some control data first for this pad */
1601     oggpad->state = GST_OGG_PAD_STATE_CONTROL;
1602     oggpad->new_page = TRUE;
1603     oggpad->first_delta = FALSE;
1604     oggpad->prev_delta = FALSE;
1605     oggpad->pagebuffers = g_queue_new ();
1606
1607     walk = g_slist_next (walk);
1608   }
1609 }
1610
1611 /* Clear all buffers from the collectpads object */
1612 static void
1613 gst_ogg_mux_clear_collectpads (GstCollectPads * collect)
1614 {
1615   GSList *walk;
1616
1617   for (walk = collect->data; walk; walk = g_slist_next (walk)) {
1618     GstOggPad *oggpad = (GstOggPad *) walk->data;
1619     GstBuffer *buf;
1620
1621     ogg_stream_clear (&oggpad->stream);
1622
1623     while ((buf = g_queue_pop_head (oggpad->pagebuffers)) != NULL) {
1624       gst_buffer_unref (buf);
1625     }
1626     g_queue_free (oggpad->pagebuffers);
1627     oggpad->pagebuffers = NULL;
1628
1629     if (oggpad->buffer) {
1630       gst_buffer_unref (oggpad->buffer);
1631       oggpad->buffer = NULL;
1632     }
1633     if (oggpad->next_buffer) {
1634       gst_buffer_unref (oggpad->next_buffer);
1635       oggpad->next_buffer = NULL;
1636     }
1637   }
1638 }
1639
1640 static GstStateChangeReturn
1641 gst_ogg_mux_change_state (GstElement * element, GstStateChange transition)
1642 {
1643   GstOggMux *ogg_mux;
1644   GstStateChangeReturn ret;
1645
1646   ogg_mux = GST_OGG_MUX (element);
1647
1648   switch (transition) {
1649     case GST_STATE_CHANGE_NULL_TO_READY:
1650       break;
1651     case GST_STATE_CHANGE_READY_TO_PAUSED:
1652       gst_ogg_mux_clear (ogg_mux);
1653       gst_ogg_mux_init_collectpads (ogg_mux->collect);
1654       gst_collect_pads_start (ogg_mux->collect);
1655       break;
1656     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1657       break;
1658     case GST_STATE_CHANGE_PAUSED_TO_READY:
1659       gst_collect_pads_stop (ogg_mux->collect);
1660       break;
1661     default:
1662       break;
1663   }
1664
1665   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1666
1667   switch (transition) {
1668     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1669       break;
1670     case GST_STATE_CHANGE_PAUSED_TO_READY:
1671       gst_ogg_mux_clear_collectpads (ogg_mux->collect);
1672       break;
1673     case GST_STATE_CHANGE_READY_TO_NULL:
1674       break;
1675     default:
1676       break;
1677   }
1678
1679   return ret;
1680 }
1681
1682 gboolean
1683 gst_ogg_mux_plugin_init (GstPlugin * plugin)
1684 {
1685   GST_DEBUG_CATEGORY_INIT (gst_ogg_mux_debug, "oggmux", 0, "ogg muxer");
1686
1687   return gst_element_register (plugin, "oggmux", GST_RANK_PRIMARY,
1688       GST_TYPE_OGG_MUX);
1689 }