Don't do crazy things with 0/1 framerates
[platform/upstream/gst-plugins-good.git] / gst / matroska / matroska-mux.c
1 /* GStreamer Matroska muxer/demuxer
2  * (c) 2003 Ronald Bultje <rbultje@ronald.bitfreak.net>
3  * (c) 2005 Michal Benes <michal.benes@xeris.cz>
4  * (c) 2008 Sebastian Dröge <sebastian.droege@collabora.co.uk>
5  *
6  * matroska-mux.c: matroska file/stream muxer
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 /* TODO: - check everywhere that we don't write invalid values
25  *       - make sure timestamps are correctly scaled everywhere
26  */
27
28 /**
29  * SECTION:element-matroskamux
30  *
31  * matroskamux muxes different input streams into a Matroska file.
32  *
33  * <refsect2>
34  * <title>Example launch line</title>
35  * |[
36  * gst-launch -v filesrc location=/path/to/mp3 ! mp3parse ! matroskamux name=mux ! filesink location=test.mkv  filesrc location=/path/to/theora.ogg ! oggdemux ! theoraparse ! mux.
37  * ]| This pipeline muxes an MP3 file and a Ogg Theora video into a Matroska file.
38  * |[
39  * gst-launch -v audiotestsrc num-buffers=100 ! audioconvert ! vorbisenc ! matroskamux ! filesink location=test.mka
40  * ]| This pipeline muxes a 440Hz sine wave encoded with the Vorbis codec into a Matroska file.
41  * </refsect2>
42  */
43
44 #ifdef HAVE_CONFIG_H
45 #include "config.h"
46 #endif
47
48 #include <math.h>
49 #include <string.h>
50
51 #include "matroska-mux.h"
52 #include "matroska-ids.h"
53
54 GST_DEBUG_CATEGORY_STATIC (matroskamux_debug);
55 #define GST_CAT_DEFAULT matroskamux_debug
56
57 enum
58 {
59   ARG_0,
60   ARG_WRITING_APP,
61   ARG_MATROSKA_VERSION
62 };
63
64 #define  DEFAULT_MATROSKA_VERSION        1
65 #define  DEFAULT_WRITING_APP             "GStreamer Matroska muxer"
66
67 static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE ("src",
68     GST_PAD_SRC,
69     GST_PAD_ALWAYS,
70     GST_STATIC_CAPS ("video/x-matroska")
71     );
72
73 #define COMMON_VIDEO_CAPS \
74   "width = (int) [ 16, 4096 ], " \
75   "height = (int) [ 16, 4096 ], " \
76   "framerate = (fraction) [ 0, MAX ]"
77
78 #define COMMON_VIDEO_CAPS_NO_FRAMERATE \
79   "width = (int) [ 16, 4096 ], " \
80   "height = (int) [ 16, 4096 ] "
81
82 /* FIXME: 
83  * * require codec data, etc as needed
84  */
85
86 static GstStaticPadTemplate videosink_templ =
87     GST_STATIC_PAD_TEMPLATE ("video_%d",
88     GST_PAD_SINK,
89     GST_PAD_REQUEST,
90     GST_STATIC_CAPS ("video/mpeg, "
91         "mpegversion = (int) { 1, 2, 4 }, "
92         "systemstream = (boolean) false, "
93         COMMON_VIDEO_CAPS "; "
94         "video/x-h264, "
95         COMMON_VIDEO_CAPS "; "
96         "video/x-divx, "
97         COMMON_VIDEO_CAPS "; "
98         "video/x-xvid, "
99         COMMON_VIDEO_CAPS "; "
100         "video/x-huffyuv, "
101         COMMON_VIDEO_CAPS "; "
102         "video/x-dv, "
103         COMMON_VIDEO_CAPS "; "
104         "video/x-h263, "
105         COMMON_VIDEO_CAPS "; "
106         "video/x-msmpeg, "
107         COMMON_VIDEO_CAPS "; "
108         "image/jpeg, "
109         COMMON_VIDEO_CAPS_NO_FRAMERATE "; "
110         "video/x-theora; "
111         "video/x-dirac, "
112         COMMON_VIDEO_CAPS "; "
113         "video/x-pn-realvideo, "
114         "rmversion = (int) [1, 4], "
115         COMMON_VIDEO_CAPS "; "
116         "video/x-raw-yuv, "
117         "format = (fourcc) { YUY2, I420, YV12, UYVY, AYUV }, "
118         COMMON_VIDEO_CAPS)
119     );
120
121 #define COMMON_AUDIO_CAPS \
122   "channels = (int) [ 1, MAX ], " \
123   "rate = (int) [ 1, MAX ]"
124
125 /* FIXME:
126  * * require codec data, etc as needed
127  */
128 static GstStaticPadTemplate audiosink_templ =
129     GST_STATIC_PAD_TEMPLATE ("audio_%d",
130     GST_PAD_SINK,
131     GST_PAD_REQUEST,
132     GST_STATIC_CAPS ("audio/mpeg, "
133         "mpegversion = (int) 1, "
134         "layer = (int) [ 1, 3 ], "
135         COMMON_AUDIO_CAPS "; "
136         "audio/mpeg, "
137         "mpegversion = (int) { 2, 4 }, "
138         COMMON_AUDIO_CAPS "; "
139         "audio/x-ac3, "
140         COMMON_AUDIO_CAPS "; "
141         "audio/x-vorbis, "
142         COMMON_AUDIO_CAPS "; "
143         "audio/x-flac, "
144         COMMON_AUDIO_CAPS "; "
145         "audio/x-raw-int, "
146         "width = (int) 8, "
147         "depth = (int) 8, "
148         "signed = (boolean) false, "
149         COMMON_AUDIO_CAPS ";"
150         "audio/x-raw-int, "
151         "width = (int) 16, "
152         "depth = (int) 16, "
153         "endianness = (int) { BIG_ENDIAN, LITTLE_ENDIAN }, "
154         "signed = (boolean) true, "
155         COMMON_AUDIO_CAPS ";"
156         "audio/x-raw-int, "
157         "width = (int) 24, "
158         "depth = (int) 24, "
159         "endianness = (int) { BIG_ENDIAN, LITTLE_ENDIAN }, "
160         "signed = (boolean) true, "
161         COMMON_AUDIO_CAPS ";"
162         "audio/x-raw-int, "
163         "width = (int) 32, "
164         "depth = (int) 32, "
165         "endianness = (int) { BIG_ENDIAN, LITTLE_ENDIAN }, "
166         "signed = (boolean) true, "
167         COMMON_AUDIO_CAPS ";"
168         "audio/x-raw-float, "
169         "width = (int) [ 32, 64 ], "
170         "endianness = (int) LITTLE_ENDIAN, "
171         COMMON_AUDIO_CAPS ";"
172         "audio/x-tta, "
173         "width = (int) { 8, 16, 24 }, "
174         "channels = (int) { 1, 2 }, " "rate = (int) [ 8000, 96000 ]; "
175         "audio/x-pn-realaudio, "
176         "raversion = (int) { 1, 2, 8 }, " COMMON_AUDIO_CAPS ";")
177     );
178
179 static GstStaticPadTemplate subtitlesink_templ =
180 GST_STATIC_PAD_TEMPLATE ("subtitle_%d",
181     GST_PAD_SINK,
182     GST_PAD_REQUEST,
183     GST_STATIC_CAPS_ANY);
184
185 static GArray *used_uids;
186 G_LOCK_DEFINE_STATIC (used_uids);
187
188 static void gst_matroska_mux_add_interfaces (GType type);
189
190 GST_BOILERPLATE_FULL (GstMatroskaMux, gst_matroska_mux, GstElement,
191     GST_TYPE_ELEMENT, gst_matroska_mux_add_interfaces);
192
193 /* Matroska muxer destructor */
194 static void gst_matroska_mux_finalize (GObject * object);
195
196 /* Pads collected callback */
197 static GstFlowReturn
198 gst_matroska_mux_collected (GstCollectPads * pads, gpointer user_data);
199
200 /* pad functions */
201 static gboolean gst_matroska_mux_handle_src_event (GstPad * pad,
202     GstEvent * event);
203 static GstPad *gst_matroska_mux_request_new_pad (GstElement * element,
204     GstPadTemplate * templ, const gchar * name);
205 static void gst_matroska_mux_release_pad (GstElement * element, GstPad * pad);
206
207 /* gst internal change state handler */
208 static GstStateChangeReturn
209 gst_matroska_mux_change_state (GstElement * element, GstStateChange transition);
210
211 /* gobject bla bla */
212 static void gst_matroska_mux_set_property (GObject * object,
213     guint prop_id, const GValue * value, GParamSpec * pspec);
214 static void gst_matroska_mux_get_property (GObject * object,
215     guint prop_id, GValue * value, GParamSpec * pspec);
216
217 /* reset muxer */
218 static void gst_matroska_mux_reset (GstElement * element);
219
220 /* uid generation */
221 static guint64 gst_matroska_mux_create_uid ();
222
223 static gboolean theora_streamheader_to_codecdata (const GValue * streamheader,
224     GstMatroskaTrackContext * context);
225 static gboolean vorbis_streamheader_to_codecdata (const GValue * streamheader,
226     GstMatroskaTrackContext * context);
227 static gboolean flac_streamheader_to_codecdata (const GValue * streamheader,
228     GstMatroskaTrackContext * context);
229
230 static void
231 gst_matroska_mux_add_interfaces (GType type)
232 {
233   static const GInterfaceInfo tag_setter_info = { NULL, NULL, NULL };
234
235   g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
236 }
237
238 static void
239 gst_matroska_mux_base_init (gpointer g_class)
240 {
241   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
242
243   gst_element_class_add_pad_template (element_class,
244       gst_static_pad_template_get (&videosink_templ));
245   gst_element_class_add_pad_template (element_class,
246       gst_static_pad_template_get (&audiosink_templ));
247   gst_element_class_add_pad_template (element_class,
248       gst_static_pad_template_get (&subtitlesink_templ));
249   gst_element_class_add_pad_template (element_class,
250       gst_static_pad_template_get (&src_templ));
251   gst_element_class_set_details_simple (element_class, "Matroska muxer",
252       "Codec/Muxer",
253       "Muxes video/audio/subtitle streams into a matroska stream",
254       "Ronald Bultje <rbultje@ronald.bitfreak.net>");
255
256   GST_DEBUG_CATEGORY_INIT (matroskamux_debug, "matroskamux", 0,
257       "Matroska muxer");
258 }
259
260 static void
261 gst_matroska_mux_class_init (GstMatroskaMuxClass * klass)
262 {
263   GObjectClass *gobject_class;
264   GstElementClass *gstelement_class;
265
266   gobject_class = (GObjectClass *) klass;
267   gstelement_class = (GstElementClass *) klass;
268
269   gobject_class->finalize = gst_matroska_mux_finalize;
270
271   gobject_class->get_property = gst_matroska_mux_get_property;
272   gobject_class->set_property = gst_matroska_mux_set_property;
273
274   g_object_class_install_property (gobject_class, ARG_WRITING_APP,
275       g_param_spec_string ("writing-app", "Writing application.",
276           "The name the application that creates the matroska file.",
277           NULL, G_PARAM_READWRITE));
278   g_object_class_install_property (gobject_class, ARG_MATROSKA_VERSION,
279       g_param_spec_int ("version", "Matroska version",
280           "This parameter determines what matroska features can be used.",
281           1, 2, DEFAULT_MATROSKA_VERSION, G_PARAM_READWRITE));
282
283   gstelement_class->change_state =
284       GST_DEBUG_FUNCPTR (gst_matroska_mux_change_state);
285   gstelement_class->request_new_pad =
286       GST_DEBUG_FUNCPTR (gst_matroska_mux_request_new_pad);
287   gstelement_class->release_pad =
288       GST_DEBUG_FUNCPTR (gst_matroska_mux_release_pad);
289 }
290
291
292 /**
293  * gst_matroska_mux_init:
294  * @mux: #GstMatroskaMux that should be initialized.
295  * @g_class: Class of the muxer.
296  *
297  * Matroska muxer constructor.
298  */
299 static void
300 gst_matroska_mux_init (GstMatroskaMux * mux, GstMatroskaMuxClass * g_class)
301 {
302   mux->srcpad = gst_pad_new_from_static_template (&src_templ, "src");
303   gst_pad_set_event_function (mux->srcpad, gst_matroska_mux_handle_src_event);
304   gst_element_add_pad (GST_ELEMENT (mux), mux->srcpad);
305
306   mux->collect = gst_collect_pads_new ();
307   gst_collect_pads_set_function (mux->collect,
308       (GstCollectPadsFunction) GST_DEBUG_FUNCPTR (gst_matroska_mux_collected),
309       mux);
310
311   mux->ebml_write = gst_ebml_write_new (mux->srcpad);
312
313   /* property defaults */
314   mux->matroska_version = DEFAULT_MATROSKA_VERSION;
315   mux->writing_app = g_strdup (DEFAULT_WRITING_APP);
316
317   /* initialize internal variables */
318   mux->index = NULL;
319   mux->num_streams = 0;
320   mux->num_a_streams = 0;
321   mux->num_t_streams = 0;
322   mux->num_v_streams = 0;
323
324   /* initialize remaining variables */
325   gst_matroska_mux_reset (GST_ELEMENT (mux));
326 }
327
328
329 /**
330  * gst_matroska_mux_finalize:
331  * @object: #GstMatroskaMux that should be finalized.
332  *
333  * Finalize matroska muxer.
334  */
335 static void
336 gst_matroska_mux_finalize (GObject * object)
337 {
338   GstMatroskaMux *mux = GST_MATROSKA_MUX (object);
339
340   gst_object_unref (mux->collect);
341   gst_object_unref (mux->ebml_write);
342   if (mux->writing_app)
343     g_free (mux->writing_app);
344
345   G_OBJECT_CLASS (parent_class)->finalize (object);
346 }
347
348
349 /**
350  * gst_matroska_mux_create_uid:
351  *
352  * Generate new unused track UID.
353  *
354  * Returns: New track UID.
355  */
356 static guint64
357 gst_matroska_mux_create_uid (void)
358 {
359   guint64 uid = 0;
360
361   G_LOCK (used_uids);
362
363   if (!used_uids)
364     used_uids = g_array_sized_new (FALSE, FALSE, sizeof (guint64), 10);
365
366   while (!uid) {
367     guint i;
368
369     uid = (((guint64) g_random_int ()) << 32) | g_random_int ();
370     for (i = 0; i < used_uids->len; i++) {
371       if (g_array_index (used_uids, guint64, i) == uid) {
372         uid = 0;
373         break;
374       }
375     }
376     g_array_append_val (used_uids, uid);
377   }
378
379   G_UNLOCK (used_uids);
380   return uid;
381 }
382
383
384 /**
385  * gst_matroska_pad_reset:
386  * @collect_pad: the #GstMatroskaPad
387  *
388  * Reset and/or release resources of a matroska collect pad.
389  */
390 static void
391 gst_matroska_pad_reset (GstMatroskaPad * collect_pad, gboolean full)
392 {
393   gchar *name = NULL;
394   GstMatroskaTrackType type = 0;
395
396   /* free track information */
397   if (collect_pad->track != NULL) {
398     /* retrieve for optional later use */
399     name = collect_pad->track->name;
400     type = collect_pad->track->type;
401     /* extra for video */
402     if (type == GST_MATROSKA_TRACK_TYPE_VIDEO) {
403       GstMatroskaTrackVideoContext *ctx =
404           (GstMatroskaTrackVideoContext *) collect_pad->track;
405
406       if (ctx->dirac_unit) {
407         gst_buffer_unref (ctx->dirac_unit);
408         ctx->dirac_unit = NULL;
409       }
410     }
411     g_free (collect_pad->track->codec_id);
412     g_free (collect_pad->track->codec_name);
413     if (full)
414       g_free (collect_pad->track->name);
415     g_free (collect_pad->track->language);
416     g_free (collect_pad->track->codec_priv);
417     g_free (collect_pad->track);
418     collect_pad->track = NULL;
419   }
420
421   /* free cached buffer */
422   if (collect_pad->buffer != NULL) {
423     gst_buffer_unref (collect_pad->buffer);
424     collect_pad->buffer = NULL;
425   }
426
427   if (!full && type != 0) {
428     GstMatroskaTrackContext *context;
429
430     /* create a fresh context */
431     switch (type) {
432       case GST_MATROSKA_TRACK_TYPE_VIDEO:
433         context = (GstMatroskaTrackContext *)
434             g_new0 (GstMatroskaTrackVideoContext, 1);
435         break;
436       case GST_MATROSKA_TRACK_TYPE_AUDIO:
437         context = (GstMatroskaTrackContext *)
438             g_new0 (GstMatroskaTrackAudioContext, 1);
439         break;
440       case GST_MATROSKA_TRACK_TYPE_SUBTITLE:
441         context = (GstMatroskaTrackContext *)
442             g_new0 (GstMatroskaTrackSubtitleContext, 1);
443         break;
444       default:
445         g_assert_not_reached ();
446         break;
447     }
448
449     context->type = type;
450     context->name = name;
451     /* TODO: check default values for the context */
452     context->flags = GST_MATROSKA_TRACK_ENABLED | GST_MATROSKA_TRACK_DEFAULT;
453     collect_pad->track = context;
454     collect_pad->buffer = NULL;
455     collect_pad->duration = 0;
456     collect_pad->start_ts = GST_CLOCK_TIME_NONE;
457     collect_pad->end_ts = GST_CLOCK_TIME_NONE;
458   }
459 }
460
461 /**
462  * gst_matroska_pad_free:
463  * @collect_pad: the #GstMatroskaPad
464  *
465  * Release resources of a matroska collect pad.
466  */
467 static void
468 gst_matroska_pad_free (GstMatroskaPad * collect_pad)
469 {
470   gst_matroska_pad_reset (collect_pad, TRUE);
471 }
472
473
474 /**
475  * gst_matroska_mux_reset:
476  * @element: #GstMatroskaMux that should be reseted.
477  *
478  * Reset matroska muxer back to initial state.
479  */
480 static void
481 gst_matroska_mux_reset (GstElement * element)
482 {
483   GstMatroskaMux *mux = GST_MATROSKA_MUX (element);
484   GSList *walk;
485
486   /* reset EBML write */
487   gst_ebml_write_reset (mux->ebml_write);
488
489   /* reset input */
490   mux->state = GST_MATROSKA_MUX_STATE_START;
491
492   /* clean up existing streams */
493
494   for (walk = mux->collect->data; walk; walk = g_slist_next (walk)) {
495     GstMatroskaPad *collect_pad;
496     GstPad *thepad;
497
498     collect_pad = (GstMatroskaPad *) walk->data;
499     thepad = collect_pad->collect.pad;
500
501     /* reset collect pad to pristine state */
502     gst_matroska_pad_reset (collect_pad, FALSE);
503   }
504
505   /* reset indexes */
506   mux->num_indexes = 0;
507   g_free (mux->index);
508   mux->index = NULL;
509
510   /* reset timers */
511   mux->time_scale = GST_MSECOND;
512   mux->duration = 0;
513
514   /* reset cluster */
515   mux->cluster = 0;
516   mux->cluster_time = 0;
517   mux->cluster_pos = 0;
518
519   /* reset tags */
520   gst_tag_setter_reset_tags (GST_TAG_SETTER (mux));
521 }
522
523 /**
524  * gst_matroska_mux_handle_src_event:
525  * @pad: Pad which received the event.
526  * @event: Received event.
527  *
528  * handle events - copied from oggmux without understanding 
529  *
530  * Returns: #TRUE on success.
531  */
532 static gboolean
533 gst_matroska_mux_handle_src_event (GstPad * pad, GstEvent * event)
534 {
535   GstEventType type;
536
537   type = event ? GST_EVENT_TYPE (event) : GST_EVENT_UNKNOWN;
538
539   switch (type) {
540     case GST_EVENT_SEEK:
541       /* disable seeking for now */
542       return FALSE;
543     default:
544       break;
545   }
546
547   return gst_pad_event_default (pad, event);
548 }
549
550 /**
551  * gst_matroska_mux_handle_sink_event:
552  * @pad: Pad which received the event.
553  * @event: Received event.
554  *
555  * handle events - informational ones like tags
556  *
557  * Returns: #TRUE on success.
558  */
559 static gboolean
560 gst_matroska_mux_handle_sink_event (GstPad * pad, GstEvent * event)
561 {
562   GstMatroskaTrackContext *context;
563   GstMatroskaPad *collect_pad;
564   GstMatroskaMux *mux;
565   GstTagList *list;
566   gboolean ret = TRUE;
567
568   mux = GST_MATROSKA_MUX (gst_pad_get_parent (pad));
569
570   switch (GST_EVENT_TYPE (event)) {
571     case GST_EVENT_TAG:
572       GST_DEBUG_OBJECT (mux, "received tag event");
573       gst_event_parse_tag (event, &list);
574
575       collect_pad = (GstMatroskaPad *) gst_pad_get_element_private (pad);
576       g_assert (collect_pad);
577       context = collect_pad->track;
578       g_assert (context);
579       /* FIXME ?
580        * strictly speaking, the incoming language code may only be 639-1, so not
581        * 639-2 according to matroska specs, but it will have to do for now */
582       gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &context->language);
583
584       gst_tag_setter_merge_tags (GST_TAG_SETTER (mux), list,
585           gst_tag_setter_get_tag_merge_mode (GST_TAG_SETTER (mux)));
586       break;
587     case GST_EVENT_NEWSEGMENT:
588       /* We don't support NEWSEGMENT events */
589       ret = FALSE;
590       gst_event_unref (event);
591       break;
592     default:
593       break;
594   }
595
596   /* now GstCollectPads can take care of the rest, e.g. EOS */
597   if (ret)
598     ret = mux->collect_event (pad, event);
599   gst_object_unref (mux);
600
601   return ret;
602 }
603
604
605 /**
606  * gst_matroska_mux_video_pad_setcaps:
607  * @pad: Pad which got the caps.
608  * @caps: New caps.
609  *
610  * Setcaps function for video sink pad.
611  *
612  * Returns: #TRUE on success.
613  */
614 static gboolean
615 gst_matroska_mux_video_pad_setcaps (GstPad * pad, GstCaps * caps)
616 {
617   GstMatroskaTrackContext *context = NULL;
618   GstMatroskaTrackVideoContext *videocontext;
619   GstMatroskaMux *mux;
620   GstMatroskaPad *collect_pad;
621   GstStructure *structure;
622   const gchar *mimetype;
623   const GValue *value = NULL;
624   const GstBuffer *codec_buf = NULL;
625   gint width, height, pixel_width, pixel_height;
626   gint fps_d, fps_n;
627
628   mux = GST_MATROSKA_MUX (GST_PAD_PARENT (pad));
629
630   /* find context */
631   collect_pad = (GstMatroskaPad *) gst_pad_get_element_private (pad);
632   g_assert (collect_pad);
633   context = collect_pad->track;
634   g_assert (context);
635   g_assert (context->type == GST_MATROSKA_TRACK_TYPE_VIDEO);
636   videocontext = (GstMatroskaTrackVideoContext *) context;
637
638   /* gst -> matroska ID'ing */
639   structure = gst_caps_get_structure (caps, 0);
640
641   mimetype = gst_structure_get_name (structure);
642
643   if (!strcmp (mimetype, "video/x-theora")) {
644     /* we'll extract the details later from the theora identification header */
645     goto skip_details;
646   }
647
648   /* get general properties */
649   gst_structure_get_int (structure, "width", &width);
650   gst_structure_get_int (structure, "height", &height);
651   videocontext->pixel_width = width;
652   videocontext->pixel_height = height;
653   if (gst_structure_get_fraction (structure, "framerate", &fps_n, &fps_d)
654       && fps_n > 0) {
655     context->default_duration =
656         gst_util_uint64_scale_int (GST_SECOND, fps_d, fps_n);
657     GST_LOG_OBJECT (pad, "default duration = %" GST_TIME_FORMAT,
658         GST_TIME_ARGS (context->default_duration));
659   } else {
660     context->default_duration = 0;
661   }
662   if (gst_structure_get_fraction (structure, "pixel-aspect-ratio",
663           &pixel_width, &pixel_height)) {
664     if (pixel_width > pixel_height) {
665       videocontext->display_width = width * pixel_width / pixel_height;
666       videocontext->display_height = height;
667     } else if (pixel_width < pixel_height) {
668       videocontext->display_width = width;
669       videocontext->display_height = height * pixel_height / pixel_width;
670     } else {
671       videocontext->display_width = 0;
672       videocontext->display_height = 0;
673     }
674   } else {
675     videocontext->display_width = 0;
676     videocontext->display_height = 0;
677   }
678
679 skip_details:
680
681   videocontext->asr_mode = GST_MATROSKA_ASPECT_RATIO_MODE_FREE;
682   videocontext->fourcc = 0;
683
684   /* TODO: - check if we handle all codecs by the spec, i.e. codec private
685    *         data and other settings
686    *       - add new formats
687    */
688
689   /* extract codec_data, may turn out needed */
690   value = gst_structure_get_value (structure, "codec_data");
691   if (value)
692     codec_buf = gst_value_get_buffer (value);
693
694   /* find type */
695   if (!strcmp (mimetype, "video/x-raw-yuv")) {
696     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_UNCOMPRESSED);
697     gst_structure_get_fourcc (structure, "format", &videocontext->fourcc);
698
699     return TRUE;
700   } else if (!strcmp (mimetype, "image/jpeg")) {
701     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_MJPEG);
702
703     return TRUE;
704   } else if (!strcmp (mimetype, "video/x-xvid") /* MS/VfW compatibility cases */
705       ||!strcmp (mimetype, "video/x-huffyuv")
706       || !strcmp (mimetype, "video/x-divx")
707       || !strcmp (mimetype, "video/x-dv")
708       || !strcmp (mimetype, "video/x-h263")
709       || !strcmp (mimetype, "video/x-msmpeg")) {
710     BITMAPINFOHEADER *bih;
711     gint size = sizeof (BITMAPINFOHEADER);
712     guint32 fourcc = 0;
713
714     if (!strcmp (mimetype, "video/x-xvid"))
715       fourcc = GST_MAKE_FOURCC ('X', 'V', 'I', 'D');
716     else if (!strcmp (mimetype, "video/x-huffyuv"))
717       fourcc = GST_MAKE_FOURCC ('H', 'F', 'Y', 'U');
718     else if (!strcmp (mimetype, "video/x-dv"))
719       fourcc = GST_MAKE_FOURCC ('D', 'V', 'S', 'D');
720     else if (!strcmp (mimetype, "video/x-h263"))
721       fourcc = GST_MAKE_FOURCC ('H', '2', '6', '3');
722     else if (!strcmp (mimetype, "video/x-divx")) {
723       gint divxversion;
724
725       gst_structure_get_int (structure, "divxversion", &divxversion);
726       switch (divxversion) {
727         case 3:
728           fourcc = GST_MAKE_FOURCC ('D', 'I', 'V', '3');
729           break;
730         case 4:
731           fourcc = GST_MAKE_FOURCC ('D', 'I', 'V', 'X');
732           break;
733         case 5:
734           fourcc = GST_MAKE_FOURCC ('D', 'X', '5', '0');
735           break;
736       }
737     } else if (!strcmp (mimetype, "video/x-msmpeg")) {
738       gint msmpegversion;
739
740       gst_structure_get_int (structure, "msmpegversion", &msmpegversion);
741       switch (msmpegversion) {
742         case 41:
743           fourcc = GST_MAKE_FOURCC ('M', 'P', 'G', '4');
744           break;
745         case 42:
746           fourcc = GST_MAKE_FOURCC ('M', 'P', '4', '2');
747           break;
748         case 43:
749           goto msmpeg43;
750           break;
751       }
752     }
753
754     if (!fourcc)
755       return FALSE;
756
757     bih = g_new0 (BITMAPINFOHEADER, 1);
758     GST_WRITE_UINT32_LE (&bih->bi_size, size);
759     GST_WRITE_UINT32_LE (&bih->bi_width, videocontext->pixel_width);
760     GST_WRITE_UINT32_LE (&bih->bi_height, videocontext->pixel_height);
761     GST_WRITE_UINT32_LE (&bih->bi_compression, fourcc);
762     GST_WRITE_UINT16_LE (&bih->bi_planes, (guint16) 1);
763     GST_WRITE_UINT16_LE (&bih->bi_bit_count, (guint16) 24);
764     GST_WRITE_UINT32_LE (&bih->bi_size_image, videocontext->pixel_width *
765         videocontext->pixel_height * 3);
766
767     /* process codec private/initialization data, if any */
768     if (codec_buf) {
769       size += GST_BUFFER_SIZE (codec_buf);
770       bih = g_realloc (bih, size);
771       GST_WRITE_UINT32_LE (&bih->bi_size, size);
772       memcpy ((guint8 *) bih + sizeof (BITMAPINFOHEADER),
773           GST_BUFFER_DATA (codec_buf), GST_BUFFER_SIZE (codec_buf));
774     }
775
776     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC);
777     context->codec_priv = (gpointer) bih;
778     context->codec_priv_size = size;
779
780     return TRUE;
781   } else if (!strcmp (mimetype, "video/x-h264")) {
782     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_AVC);
783
784     if (context->codec_priv != NULL) {
785       g_free (context->codec_priv);
786       context->codec_priv = NULL;
787       context->codec_priv_size = 0;
788     }
789
790     /* Create avcC header */
791     if (codec_buf != NULL) {
792       context->codec_priv_size = GST_BUFFER_SIZE (codec_buf);
793       context->codec_priv = g_malloc0 (context->codec_priv_size);
794       memcpy (context->codec_priv, GST_BUFFER_DATA (codec_buf),
795           context->codec_priv_size);
796     }
797
798     return TRUE;
799   } else if (!strcmp (mimetype, "video/x-theora")) {
800     const GValue *streamheader;
801
802     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_THEORA);
803
804     if (context->codec_priv != NULL) {
805       g_free (context->codec_priv);
806       context->codec_priv = NULL;
807       context->codec_priv_size = 0;
808     }
809
810     streamheader = gst_structure_get_value (structure, "streamheader");
811     if (!theora_streamheader_to_codecdata (streamheader, context)) {
812       GST_ELEMENT_ERROR (mux, STREAM, MUX, (NULL),
813           ("theora stream headers missing or malformed"));
814       return FALSE;
815     }
816     return TRUE;
817   } else if (!strcmp (mimetype, "video/x-dirac")) {
818     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_DIRAC);
819
820     return TRUE;
821   } else if (!strcmp (mimetype, "video/mpeg")) {
822     gint mpegversion;
823
824     gst_structure_get_int (structure, "mpegversion", &mpegversion);
825     switch (mpegversion) {
826       case 1:
827         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_MPEG1);
828         break;
829       case 2:
830         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_MPEG2);
831         break;
832       case 4:
833         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_ASP);
834         break;
835       default:
836         return FALSE;
837     }
838
839     /* global headers may be in codec data */
840     if (codec_buf != NULL) {
841       context->codec_priv_size = GST_BUFFER_SIZE (codec_buf);
842       context->codec_priv = g_malloc0 (context->codec_priv_size);
843       memcpy (context->codec_priv, GST_BUFFER_DATA (codec_buf),
844           context->codec_priv_size);
845     }
846
847     return TRUE;
848   } else if (!strcmp (mimetype, "video/x-msmpeg")) {
849   msmpeg43:
850     /* can only make it here if preceding case verified it was version 3 */
851     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_MSMPEG4V3);
852
853     return TRUE;
854   } else if (!strcmp (mimetype, "video/x-pn-realvideo")) {
855     gint rmversion;
856     const GValue *mdpr_data;
857
858     gst_structure_get_int (structure, "rmversion", &rmversion);
859     switch (rmversion) {
860       case 1:
861         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO1);
862         break;
863       case 2:
864         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO2);
865         break;
866       case 3:
867         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO3);
868         break;
869       case 4:
870         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO4);
871         break;
872       default:
873         return FALSE;
874     }
875
876     mdpr_data = gst_structure_get_value (structure, "mdpr_data");
877     if (mdpr_data != NULL) {
878       guint8 *priv_data = NULL;
879       guint priv_data_size = 0;
880
881       GstBuffer *codec_data_buf = g_value_peek_pointer (mdpr_data);
882
883       priv_data_size = GST_BUFFER_SIZE (codec_data_buf);
884       priv_data = g_malloc0 (priv_data_size);
885
886       memcpy (priv_data, GST_BUFFER_DATA (codec_data_buf), priv_data_size);
887
888       context->codec_priv = priv_data;
889       context->codec_priv_size = priv_data_size;
890     }
891
892     return TRUE;
893   }
894
895   return FALSE;
896 }
897
898 static gboolean
899 xiph3_streamheader_to_codecdata (const GValue * streamheader,
900     GstMatroskaTrackContext * context, GstBuffer ** p_buf0)
901 {
902   GstBuffer *buf[3];
903   GArray *bufarr;
904   guint8 *priv_data;
905   guint i, offset, priv_data_size;
906
907   if (streamheader == NULL)
908     goto no_stream_headers;
909
910   if (G_VALUE_TYPE (streamheader) != GST_TYPE_ARRAY)
911     goto wrong_type;
912
913   bufarr = g_value_peek_pointer (streamheader);
914   if (bufarr->len != 3)
915     goto wrong_count;
916
917   context->xiph_headers_to_skip = bufarr->len;
918
919   for (i = 0; i < 3; i++) {
920     GValue *bufval = &g_array_index (bufarr, GValue, i);
921
922     if (G_VALUE_TYPE (bufval) != GST_TYPE_BUFFER)
923       goto wrong_content_type;
924
925     buf[i] = g_value_peek_pointer (bufval);
926   }
927
928   priv_data_size = 1;
929   priv_data_size += GST_BUFFER_SIZE (buf[0]) / 0xff + 1;
930   priv_data_size += GST_BUFFER_SIZE (buf[1]) / 0xff + 1;
931
932   for (i = 0; i < 3; ++i) {
933     priv_data_size += GST_BUFFER_SIZE (buf[i]);
934   }
935
936   priv_data = g_malloc0 (priv_data_size);
937
938   priv_data[0] = 2;
939   offset = 1;
940
941   for (i = 0; i < GST_BUFFER_SIZE (buf[0]) / 0xff; ++i) {
942     priv_data[offset++] = 0xff;
943   }
944   priv_data[offset++] = GST_BUFFER_SIZE (buf[0]) % 0xff;
945
946   for (i = 0; i < GST_BUFFER_SIZE (buf[1]) / 0xff; ++i) {
947     priv_data[offset++] = 0xff;
948   }
949   priv_data[offset++] = GST_BUFFER_SIZE (buf[1]) % 0xff;
950
951   for (i = 0; i < 3; ++i) {
952     memcpy (priv_data + offset, GST_BUFFER_DATA (buf[i]),
953         GST_BUFFER_SIZE (buf[i]));
954     offset += GST_BUFFER_SIZE (buf[i]);
955   }
956
957   context->codec_priv = priv_data;
958   context->codec_priv_size = priv_data_size;
959
960   if (p_buf0)
961     *p_buf0 = gst_buffer_ref (buf[0]);
962
963   return TRUE;
964
965 /* ERRORS */
966 no_stream_headers:
967   {
968     GST_WARNING ("required streamheaders missing in sink caps!");
969     return FALSE;
970   }
971 wrong_type:
972   {
973     GST_WARNING ("streamheaders are not a GST_TYPE_ARRAY, but a %s",
974         G_VALUE_TYPE_NAME (streamheader));
975     return FALSE;
976   }
977 wrong_count:
978   {
979     GST_WARNING ("got %u streamheaders, not 3 as expected", bufarr->len);
980     return FALSE;
981   }
982 wrong_content_type:
983   {
984     GST_WARNING ("streamheaders array does not contain GstBuffers");
985     return FALSE;
986   }
987 }
988
989 static gboolean
990 vorbis_streamheader_to_codecdata (const GValue * streamheader,
991     GstMatroskaTrackContext * context)
992 {
993   GstBuffer *buf0 = NULL;
994
995   if (!xiph3_streamheader_to_codecdata (streamheader, context, &buf0))
996     return FALSE;
997
998   if (buf0 == NULL || GST_BUFFER_SIZE (buf0) < 1 + 6 + 4) {
999     GST_WARNING ("First vorbis header too small, ignoring");
1000   } else {
1001     if (memcmp (GST_BUFFER_DATA (buf0) + 1, "vorbis", 6) == 0) {
1002       GstMatroskaTrackAudioContext *audiocontext;
1003       guint8 *hdr;
1004
1005       hdr = GST_BUFFER_DATA (buf0) + 1 + 6 + 4;
1006       audiocontext = (GstMatroskaTrackAudioContext *) context;
1007       audiocontext->channels = GST_READ_UINT8 (hdr);
1008       audiocontext->samplerate = GST_READ_UINT32_LE (hdr + 1);
1009     }
1010   }
1011
1012   if (buf0)
1013     gst_buffer_unref (buf0);
1014
1015   return TRUE;
1016 }
1017
1018 static gboolean
1019 theora_streamheader_to_codecdata (const GValue * streamheader,
1020     GstMatroskaTrackContext * context)
1021 {
1022   GstBuffer *buf0 = NULL;
1023
1024   if (!xiph3_streamheader_to_codecdata (streamheader, context, &buf0))
1025     return FALSE;
1026
1027   if (buf0 == NULL || GST_BUFFER_SIZE (buf0) < 1 + 6 + 26) {
1028     GST_WARNING ("First theora header too small, ignoring");
1029   } else if (memcmp (GST_BUFFER_DATA (buf0), "\200theora\003\002", 9) != 0) {
1030     GST_WARNING ("First header not a theora identification header, ignoring");
1031   } else {
1032     GstMatroskaTrackVideoContext *videocontext;
1033     guint fps_num, fps_denom, par_num, par_denom;
1034     guint8 *hdr;
1035
1036     hdr = GST_BUFFER_DATA (buf0) + 1 + 6 + 3 + 2 + 2;
1037
1038     videocontext = (GstMatroskaTrackVideoContext *) context;
1039     videocontext->pixel_width = GST_READ_UINT32_BE (hdr) >> 8;
1040     videocontext->pixel_height = GST_READ_UINT32_BE (hdr + 3) >> 8;
1041     hdr += 3 + 3 + 1 + 1;
1042     fps_num = GST_READ_UINT32_BE (hdr);
1043     fps_denom = GST_READ_UINT32_BE (hdr + 4);
1044     context->default_duration = gst_util_uint64_scale_int (GST_SECOND,
1045         fps_denom, fps_num);
1046     hdr += 4 + 4;
1047     par_num = GST_READ_UINT32_BE (hdr) >> 8;
1048     par_denom = GST_READ_UINT32_BE (hdr + 3) >> 8;
1049     if (par_num > 0 && par_num > 0) {
1050       if (par_num > par_denom) {
1051         videocontext->display_width =
1052             videocontext->pixel_width * par_num / par_denom;
1053         videocontext->display_height = videocontext->pixel_height;
1054       } else if (par_num < par_denom) {
1055         videocontext->display_width = videocontext->pixel_width;
1056         videocontext->display_height =
1057             videocontext->pixel_height * par_denom / par_num;
1058       } else {
1059         videocontext->display_width = 0;
1060         videocontext->display_height = 0;
1061       }
1062     } else {
1063       videocontext->display_width = 0;
1064       videocontext->display_height = 0;
1065     }
1066     hdr += 3 + 3;
1067   }
1068
1069   if (buf0)
1070     gst_buffer_unref (buf0);
1071
1072   return TRUE;
1073 }
1074
1075 static gboolean
1076 flac_streamheader_to_codecdata (const GValue * streamheader,
1077     GstMatroskaTrackContext * context)
1078 {
1079   GArray *bufarr;
1080   gint i;
1081   GValue *bufval;
1082   GstBuffer *buffer;
1083
1084   if (streamheader == NULL || G_VALUE_TYPE (streamheader) != GST_TYPE_ARRAY) {
1085     GST_WARNING ("No or invalid streamheader field in the caps");
1086     return FALSE;
1087   }
1088
1089   bufarr = g_value_peek_pointer (streamheader);
1090   if (bufarr->len < 2) {
1091     GST_WARNING ("Too few headers in streamheader field");
1092     return FALSE;
1093   }
1094
1095   context->xiph_headers_to_skip = bufarr->len + 1;
1096
1097   bufval = &g_array_index (bufarr, GValue, 0);
1098   if (G_VALUE_TYPE (bufval) != GST_TYPE_BUFFER) {
1099     GST_WARNING ("streamheaders array does not contain GstBuffers");
1100     return FALSE;
1101   }
1102
1103   buffer = g_value_peek_pointer (bufval);
1104
1105   /* Need at least OggFLAC mapping header, fLaC marker and STREAMINFO block */
1106   if (GST_BUFFER_SIZE (buffer) < 9 + 4 + 4 + 34
1107       || memcmp (GST_BUFFER_DATA (buffer) + 1, "FLAC", 4) != 0
1108       || memcmp (GST_BUFFER_DATA (buffer) + 9, "fLaC", 4) != 0) {
1109     GST_WARNING ("Invalid streamheader for FLAC");
1110     return FALSE;
1111   }
1112
1113   context->codec_priv = g_malloc (GST_BUFFER_SIZE (buffer) - 9);
1114   context->codec_priv_size = GST_BUFFER_SIZE (buffer) - 9;
1115   memcpy (context->codec_priv, GST_BUFFER_DATA (buffer) + 9,
1116       GST_BUFFER_SIZE (buffer) - 9);
1117
1118   for (i = 1; i < bufarr->len; i++) {
1119     bufval = &g_array_index (bufarr, GValue, i);
1120
1121     if (G_VALUE_TYPE (bufval) != GST_TYPE_BUFFER) {
1122       g_free (context->codec_priv);
1123       context->codec_priv = NULL;
1124       context->codec_priv_size = 0;
1125       GST_WARNING ("streamheaders array does not contain GstBuffers");
1126       return FALSE;
1127     }
1128
1129     buffer = g_value_peek_pointer (bufval);
1130
1131     context->codec_priv =
1132         g_realloc (context->codec_priv,
1133         context->codec_priv_size + GST_BUFFER_SIZE (buffer));
1134     memcpy ((guint8 *) context->codec_priv + context->codec_priv_size,
1135         GST_BUFFER_DATA (buffer), GST_BUFFER_SIZE (buffer));
1136     context->codec_priv_size =
1137         context->codec_priv_size + GST_BUFFER_SIZE (buffer);
1138   }
1139
1140   return TRUE;
1141 }
1142
1143 static gchar *
1144 aac_codec_data_to_codec_id (const GstBuffer * buf)
1145 {
1146   gchar *result;
1147   gint profile;
1148
1149   /* default to MAIN */
1150   profile = 1;
1151
1152   if (GST_BUFFER_SIZE (buf) >= 2) {
1153     profile = GST_READ_UINT8 (GST_BUFFER_DATA (buf));
1154     profile >>= 3;
1155   }
1156
1157   switch (profile) {
1158     case 1:
1159       result = "MAIN";
1160       break;
1161     case 2:
1162       result = "LC";
1163       break;
1164     case 3:
1165       result = "SSR";
1166       break;
1167     case 4:
1168       result = "LTP";
1169       break;
1170     default:
1171       GST_WARNING ("unknown AAC profile, defaulting to MAIN");
1172       result = "MAIN";
1173       break;
1174   }
1175
1176   return result;
1177 }
1178
1179 /**
1180  * gst_matroska_mux_audio_pad_setcaps:
1181  * @pad: Pad which got the caps.
1182  * @caps: New caps.
1183  *
1184  * Setcaps function for audio sink pad.
1185  *
1186  * Returns: #TRUE on success.
1187  */
1188 static gboolean
1189 gst_matroska_mux_audio_pad_setcaps (GstPad * pad, GstCaps * caps)
1190 {
1191   GstMatroskaTrackContext *context = NULL;
1192   GstMatroskaTrackAudioContext *audiocontext;
1193   GstMatroskaMux *mux;
1194   GstMatroskaPad *collect_pad;
1195   const gchar *mimetype;
1196   gint samplerate = 0, channels = 0;
1197   GstStructure *structure;
1198
1199   mux = GST_MATROSKA_MUX (GST_PAD_PARENT (pad));
1200
1201   /* find context */
1202   collect_pad = (GstMatroskaPad *) gst_pad_get_element_private (pad);
1203   g_assert (collect_pad);
1204   context = collect_pad->track;
1205   g_assert (context);
1206   g_assert (context->type == GST_MATROSKA_TRACK_TYPE_AUDIO);
1207   audiocontext = (GstMatroskaTrackAudioContext *) context;
1208
1209   structure = gst_caps_get_structure (caps, 0);
1210   mimetype = gst_structure_get_name (structure);
1211
1212   /* general setup */
1213   gst_structure_get_int (structure, "rate", &samplerate);
1214   gst_structure_get_int (structure, "channels", &channels);
1215
1216   audiocontext->samplerate = samplerate;
1217   audiocontext->channels = channels;
1218   audiocontext->bitdepth = 0;
1219   context->default_duration = 0;
1220
1221   /* TODO: - check if we handle all codecs by the spec, i.e. codec private
1222    *         data and other settings
1223    *       - add new formats
1224    */
1225
1226   if (!strcmp (mimetype, "audio/mpeg")) {
1227     gint mpegversion = 0;
1228     const GValue *codec_data;
1229     const GstBuffer *buf = NULL;
1230
1231     codec_data = gst_structure_get_value (structure, "codec_data");
1232     if (codec_data)
1233       buf = gst_value_get_buffer (codec_data);
1234
1235     gst_structure_get_int (structure, "mpegversion", &mpegversion);
1236     switch (mpegversion) {
1237       case 1:{
1238         gint layer;
1239         gint version = 1;
1240         gint spf;
1241
1242         gst_structure_get_int (structure, "layer", &layer);
1243
1244         if (!gst_structure_get_int (structure, "mpegaudioversion", &version)) {
1245           GST_WARNING_OBJECT (mux,
1246               "Unable to determine MPEG audio version, assuming 1");
1247           version = 1;
1248         }
1249
1250         if (layer == 1)
1251           spf = 384;
1252         else if (layer == 2)
1253           spf = 1152;
1254         else if (version == 2)
1255           spf = 576;
1256         else
1257           spf = 1152;
1258
1259         context->default_duration =
1260             gst_util_uint64_scale (GST_SECOND, spf, audiocontext->samplerate);
1261
1262         switch (layer) {
1263           case 1:
1264             context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L1);
1265             break;
1266           case 2:
1267             context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L2);
1268             break;
1269           case 3:
1270             context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L3);
1271             break;
1272           default:
1273             return FALSE;
1274         }
1275         break;
1276       }
1277       case 2:
1278         if (buf) {
1279           context->codec_id =
1280               g_strdup_printf (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2 "%s",
1281               aac_codec_data_to_codec_id (buf));
1282         } else {
1283           GST_DEBUG_OBJECT (mux, "no AAC codec_data; not packetized");
1284           return FALSE;
1285         }
1286         break;
1287       case 4:
1288         if (buf) {
1289           context->codec_id =
1290               g_strdup_printf (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4 "%s",
1291               aac_codec_data_to_codec_id (buf));
1292         } else {
1293           GST_DEBUG_OBJECT (mux, "no AAC codec_data; not packetized");
1294           return FALSE;
1295         }
1296         break;
1297       default:
1298         return FALSE;
1299     }
1300
1301     return TRUE;
1302   } else if (!strcmp (mimetype, "audio/x-raw-int")) {
1303     gint endianness, width, depth;
1304     gboolean signedness = G_LITTLE_ENDIAN;
1305
1306     if (!gst_structure_get_int (structure, "width", &width) ||
1307         !gst_structure_get_int (structure, "depth", &depth) ||
1308         !gst_structure_get_boolean (structure, "signed", &signedness)) {
1309       GST_DEBUG_OBJECT (mux, "broken caps, width/depth/signed field missing");
1310       return FALSE;
1311     }
1312
1313     if (depth > 8 &&
1314         !gst_structure_get_int (structure, "endianness", &endianness)) {
1315       GST_DEBUG_OBJECT (mux, "broken caps, no endianness specified");
1316       return FALSE;
1317     }
1318
1319     if (width != depth) {
1320       GST_DEBUG_OBJECT (mux, "width must be same as depth!");
1321       return FALSE;
1322     }
1323
1324     /* FIXME: where is this spec'ed out? (tpm) */
1325     if ((width == 8 && signedness) || (width >= 16 && !signedness)) {
1326       GST_DEBUG_OBJECT (mux, "8-bit PCM must be unsigned, 16-bit PCM signed");
1327       return FALSE;
1328     }
1329
1330     audiocontext->bitdepth = depth;
1331     if (endianness == G_BIG_ENDIAN)
1332       context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE);
1333     else
1334       context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_LE);
1335
1336     return TRUE;
1337   } else if (!strcmp (mimetype, "audio/x-raw-float")) {
1338     gint width;
1339
1340     if (!gst_structure_get_int (structure, "width", &width)) {
1341       GST_DEBUG_OBJECT (mux, "broken caps, width field missing");
1342       return FALSE;
1343     }
1344
1345     audiocontext->bitdepth = width;
1346     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_PCM_FLOAT);
1347
1348     return TRUE;
1349   } else if (!strcmp (mimetype, "audio/x-vorbis")) {
1350     const GValue *streamheader;
1351
1352     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_VORBIS);
1353
1354     if (context->codec_priv != NULL) {
1355       g_free (context->codec_priv);
1356       context->codec_priv = NULL;
1357       context->codec_priv_size = 0;
1358     }
1359
1360     streamheader = gst_structure_get_value (structure, "streamheader");
1361     if (!vorbis_streamheader_to_codecdata (streamheader, context)) {
1362       GST_ELEMENT_ERROR (mux, STREAM, MUX, (NULL),
1363           ("vorbis stream headers missing or malformed"));
1364       return FALSE;
1365     }
1366     return TRUE;
1367   } else if (!strcmp (mimetype, "audio/x-flac")) {
1368     const GValue *streamheader;
1369
1370     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_FLAC);
1371     if (context->codec_priv != NULL) {
1372       g_free (context->codec_priv);
1373       context->codec_priv = NULL;
1374       context->codec_priv_size = 0;
1375     }
1376
1377     streamheader = gst_structure_get_value (structure, "streamheader");
1378     if (!flac_streamheader_to_codecdata (streamheader, context)) {
1379       GST_ELEMENT_ERROR (mux, STREAM, MUX, (NULL),
1380           ("flac stream headers missing or malformed"));
1381       return FALSE;
1382     }
1383     return TRUE;
1384   } else if (!strcmp (mimetype, "audio/x-ac3")) {
1385     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_AC3);
1386
1387     return TRUE;
1388   } else if (!strcmp (mimetype, "audio/x-tta")) {
1389     gint width;
1390
1391     /* TTA frame duration */
1392     context->default_duration = 1.04489795918367346939 * GST_SECOND;
1393
1394     gst_structure_get_int (structure, "width", &width);
1395     audiocontext->bitdepth = width;
1396     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_TTA);
1397
1398     return TRUE;
1399   } else if (!strcmp (mimetype, "audio/x-pn-realaudio")) {
1400     gint raversion;
1401     const GValue *mdpr_data;
1402
1403     gst_structure_get_int (structure, "raversion", &raversion);
1404     switch (raversion) {
1405       case 1:
1406         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4);
1407         break;
1408       case 2:
1409         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_REAL_28_8);
1410         break;
1411       case 8:
1412         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK);
1413         break;
1414       default:
1415         return FALSE;
1416     }
1417
1418     mdpr_data = gst_structure_get_value (structure, "mdpr_data");
1419     if (mdpr_data != NULL) {
1420       guint8 *priv_data = NULL;
1421       guint priv_data_size = 0;
1422
1423       GstBuffer *codec_data_buf = g_value_peek_pointer (mdpr_data);
1424
1425       priv_data_size = GST_BUFFER_SIZE (codec_data_buf);
1426       priv_data = g_malloc0 (priv_data_size);
1427
1428       memcpy (priv_data, GST_BUFFER_DATA (codec_data_buf), priv_data_size);
1429
1430       context->codec_priv = priv_data;
1431       context->codec_priv_size = priv_data_size;
1432     }
1433
1434     return TRUE;
1435   }
1436
1437   return FALSE;
1438 }
1439
1440
1441 /**
1442  * gst_matroska_mux_subtitle_pad_setcaps:
1443  * @pad: Pad which got the caps.
1444  * @caps: New caps.
1445  *
1446  * Setcaps function for subtitle sink pad.
1447  *
1448  * Returns: #TRUE on success.
1449  */
1450 static gboolean
1451 gst_matroska_mux_subtitle_pad_setcaps (GstPad * pad, GstCaps * caps)
1452 {
1453   /* FIXME:
1454    * Consider this as boilerplate code for now. There is
1455    * no single subtitle creation element in GStreamer,
1456    * neither do I know how subtitling works at all. */
1457
1458   return FALSE;
1459 }
1460
1461
1462 /**
1463  * gst_matroska_mux_request_new_pad:
1464  * @element: #GstMatroskaMux.
1465  * @templ: #GstPadTemplate.
1466  * @pad_name: New pad name.
1467  *
1468  * Request pad function for sink templates.
1469  *
1470  * Returns: New #GstPad.
1471  */
1472 static GstPad *
1473 gst_matroska_mux_request_new_pad (GstElement * element,
1474     GstPadTemplate * templ, const gchar * pad_name)
1475 {
1476   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
1477   GstMatroskaMux *mux = GST_MATROSKA_MUX (element);
1478   GstMatroskaPad *collect_pad;
1479   GstPad *newpad = NULL;
1480   gchar *name = NULL;
1481   GstPadSetCapsFunction setcapsfunc = NULL;
1482   GstMatroskaTrackContext *context = NULL;
1483
1484   if (templ == gst_element_class_get_pad_template (klass, "audio_%d")) {
1485     name = g_strdup_printf ("audio_%d", mux->num_a_streams++);
1486     setcapsfunc = GST_DEBUG_FUNCPTR (gst_matroska_mux_audio_pad_setcaps);
1487     context = (GstMatroskaTrackContext *)
1488         g_new0 (GstMatroskaTrackAudioContext, 1);
1489     context->type = GST_MATROSKA_TRACK_TYPE_AUDIO;
1490     context->name = g_strdup ("Audio");
1491   } else if (templ == gst_element_class_get_pad_template (klass, "video_%d")) {
1492     name = g_strdup_printf ("video_%d", mux->num_v_streams++);
1493     setcapsfunc = GST_DEBUG_FUNCPTR (gst_matroska_mux_video_pad_setcaps);
1494     context = (GstMatroskaTrackContext *)
1495         g_new0 (GstMatroskaTrackVideoContext, 1);
1496     context->type = GST_MATROSKA_TRACK_TYPE_VIDEO;
1497     context->name = g_strdup ("Video");
1498   } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%d")) {
1499     name = g_strdup_printf ("subtitle_%d", mux->num_t_streams++);
1500     setcapsfunc = GST_DEBUG_FUNCPTR (gst_matroska_mux_subtitle_pad_setcaps);
1501     context = (GstMatroskaTrackContext *)
1502         g_new0 (GstMatroskaTrackSubtitleContext, 1);
1503     context->type = GST_MATROSKA_TRACK_TYPE_SUBTITLE;
1504     context->name = g_strdup ("Subtitle");
1505   } else {
1506     GST_WARNING_OBJECT (mux, "This is not our template!");
1507     return NULL;
1508   }
1509
1510   newpad = gst_pad_new_from_template (templ, name);
1511   g_free (name);
1512   collect_pad = (GstMatroskaPad *)
1513       gst_collect_pads_add_pad_full (mux->collect, newpad,
1514       sizeof (GstMatroskaPad),
1515       (GstCollectDataDestroyNotify) gst_matroska_pad_free);
1516
1517   collect_pad->track = context;
1518   gst_matroska_pad_reset (collect_pad, FALSE);
1519
1520   /* FIXME: hacked way to override/extend the event function of
1521    * GstCollectPads; because it sets its own event function giving the
1522    * element no access to events.
1523    * TODO GstCollectPads should really give its 'users' a clean chance to
1524    * properly handle events that are not meant for collectpads itself.
1525    * Perhaps a callback or so, though rejected (?) in #340060.
1526    * This would allow (clean) transcoding of info from demuxer/streams
1527    * to another muxer */
1528   mux->collect_event = (GstPadEventFunction) GST_PAD_EVENTFUNC (newpad);
1529   gst_pad_set_event_function (newpad,
1530       GST_DEBUG_FUNCPTR (gst_matroska_mux_handle_sink_event));
1531
1532   gst_pad_set_setcaps_function (newpad, setcapsfunc);
1533   gst_pad_set_active (newpad, TRUE);
1534   gst_element_add_pad (element, newpad);
1535   mux->num_streams++;
1536
1537   return newpad;
1538 }
1539
1540 /**
1541  * gst_matroska_mux_release_pad:
1542  * @element: #GstMatroskaMux.
1543  * @pad: Pad to release.
1544  *
1545  * Release a previously requested pad.
1546 */
1547 static void
1548 gst_matroska_mux_release_pad (GstElement * element, GstPad * pad)
1549 {
1550   GstMatroskaMux *mux;
1551   GSList *walk;
1552
1553   mux = GST_MATROSKA_MUX (GST_PAD_PARENT (pad));
1554
1555   for (walk = mux->collect->data; walk; walk = g_slist_next (walk)) {
1556     GstCollectData *cdata = (GstCollectData *) walk->data;
1557     GstMatroskaPad *collect_pad = (GstMatroskaPad *) cdata;
1558
1559     if (cdata->pad == pad) {
1560       GstClockTime min_dur;     /* observed minimum duration */
1561
1562       if (GST_CLOCK_TIME_IS_VALID (collect_pad->start_ts) &&
1563           GST_CLOCK_TIME_IS_VALID (collect_pad->end_ts)) {
1564         min_dur = GST_CLOCK_DIFF (collect_pad->start_ts, collect_pad->end_ts);
1565         if (collect_pad->duration < min_dur)
1566           collect_pad->duration = min_dur;
1567       }
1568
1569       if (GST_CLOCK_TIME_IS_VALID (collect_pad->duration) &&
1570           mux->duration < collect_pad->duration)
1571         mux->duration = collect_pad->duration;
1572
1573       break;
1574     }
1575   }
1576
1577   gst_collect_pads_remove_pad (mux->collect, pad);
1578   if (gst_element_remove_pad (element, pad))
1579     mux->num_streams--;
1580 }
1581
1582
1583 /**
1584  * gst_matroska_mux_track_header:
1585  * @mux: #GstMatroskaMux
1586  * @context: Tack context.
1587  *
1588  * Write a track header.
1589  */
1590 static void
1591 gst_matroska_mux_track_header (GstMatroskaMux * mux,
1592     GstMatroskaTrackContext * context)
1593 {
1594   GstEbmlWrite *ebml = mux->ebml_write;
1595   guint64 master;
1596
1597   /* TODO: check if everything necessary is written and check default values */
1598
1599   /* track type goes before the type-specific stuff */
1600   gst_ebml_write_uint (ebml, GST_MATROSKA_ID_TRACKNUMBER, context->num);
1601   gst_ebml_write_uint (ebml, GST_MATROSKA_ID_TRACKTYPE, context->type);
1602
1603   gst_ebml_write_uint (ebml, GST_MATROSKA_ID_TRACKUID,
1604       gst_matroska_mux_create_uid ());
1605   if (context->default_duration) {
1606     gst_ebml_write_uint (ebml, GST_MATROSKA_ID_TRACKDEFAULTDURATION,
1607         context->default_duration);
1608   }
1609   if (context->language) {
1610     gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_TRACKLANGUAGE,
1611         context->language);
1612   }
1613
1614   /* type-specific stuff */
1615   switch (context->type) {
1616     case GST_MATROSKA_TRACK_TYPE_VIDEO:{
1617       GstMatroskaTrackVideoContext *videocontext =
1618           (GstMatroskaTrackVideoContext *) context;
1619
1620       master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TRACKVIDEO);
1621       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_VIDEOPIXELWIDTH,
1622           videocontext->pixel_width);
1623       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_VIDEOPIXELHEIGHT,
1624           videocontext->pixel_height);
1625       if (videocontext->display_width && videocontext->display_height) {
1626         gst_ebml_write_uint (ebml, GST_MATROSKA_ID_VIDEODISPLAYWIDTH,
1627             videocontext->display_width);
1628         gst_ebml_write_uint (ebml, GST_MATROSKA_ID_VIDEODISPLAYHEIGHT,
1629             videocontext->display_height);
1630       }
1631       if (context->flags & GST_MATROSKA_VIDEOTRACK_INTERLACED)
1632         gst_ebml_write_uint (ebml, GST_MATROSKA_ID_VIDEOFLAGINTERLACED, 1);
1633       if (videocontext->fourcc) {
1634         guint32 fcc_le = GUINT32_TO_LE (videocontext->fourcc);
1635
1636         gst_ebml_write_binary (ebml, GST_MATROSKA_ID_VIDEOCOLOURSPACE,
1637             (gpointer) & fcc_le, 4);
1638       }
1639       gst_ebml_write_master_finish (ebml, master);
1640
1641       break;
1642     }
1643
1644     case GST_MATROSKA_TRACK_TYPE_AUDIO:{
1645       GstMatroskaTrackAudioContext *audiocontext =
1646           (GstMatroskaTrackAudioContext *) context;
1647
1648       master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TRACKAUDIO);
1649       if (audiocontext->samplerate != 8000)
1650         gst_ebml_write_float (ebml, GST_MATROSKA_ID_AUDIOSAMPLINGFREQ,
1651             audiocontext->samplerate);
1652       if (audiocontext->channels != 1)
1653         gst_ebml_write_uint (ebml, GST_MATROSKA_ID_AUDIOCHANNELS,
1654             audiocontext->channels);
1655       if (audiocontext->bitdepth) {
1656         gst_ebml_write_uint (ebml, GST_MATROSKA_ID_AUDIOBITDEPTH,
1657             audiocontext->bitdepth);
1658       }
1659       gst_ebml_write_master_finish (ebml, master);
1660
1661       break;
1662     }
1663
1664     default:
1665       /* doesn't need type-specific data */
1666       break;
1667   }
1668
1669   gst_ebml_write_ascii (ebml, GST_MATROSKA_ID_CODECID, context->codec_id);
1670   if (context->codec_priv)
1671     gst_ebml_write_binary (ebml, GST_MATROSKA_ID_CODECPRIVATE,
1672         context->codec_priv, context->codec_priv_size);
1673   /* FIXME: until we have a nice way of getting the codecname
1674    * out of the caps, I'm not going to enable this. Too much
1675    * (useless, double, boring) work... */
1676   /* TODO: Use value from tags if any */
1677   /*gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_CODECNAME,
1678      context->codec_name); */
1679   gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_TRACKNAME, context->name);
1680 }
1681
1682
1683 /**
1684  * gst_matroska_mux_start:
1685  * @mux: #GstMatroskaMux
1686  *
1687  * Start a new matroska file (write headers etc...)
1688  */
1689 static void
1690 gst_matroska_mux_start (GstMatroskaMux * mux)
1691 {
1692   GstEbmlWrite *ebml = mux->ebml_write;
1693   guint32 seekhead_id[] = { GST_MATROSKA_ID_SEGMENTINFO,
1694     GST_MATROSKA_ID_TRACKS,
1695     GST_MATROSKA_ID_CUES,
1696     GST_MATROSKA_ID_TAGS,
1697     0
1698   };
1699   guint64 master, child;
1700   GSList *collected;
1701   int i;
1702   guint tracknum = 1;
1703   GstClockTime duration = 0;
1704   guint32 segment_uid[4];
1705   GTimeVal time = { 0, 0 };
1706
1707   /* we start with a EBML header */
1708   gst_ebml_write_header (ebml, "matroska", mux->matroska_version);
1709
1710   /* start a segment */
1711   mux->segment_pos =
1712       gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_SEGMENT);
1713   mux->segment_master = ebml->pos;
1714
1715   /* the rest of the header is cached */
1716   gst_ebml_write_set_cache (ebml, 0x1000);
1717
1718   /* seekhead (table of contents) - we set the positions later */
1719   mux->seekhead_pos = ebml->pos;
1720   master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_SEEKHEAD);
1721   for (i = 0; seekhead_id[i] != 0; i++) {
1722     child = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_SEEKENTRY);
1723     gst_ebml_write_uint (ebml, GST_MATROSKA_ID_SEEKID, seekhead_id[i]);
1724     gst_ebml_write_uint (ebml, GST_MATROSKA_ID_SEEKPOSITION, -1);
1725     gst_ebml_write_master_finish (ebml, child);
1726   }
1727   gst_ebml_write_master_finish (ebml, master);
1728
1729   /* segment info */
1730   mux->info_pos = ebml->pos;
1731   master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_SEGMENTINFO);
1732   for (i = 0; i < 4; i++) {
1733     segment_uid[i] = g_random_int ();
1734   }
1735   gst_ebml_write_binary (ebml, GST_MATROSKA_ID_SEGMENTUID,
1736       (guint8 *) segment_uid, 16);
1737   gst_ebml_write_uint (ebml, GST_MATROSKA_ID_TIMECODESCALE, mux->time_scale);
1738   mux->duration_pos = ebml->pos;
1739   /* get duration */
1740   for (collected = mux->collect->data; collected;
1741       collected = g_slist_next (collected)) {
1742     GstMatroskaPad *collect_pad;
1743     GstFormat format = GST_FORMAT_TIME;
1744     GstPad *thepad;
1745     gint64 trackduration;
1746
1747     collect_pad = (GstMatroskaPad *) collected->data;
1748     thepad = collect_pad->collect.pad;
1749
1750     /* Query the total length of the track. */
1751     GST_DEBUG_OBJECT (thepad, "querying peer duration");
1752     if (gst_pad_query_peer_duration (thepad, &format, &trackduration)) {
1753       GST_DEBUG_OBJECT (thepad, "duration: %" GST_TIME_FORMAT,
1754           GST_TIME_ARGS (trackduration));
1755       if (trackduration != GST_CLOCK_TIME_NONE && trackduration > duration) {
1756         duration = (GstClockTime) trackduration;
1757       }
1758     }
1759   }
1760   gst_ebml_write_float (ebml, GST_MATROSKA_ID_DURATION,
1761       gst_guint64_to_gdouble (duration) /
1762       gst_guint64_to_gdouble (mux->time_scale));
1763
1764   gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_MUXINGAPP,
1765       "GStreamer plugin version " PACKAGE_VERSION);
1766   if (mux->writing_app && mux->writing_app[0]) {
1767     gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_WRITINGAPP, mux->writing_app);
1768   }
1769   g_get_current_time (&time);
1770   gst_ebml_write_date (ebml, GST_MATROSKA_ID_DATEUTC, time.tv_sec);
1771   gst_ebml_write_master_finish (ebml, master);
1772
1773   /* tracks */
1774   mux->tracks_pos = ebml->pos;
1775   master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TRACKS);
1776
1777   for (collected = mux->collect->data; collected;
1778       collected = g_slist_next (collected)) {
1779     GstMatroskaPad *collect_pad;
1780     GstPad *thepad;
1781
1782     collect_pad = (GstMatroskaPad *) collected->data;
1783     thepad = collect_pad->collect.pad;
1784
1785     if (gst_pad_is_linked (thepad) && gst_pad_is_active (thepad) &&
1786         collect_pad->track->codec_id != 0) {
1787       collect_pad->track->num = tracknum++;
1788       child = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TRACKENTRY);
1789       gst_matroska_mux_track_header (mux, collect_pad->track);
1790       gst_ebml_write_master_finish (ebml, child);
1791     }
1792   }
1793   gst_ebml_write_master_finish (ebml, master);
1794
1795   /* lastly, flush the cache */
1796   gst_ebml_write_flush_cache (ebml);
1797 }
1798
1799 static void
1800 gst_matroska_mux_write_simple_tag (const GstTagList * list, const gchar * tag,
1801     gpointer data)
1802 {
1803   /* TODO: more sensible tag mappings */
1804   struct
1805   {
1806     gchar *matroska_tagname;
1807     gchar *gstreamer_tagname;
1808   }
1809   tag_conv[] = {
1810     {
1811     GST_MATROSKA_TAG_ID_TITLE, GST_TAG_TITLE}, {
1812     GST_MATROSKA_TAG_ID_AUTHOR, GST_TAG_ARTIST}, {
1813     GST_MATROSKA_TAG_ID_ALBUM, GST_TAG_ALBUM}, {
1814     GST_MATROSKA_TAG_ID_COMMENTS, GST_TAG_COMMENT}, {
1815     GST_MATROSKA_TAG_ID_BITSPS, GST_TAG_BITRATE}, {
1816     GST_MATROSKA_TAG_ID_BPS, GST_TAG_BITRATE}, {
1817     GST_MATROSKA_TAG_ID_ENCODER, GST_TAG_ENCODER}, {
1818     GST_MATROSKA_TAG_ID_DATE, GST_TAG_DATE}, {
1819     GST_MATROSKA_TAG_ID_ISRC, GST_TAG_ISRC}, {
1820     GST_MATROSKA_TAG_ID_COPYRIGHT, GST_TAG_COPYRIGHT}, {
1821     GST_MATROSKA_TAG_ID_BPM, GST_TAG_BEATS_PER_MINUTE}, {
1822     GST_MATROSKA_TAG_ID_TERMS_OF_USE, GST_TAG_LICENSE}, {
1823     GST_MATROSKA_TAG_ID_COMPOSER, GST_TAG_COMPOSER}, {
1824     GST_MATROSKA_TAG_ID_LEAD_PERFORMER, GST_TAG_PERFORMER}, {
1825     GST_MATROSKA_TAG_ID_GENRE, GST_TAG_GENRE}
1826   };
1827   GstEbmlWrite *ebml = (GstEbmlWrite *) data;
1828   guint i;
1829   guint64 simpletag_master;
1830
1831   for (i = 0; i < G_N_ELEMENTS (tag_conv); i++) {
1832     const gchar *tagname_gst = tag_conv[i].gstreamer_tagname;
1833     const gchar *tagname_mkv = tag_conv[i].matroska_tagname;
1834
1835     if (strcmp (tagname_gst, tag) == 0) {
1836       GValue src = { 0, };
1837       gchar *dest;
1838
1839       if (!gst_tag_list_copy_value (&src, list, tag))
1840         break;
1841       if ((dest = gst_value_serialize (&src))) {
1842
1843         simpletag_master = gst_ebml_write_master_start (ebml,
1844             GST_MATROSKA_ID_SIMPLETAG);
1845         gst_ebml_write_ascii (ebml, GST_MATROSKA_ID_TAGNAME, tagname_mkv);
1846         gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_TAGSTRING, dest);
1847         gst_ebml_write_master_finish (ebml, simpletag_master);
1848       } else {
1849         GST_WARNING ("Can't transform tag '%s' to string", tagname_mkv);
1850       }
1851       g_value_unset (&src);
1852       break;
1853     }
1854   }
1855 }
1856
1857
1858 /**
1859  * gst_matroska_mux_finish:
1860  * @mux: #GstMatroskaMux
1861  *
1862  * Finish a new matroska file (write index etc...)
1863  */
1864 static void
1865 gst_matroska_mux_finish (GstMatroskaMux * mux)
1866 {
1867   GstEbmlWrite *ebml = mux->ebml_write;
1868   guint64 pos;
1869   guint64 duration = 0;
1870   GSList *collected;
1871   const GstTagList *tags;
1872
1873   /* finish last cluster */
1874   if (mux->cluster) {
1875     gst_ebml_write_master_finish (ebml, mux->cluster);
1876   }
1877
1878   /* cues */
1879   if (mux->index != NULL) {
1880     guint n;
1881     guint64 master, pointentry_master, trackpos_master;
1882
1883     mux->cues_pos = ebml->pos;
1884     gst_ebml_write_set_cache (ebml, 12 + 41 * mux->num_indexes);
1885     master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_CUES);
1886
1887     for (n = 0; n < mux->num_indexes; n++) {
1888       GstMatroskaIndex *idx = &mux->index[n];
1889
1890       pointentry_master = gst_ebml_write_master_start (ebml,
1891           GST_MATROSKA_ID_POINTENTRY);
1892       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CUETIME,
1893           idx->time / mux->time_scale);
1894       trackpos_master = gst_ebml_write_master_start (ebml,
1895           GST_MATROSKA_ID_CUETRACKPOSITIONS);
1896       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CUETRACK, idx->track);
1897       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CUECLUSTERPOSITION,
1898           idx->pos - mux->segment_master);
1899       gst_ebml_write_master_finish (ebml, trackpos_master);
1900       gst_ebml_write_master_finish (ebml, pointentry_master);
1901     }
1902
1903     gst_ebml_write_master_finish (ebml, master);
1904     gst_ebml_write_flush_cache (ebml);
1905   }
1906
1907   /* tags */
1908   tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (mux));
1909
1910   if (tags != NULL && !gst_tag_list_is_empty (tags)) {
1911     guint64 master_tags, master_tag;
1912
1913     GST_DEBUG ("Writing tags");
1914
1915     /* TODO: maybe limit via the TARGETS id by looking at the source pad */
1916     mux->tags_pos = ebml->pos;
1917     master_tags = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TAGS);
1918     master_tag = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TAG);
1919     gst_tag_list_foreach (tags, gst_matroska_mux_write_simple_tag, ebml);
1920     gst_ebml_write_master_finish (ebml, master_tag);
1921     gst_ebml_write_master_finish (ebml, master_tags);
1922   }
1923
1924   /* update seekhead. We know that:
1925    * - a seekhead contains 4 entries.
1926    * - order of entries is as above.
1927    * - a seekhead has a 4-byte header + 8-byte length
1928    * - each entry is 2-byte master, 2-byte ID pointer,
1929    *     2-byte length pointer, all 8/1-byte length, 4-
1930    *     byte ID and 8-byte length pointer, where the
1931    *     length pointer starts at 20.
1932    * - all entries are local to the segment (so pos - segment_master).
1933    * - so each entry is at 12 + 20 + num * 28. */
1934   gst_ebml_replace_uint (ebml, mux->seekhead_pos + 32,
1935       mux->info_pos - mux->segment_master);
1936   gst_ebml_replace_uint (ebml, mux->seekhead_pos + 60,
1937       mux->tracks_pos - mux->segment_master);
1938   if (mux->index != NULL) {
1939     gst_ebml_replace_uint (ebml, mux->seekhead_pos + 88,
1940         mux->cues_pos - mux->segment_master);
1941   } else {
1942     /* void'ify */
1943     guint64 my_pos = ebml->pos;
1944
1945     gst_ebml_write_seek (ebml, mux->seekhead_pos + 68);
1946     gst_ebml_write_buffer_header (ebml, GST_EBML_ID_VOID, 26);
1947     gst_ebml_write_seek (ebml, my_pos);
1948   }
1949   if (tags != NULL) {
1950     gst_ebml_replace_uint (ebml, mux->seekhead_pos + 116,
1951         mux->tags_pos - mux->segment_master);
1952   } else {
1953     /* void'ify */
1954     guint64 my_pos = ebml->pos;
1955
1956     gst_ebml_write_seek (ebml, mux->seekhead_pos + 96);
1957     gst_ebml_write_buffer_header (ebml, GST_EBML_ID_VOID, 26);
1958     gst_ebml_write_seek (ebml, my_pos);
1959   }
1960
1961   /* update duration */
1962   /* first get the overall duration */
1963   /* a released track may have left a duration in here */
1964   duration = mux->duration;
1965   for (collected = mux->collect->data; collected;
1966       collected = g_slist_next (collected)) {
1967     GstMatroskaPad *collect_pad;
1968     GstClockTime min_duration;  /* observed minimum duration */
1969
1970     collect_pad = (GstMatroskaPad *) collected->data;
1971
1972     GST_DEBUG_OBJECT (mux, "Pad %" GST_PTR_FORMAT " start ts %" GST_TIME_FORMAT
1973         " end ts %" GST_TIME_FORMAT, collect_pad,
1974         GST_TIME_ARGS (collect_pad->start_ts),
1975         GST_TIME_ARGS (collect_pad->end_ts));
1976
1977     if (GST_CLOCK_TIME_IS_VALID (collect_pad->start_ts) &&
1978         GST_CLOCK_TIME_IS_VALID (collect_pad->end_ts)) {
1979       min_duration =
1980           GST_CLOCK_DIFF (collect_pad->start_ts, collect_pad->end_ts);
1981       if (collect_pad->duration < min_duration)
1982         collect_pad->duration = min_duration;
1983       GST_DEBUG_OBJECT (collect_pad, "final track duration: %" GST_TIME_FORMAT,
1984           GST_TIME_ARGS (collect_pad->duration));
1985     }
1986
1987     if (GST_CLOCK_TIME_IS_VALID (collect_pad->duration) &&
1988         duration < collect_pad->duration)
1989       duration = collect_pad->duration;
1990   }
1991   if (duration != 0) {
1992     GST_DEBUG_OBJECT (mux, "final total duration: %" GST_TIME_FORMAT,
1993         GST_TIME_ARGS (duration));
1994     pos = mux->ebml_write->pos;
1995     gst_ebml_write_seek (ebml, mux->duration_pos);
1996     gst_ebml_write_float (ebml, GST_MATROSKA_ID_DURATION,
1997         gst_guint64_to_gdouble (duration) /
1998         gst_guint64_to_gdouble (mux->time_scale));
1999     gst_ebml_write_seek (ebml, pos);
2000   } else {
2001     /* void'ify */
2002     guint64 my_pos = ebml->pos;
2003
2004     gst_ebml_write_seek (ebml, mux->duration_pos);
2005     gst_ebml_write_buffer_header (ebml, GST_EBML_ID_VOID, 8);
2006     gst_ebml_write_seek (ebml, my_pos);
2007   }
2008
2009   /* finish segment - this also writes element length */
2010   gst_ebml_write_master_finish (ebml, mux->segment_pos);
2011 }
2012
2013
2014 /**
2015  * gst_matroska_mux_best_pad:
2016  * @mux: #GstMatroskaMux
2017  * @popped: True if at least one buffer was popped from #GstCollectPads
2018  *
2019  * Find a pad with the oldest data 
2020  * (data from this pad should be written first).
2021  *
2022  * Returns: Selected pad.
2023  */
2024 static GstMatroskaPad *
2025 gst_matroska_mux_best_pad (GstMatroskaMux * mux, gboolean * popped)
2026 {
2027   GSList *collected;
2028   GstMatroskaPad *best = NULL;
2029
2030   *popped = FALSE;
2031   for (collected = mux->collect->data; collected;
2032       collected = g_slist_next (collected)) {
2033     GstMatroskaPad *collect_pad;
2034
2035     collect_pad = (GstMatroskaPad *) collected->data;
2036     /* fetch a new buffer if needed */
2037     if (collect_pad->buffer == NULL) {
2038       collect_pad->buffer = gst_collect_pads_pop (mux->collect,
2039           (GstCollectData *) collect_pad);
2040
2041       if (collect_pad->buffer != NULL)
2042         *popped = TRUE;
2043     }
2044
2045     /* if we have a buffer check if it is better then the current best one */
2046     if (collect_pad->buffer != NULL) {
2047       if (best == NULL || !GST_BUFFER_TIMESTAMP_IS_VALID (collect_pad->buffer)
2048           || (GST_BUFFER_TIMESTAMP_IS_VALID (best->buffer)
2049               && GST_BUFFER_TIMESTAMP (collect_pad->buffer) <
2050               GST_BUFFER_TIMESTAMP (best->buffer))) {
2051         best = collect_pad;
2052       }
2053     }
2054   }
2055
2056   return best;
2057 }
2058
2059 /**
2060  * gst_matroska_mux_buffer_header:
2061  * @track: Track context.
2062  * @relative_timestamp: relative timestamp of the buffer
2063  * @flags: Buffer flags.
2064  *
2065  * Create a buffer containing buffer header.
2066  * 
2067  * Returns: New buffer.
2068  */
2069 GstBuffer *
2070 gst_matroska_mux_create_buffer_header (GstMatroskaTrackContext * track,
2071     gint16 relative_timestamp, int flags)
2072 {
2073   GstBuffer *hdr;
2074
2075   hdr = gst_buffer_new_and_alloc (4);
2076   /* track num - FIXME: what if num >= 0x80 (unlikely)? */
2077   GST_BUFFER_DATA (hdr)[0] = track->num | 0x80;
2078   /* time relative to clustertime */
2079   GST_WRITE_UINT16_BE (GST_BUFFER_DATA (hdr) + 1, relative_timestamp);
2080
2081   /* flags */
2082   GST_BUFFER_DATA (hdr)[3] = flags;
2083
2084   return hdr;
2085 }
2086
2087 static GstBuffer *
2088 gst_matroska_mux_handle_dirac_packet (GstMatroskaMux * mux,
2089     GstMatroskaPad * collect_pad, GstBuffer * buf)
2090 {
2091   GstMatroskaTrackVideoContext *ctx =
2092       (GstMatroskaTrackVideoContext *) collect_pad->track;
2093   const guint8 *data = GST_BUFFER_DATA (buf);
2094   guint size = GST_BUFFER_SIZE (buf);
2095   guint8 parse_code;
2096   guint32 next_parse_offset;
2097   GstBuffer *ret = NULL;
2098   gboolean is_picture = FALSE;
2099
2100   if (GST_BUFFER_SIZE (buf) < 13) {
2101     gst_buffer_unref (buf);
2102     return ret;
2103   }
2104
2105   /* Check if this buffer contains a picture packet */
2106   while (size >= 13) {
2107     if (GST_READ_UINT32_BE (data) != 0x42424344) {
2108       gst_buffer_unref (buf);
2109       return ret;
2110     }
2111
2112     parse_code = GST_READ_UINT8 (data + 4);
2113     if (parse_code == 0x00) {
2114       if (ctx->dirac_unit) {
2115         gst_buffer_unref (ctx->dirac_unit);
2116         ctx->dirac_unit = NULL;
2117       }
2118     } else if (parse_code & 0x08) {
2119       is_picture = TRUE;
2120       break;
2121     }
2122
2123     next_parse_offset = GST_READ_UINT32_BE (data + 5);
2124
2125     data += next_parse_offset;
2126     size -= next_parse_offset;
2127   }
2128
2129   if (ctx->dirac_unit)
2130     ctx->dirac_unit = gst_buffer_join (ctx->dirac_unit, gst_buffer_ref (buf));
2131   else
2132     ctx->dirac_unit = gst_buffer_ref (buf);
2133
2134   if (is_picture) {
2135     ret = gst_buffer_make_metadata_writable (ctx->dirac_unit);
2136     ctx->dirac_unit = NULL;
2137     gst_buffer_copy_metadata (ret, buf,
2138         GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS |
2139         GST_BUFFER_COPY_CAPS);
2140     gst_buffer_unref (buf);
2141   } else {
2142     gst_buffer_unref (buf);
2143     ret = NULL;
2144   }
2145
2146   return ret;
2147 }
2148
2149 /**
2150  * gst_matroska_mux_write_data:
2151  * @mux: #GstMatroskaMux
2152  * @collect_pad: #GstMatroskaPad with the data
2153  *
2154  * Write collected data (called from gst_matroska_mux_collected).
2155  *
2156  * Returns: Result of the gst_pad_push issued to write the data.
2157  */
2158 static GstFlowReturn
2159 gst_matroska_mux_write_data (GstMatroskaMux * mux, GstMatroskaPad * collect_pad)
2160 {
2161   GstEbmlWrite *ebml = mux->ebml_write;
2162   GstBuffer *buf, *hdr;
2163   guint64 cluster, blockgroup;
2164   gboolean write_duration;
2165   gint16 relative_timestamp;
2166   gint64 relative_timestamp64;
2167   guint64 block_duration;
2168   gboolean is_video_keyframe = FALSE;
2169
2170   /* write data */
2171   buf = collect_pad->buffer;
2172   collect_pad->buffer = NULL;
2173
2174   /* vorbis/theora headers are retrieved from caps and put in CodecPrivate */
2175   if (collect_pad->track->xiph_headers_to_skip > 0) {
2176     GST_LOG_OBJECT (collect_pad->collect.pad, "dropping streamheader buffer");
2177     gst_buffer_unref (buf);
2178     --collect_pad->track->xiph_headers_to_skip;
2179     return GST_FLOW_OK;
2180   }
2181
2182   /* for dirac we have to queue up everything up to a picture unit */
2183   if (collect_pad->track->codec_id != NULL &&
2184       strcmp (collect_pad->track->codec_id,
2185           GST_MATROSKA_CODEC_ID_VIDEO_DIRAC) == 0) {
2186     buf = gst_matroska_mux_handle_dirac_packet (mux, collect_pad, buf);
2187     if (!buf)
2188       return GST_FLOW_OK;
2189   }
2190
2191   /* hm, invalid timestamp (due to --to be fixed--- element upstream);
2192    * this would wreak havoc with time stored in matroska file */
2193   /* TODO: maybe calculate a timestamp by using the previous timestamp
2194    * and default duration */
2195   if (!GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2196     GST_WARNING_OBJECT (collect_pad->collect.pad,
2197         "Invalid buffer timestamp; dropping buffer");
2198     gst_buffer_unref (buf);
2199     return GST_FLOW_OK;
2200   }
2201
2202   /* set the timestamp for outgoing buffers */
2203   ebml->timestamp = GST_BUFFER_TIMESTAMP (buf);
2204
2205   if (collect_pad->track->type == GST_MATROSKA_TRACK_TYPE_VIDEO &&
2206       !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2207     GST_LOG_OBJECT (mux, "have video keyframe, ts=%" GST_TIME_FORMAT,
2208         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2209     is_video_keyframe = TRUE;
2210   }
2211
2212   if (mux->cluster) {
2213     /* start a new cluster every two seconds or at keyframe */
2214     if (mux->cluster_time + GST_SECOND * 2 < GST_BUFFER_TIMESTAMP (buf)
2215         || is_video_keyframe) {
2216
2217       gst_ebml_write_master_finish (ebml, mux->cluster);
2218       mux->cluster_pos = ebml->pos;
2219       mux->cluster =
2220           gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_CLUSTER);
2221       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CLUSTERTIMECODE,
2222           GST_BUFFER_TIMESTAMP (buf) / mux->time_scale);
2223       mux->cluster_time = GST_BUFFER_TIMESTAMP (buf);
2224     }
2225   } else {
2226     /* first cluster */
2227
2228     mux->cluster_pos = ebml->pos;
2229     mux->cluster = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_CLUSTER);
2230     gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CLUSTERTIMECODE,
2231         GST_BUFFER_TIMESTAMP (buf) / mux->time_scale);
2232     mux->cluster_time = GST_BUFFER_TIMESTAMP (buf);
2233   }
2234   cluster = mux->cluster;
2235
2236   /* update duration of this track */
2237   if (GST_BUFFER_DURATION_IS_VALID (buf))
2238     collect_pad->duration += GST_BUFFER_DURATION (buf);
2239
2240   /* We currently write an index entry for each keyframe in a
2241    * video track or one entry for each cluster in an audio track
2242    * for audio only files. This can be largely improved, such as doing
2243    * one for each keyframe or each second (for all-keyframe
2244    * streams), only the *first* video track. But that'll come later... */
2245
2246   /* TODO: index is useful for every track, should contain the number of
2247    * the block in the cluster which contains the timestamp
2248    */
2249   if (is_video_keyframe) {
2250     GstMatroskaIndex *idx;
2251
2252     if (mux->num_indexes % 32 == 0) {
2253       mux->index = g_renew (GstMatroskaIndex, mux->index,
2254           mux->num_indexes + 32);
2255     }
2256     idx = &mux->index[mux->num_indexes++];
2257
2258     idx->pos = mux->cluster_pos;
2259     idx->time = GST_BUFFER_TIMESTAMP (buf);
2260     idx->track = collect_pad->track->num;
2261   } else if ((collect_pad->track->type == GST_MATROSKA_TRACK_TYPE_AUDIO) &&
2262       (mux->num_streams == 1)) {
2263     GstMatroskaIndex *idx;
2264
2265     if (mux->num_indexes % 32 == 0) {
2266       mux->index = g_renew (GstMatroskaIndex, mux->index,
2267           mux->num_indexes + 32);
2268     }
2269     idx = &mux->index[mux->num_indexes++];
2270
2271     idx->pos = mux->cluster_pos;
2272     idx->time = GST_BUFFER_TIMESTAMP (buf);
2273     idx->track = collect_pad->track->num;
2274   }
2275
2276   /* Check if the duration differs from the default duration. */
2277   write_duration = FALSE;
2278   block_duration = GST_BUFFER_DURATION (buf);
2279   if (GST_BUFFER_DURATION_IS_VALID (buf)) {
2280     if (block_duration != collect_pad->track->default_duration) {
2281       write_duration = TRUE;
2282     }
2283   }
2284
2285   /* write the block, for matroska v2 use SimpleBlock if possible
2286    * one slice (*breath*).
2287    * FIXME: Need to do correct lacing! */
2288   relative_timestamp64 = GST_BUFFER_TIMESTAMP (buf) - mux->cluster_time;
2289   if (relative_timestamp64 >= 0) {
2290     /* round the timestamp */
2291     relative_timestamp64 += mux->time_scale / 2;
2292   } else {
2293     /* round the timestamp */
2294     relative_timestamp64 -= mux->time_scale / 2;
2295   }
2296   relative_timestamp = relative_timestamp64 / (gint64) mux->time_scale;
2297   if (mux->matroska_version > 1 && !write_duration) {
2298     int flags =
2299         GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT) ? 0 : 0x80;
2300
2301     hdr =
2302         gst_matroska_mux_create_buffer_header (collect_pad->track,
2303         relative_timestamp, flags);
2304     gst_ebml_write_buffer_header (ebml, GST_MATROSKA_ID_SIMPLEBLOCK,
2305         GST_BUFFER_SIZE (buf) + GST_BUFFER_SIZE (hdr));
2306     gst_ebml_write_buffer (ebml, hdr);
2307     gst_ebml_write_buffer (ebml, buf);
2308
2309     return gst_ebml_last_write_result (ebml);
2310   } else {
2311     blockgroup = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_BLOCKGROUP);
2312     hdr =
2313         gst_matroska_mux_create_buffer_header (collect_pad->track,
2314         relative_timestamp, 0);
2315     gst_ebml_write_buffer_header (ebml, GST_MATROSKA_ID_BLOCK,
2316         GST_BUFFER_SIZE (buf) + GST_BUFFER_SIZE (hdr));
2317     gst_ebml_write_buffer (ebml, hdr);
2318     gst_ebml_write_buffer (ebml, buf);
2319     if (write_duration) {
2320       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_BLOCKDURATION,
2321           block_duration / mux->time_scale);
2322     }
2323     gst_ebml_write_master_finish (ebml, blockgroup);
2324     return gst_ebml_last_write_result (ebml);
2325   }
2326 }
2327
2328
2329 /**
2330  * gst_matroska_mux_collected:
2331  * @pads: #GstCollectPads
2332  * @uuser_data: #GstMatroskaMux
2333  *
2334  * Collectpads callback.
2335  *
2336  * Returns: #GstFlowReturn
2337  */
2338 static GstFlowReturn
2339 gst_matroska_mux_collected (GstCollectPads * pads, gpointer user_data)
2340 {
2341   GstMatroskaMux *mux = GST_MATROSKA_MUX (user_data);
2342   GstMatroskaPad *best;
2343   gboolean popped;
2344   GstFlowReturn ret;
2345
2346   GST_DEBUG_OBJECT (mux, "Collected pads");
2347
2348   /* start with a header */
2349   if (mux->state == GST_MATROSKA_MUX_STATE_START) {
2350     if (mux->collect->data == NULL) {
2351       GST_ELEMENT_ERROR (mux, STREAM, MUX, (NULL),
2352           ("No input streams configured"));
2353       return GST_FLOW_ERROR;
2354     }
2355     mux->state = GST_MATROSKA_MUX_STATE_HEADER;
2356     gst_matroska_mux_start (mux);
2357     mux->state = GST_MATROSKA_MUX_STATE_DATA;
2358   }
2359
2360   do {
2361     /* which stream to write from? */
2362     best = gst_matroska_mux_best_pad (mux, &popped);
2363
2364     /* if there is no best pad, we have reached EOS */
2365     if (best == NULL) {
2366       GST_DEBUG_OBJECT (mux, "No best pad finishing...");
2367       gst_matroska_mux_finish (mux);
2368       gst_pad_push_event (mux->srcpad, gst_event_new_eos ());
2369       ret = GST_FLOW_UNEXPECTED;
2370       break;
2371     }
2372     GST_DEBUG_OBJECT (best->collect.pad, "best pad - buffer ts %"
2373         GST_TIME_FORMAT " dur %" GST_TIME_FORMAT,
2374         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (best->buffer)),
2375         GST_TIME_ARGS (GST_BUFFER_DURATION (best->buffer)));
2376
2377     /* make note of first and last encountered timestamps, so we can calculate
2378      * the actual duration later when we send an updated header on eos */
2379     if (GST_BUFFER_TIMESTAMP_IS_VALID (best->buffer)) {
2380       GstClockTime start_ts = GST_BUFFER_TIMESTAMP (best->buffer);
2381       GstClockTime end_ts = start_ts;
2382
2383       if (GST_BUFFER_DURATION_IS_VALID (best->buffer))
2384         end_ts += GST_BUFFER_DURATION (best->buffer);
2385       else if (best->track->default_duration)
2386         end_ts += best->track->default_duration;
2387
2388       if (!GST_CLOCK_TIME_IS_VALID (best->end_ts) || end_ts > best->end_ts)
2389         best->end_ts = end_ts;
2390
2391       if (G_UNLIKELY (best->start_ts == GST_CLOCK_TIME_NONE ||
2392               start_ts < best->start_ts))
2393         best->start_ts = start_ts;
2394     }
2395
2396     /* write one buffer */
2397     ret = gst_matroska_mux_write_data (mux, best);
2398   } while (ret == GST_FLOW_OK && !popped);
2399
2400   return ret;
2401 }
2402
2403
2404 /**
2405  * gst_matroska_mux_change_state:
2406  * @element: #GstMatroskaMux
2407  * @transition: State change transition.
2408  *
2409  * Change the muxer state.
2410  *
2411  * Returns: #GstStateChangeReturn
2412  */
2413 static GstStateChangeReturn
2414 gst_matroska_mux_change_state (GstElement * element, GstStateChange transition)
2415 {
2416   GstStateChangeReturn ret;
2417   GstMatroskaMux *mux = GST_MATROSKA_MUX (element);
2418
2419   switch (transition) {
2420     case GST_STATE_CHANGE_NULL_TO_READY:
2421       break;
2422     case GST_STATE_CHANGE_READY_TO_PAUSED:
2423       gst_collect_pads_start (mux->collect);
2424       break;
2425     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2426       break;
2427     case GST_STATE_CHANGE_PAUSED_TO_READY:
2428       gst_collect_pads_stop (mux->collect);
2429       break;
2430     default:
2431       break;
2432   }
2433
2434   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2435
2436   switch (transition) {
2437     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2438       break;
2439     case GST_STATE_CHANGE_PAUSED_TO_READY:
2440       gst_matroska_mux_reset (GST_ELEMENT (mux));
2441       break;
2442     case GST_STATE_CHANGE_READY_TO_NULL:
2443       break;
2444     default:
2445       break;
2446   }
2447
2448   return ret;
2449 }
2450
2451 static void
2452 gst_matroska_mux_set_property (GObject * object,
2453     guint prop_id, const GValue * value, GParamSpec * pspec)
2454 {
2455   GstMatroskaMux *mux;
2456
2457   g_return_if_fail (GST_IS_MATROSKA_MUX (object));
2458   mux = GST_MATROSKA_MUX (object);
2459
2460   switch (prop_id) {
2461     case ARG_WRITING_APP:
2462       if (!g_value_get_string (value)) {
2463         GST_WARNING_OBJECT (mux, "writing-app property can not be NULL");
2464         break;
2465       }
2466       g_free (mux->writing_app);
2467       mux->writing_app = g_value_dup_string (value);
2468       break;
2469     case ARG_MATROSKA_VERSION:
2470       mux->matroska_version = g_value_get_int (value);
2471       break;
2472     default:
2473       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2474       break;
2475   }
2476 }
2477
2478 static void
2479 gst_matroska_mux_get_property (GObject * object,
2480     guint prop_id, GValue * value, GParamSpec * pspec)
2481 {
2482   GstMatroskaMux *mux;
2483
2484   g_return_if_fail (GST_IS_MATROSKA_MUX (object));
2485   mux = GST_MATROSKA_MUX (object);
2486
2487   switch (prop_id) {
2488     case ARG_WRITING_APP:
2489       g_value_set_string (value, mux->writing_app);
2490       break;
2491     case ARG_MATROSKA_VERSION:
2492       g_value_set_int (value, mux->matroska_version);
2493       break;
2494     default:
2495       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2496       break;
2497   }
2498 }
2499
2500 gboolean
2501 gst_matroska_mux_plugin_init (GstPlugin * plugin)
2502 {
2503   return gst_element_register (plugin, "matroskamux",
2504       GST_RANK_NONE, GST_TYPE_MATROSKA_MUX);
2505 }