matroska: don't leak serialized values when writing tags
[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 width, depth;
1304     gint endianness = G_LITTLE_ENDIAN;
1305     gboolean signedness = TRUE;
1306
1307     if (!gst_structure_get_int (structure, "width", &width) ||
1308         !gst_structure_get_int (structure, "depth", &depth) ||
1309         !gst_structure_get_boolean (structure, "signed", &signedness)) {
1310       GST_DEBUG_OBJECT (mux, "broken caps, width/depth/signed field missing");
1311       return FALSE;
1312     }
1313
1314     if (depth > 8 &&
1315         !gst_structure_get_int (structure, "endianness", &endianness)) {
1316       GST_DEBUG_OBJECT (mux, "broken caps, no endianness specified");
1317       return FALSE;
1318     }
1319
1320     if (width != depth) {
1321       GST_DEBUG_OBJECT (mux, "width must be same as depth!");
1322       return FALSE;
1323     }
1324
1325     /* FIXME: where is this spec'ed out? (tpm) */
1326     if ((width == 8 && signedness) || (width >= 16 && !signedness)) {
1327       GST_DEBUG_OBJECT (mux, "8-bit PCM must be unsigned, 16-bit PCM signed");
1328       return FALSE;
1329     }
1330
1331     audiocontext->bitdepth = depth;
1332     if (endianness == G_BIG_ENDIAN)
1333       context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE);
1334     else
1335       context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_LE);
1336
1337     return TRUE;
1338   } else if (!strcmp (mimetype, "audio/x-raw-float")) {
1339     gint width;
1340
1341     if (!gst_structure_get_int (structure, "width", &width)) {
1342       GST_DEBUG_OBJECT (mux, "broken caps, width field missing");
1343       return FALSE;
1344     }
1345
1346     audiocontext->bitdepth = width;
1347     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_PCM_FLOAT);
1348
1349     return TRUE;
1350   } else if (!strcmp (mimetype, "audio/x-vorbis")) {
1351     const GValue *streamheader;
1352
1353     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_VORBIS);
1354
1355     if (context->codec_priv != NULL) {
1356       g_free (context->codec_priv);
1357       context->codec_priv = NULL;
1358       context->codec_priv_size = 0;
1359     }
1360
1361     streamheader = gst_structure_get_value (structure, "streamheader");
1362     if (!vorbis_streamheader_to_codecdata (streamheader, context)) {
1363       GST_ELEMENT_ERROR (mux, STREAM, MUX, (NULL),
1364           ("vorbis stream headers missing or malformed"));
1365       return FALSE;
1366     }
1367     return TRUE;
1368   } else if (!strcmp (mimetype, "audio/x-flac")) {
1369     const GValue *streamheader;
1370
1371     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_FLAC);
1372     if (context->codec_priv != NULL) {
1373       g_free (context->codec_priv);
1374       context->codec_priv = NULL;
1375       context->codec_priv_size = 0;
1376     }
1377
1378     streamheader = gst_structure_get_value (structure, "streamheader");
1379     if (!flac_streamheader_to_codecdata (streamheader, context)) {
1380       GST_ELEMENT_ERROR (mux, STREAM, MUX, (NULL),
1381           ("flac stream headers missing or malformed"));
1382       return FALSE;
1383     }
1384     return TRUE;
1385   } else if (!strcmp (mimetype, "audio/x-ac3")) {
1386     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_AC3);
1387
1388     return TRUE;
1389   } else if (!strcmp (mimetype, "audio/x-tta")) {
1390     gint width;
1391
1392     /* TTA frame duration */
1393     context->default_duration = 1.04489795918367346939 * GST_SECOND;
1394
1395     gst_structure_get_int (structure, "width", &width);
1396     audiocontext->bitdepth = width;
1397     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_TTA);
1398
1399     return TRUE;
1400   } else if (!strcmp (mimetype, "audio/x-pn-realaudio")) {
1401     gint raversion;
1402     const GValue *mdpr_data;
1403
1404     gst_structure_get_int (structure, "raversion", &raversion);
1405     switch (raversion) {
1406       case 1:
1407         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4);
1408         break;
1409       case 2:
1410         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_REAL_28_8);
1411         break;
1412       case 8:
1413         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK);
1414         break;
1415       default:
1416         return FALSE;
1417     }
1418
1419     mdpr_data = gst_structure_get_value (structure, "mdpr_data");
1420     if (mdpr_data != NULL) {
1421       guint8 *priv_data = NULL;
1422       guint priv_data_size = 0;
1423
1424       GstBuffer *codec_data_buf = g_value_peek_pointer (mdpr_data);
1425
1426       priv_data_size = GST_BUFFER_SIZE (codec_data_buf);
1427       priv_data = g_malloc0 (priv_data_size);
1428
1429       memcpy (priv_data, GST_BUFFER_DATA (codec_data_buf), priv_data_size);
1430
1431       context->codec_priv = priv_data;
1432       context->codec_priv_size = priv_data_size;
1433     }
1434
1435     return TRUE;
1436   }
1437
1438   return FALSE;
1439 }
1440
1441
1442 /**
1443  * gst_matroska_mux_subtitle_pad_setcaps:
1444  * @pad: Pad which got the caps.
1445  * @caps: New caps.
1446  *
1447  * Setcaps function for subtitle sink pad.
1448  *
1449  * Returns: #TRUE on success.
1450  */
1451 static gboolean
1452 gst_matroska_mux_subtitle_pad_setcaps (GstPad * pad, GstCaps * caps)
1453 {
1454   /* FIXME:
1455    * Consider this as boilerplate code for now. There is
1456    * no single subtitle creation element in GStreamer,
1457    * neither do I know how subtitling works at all. */
1458
1459   return FALSE;
1460 }
1461
1462
1463 /**
1464  * gst_matroska_mux_request_new_pad:
1465  * @element: #GstMatroskaMux.
1466  * @templ: #GstPadTemplate.
1467  * @pad_name: New pad name.
1468  *
1469  * Request pad function for sink templates.
1470  *
1471  * Returns: New #GstPad.
1472  */
1473 static GstPad *
1474 gst_matroska_mux_request_new_pad (GstElement * element,
1475     GstPadTemplate * templ, const gchar * pad_name)
1476 {
1477   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
1478   GstMatroskaMux *mux = GST_MATROSKA_MUX (element);
1479   GstMatroskaPad *collect_pad;
1480   GstPad *newpad = NULL;
1481   gchar *name = NULL;
1482   GstPadSetCapsFunction setcapsfunc = NULL;
1483   GstMatroskaTrackContext *context = NULL;
1484
1485   if (templ == gst_element_class_get_pad_template (klass, "audio_%d")) {
1486     name = g_strdup_printf ("audio_%d", mux->num_a_streams++);
1487     setcapsfunc = GST_DEBUG_FUNCPTR (gst_matroska_mux_audio_pad_setcaps);
1488     context = (GstMatroskaTrackContext *)
1489         g_new0 (GstMatroskaTrackAudioContext, 1);
1490     context->type = GST_MATROSKA_TRACK_TYPE_AUDIO;
1491     context->name = g_strdup ("Audio");
1492   } else if (templ == gst_element_class_get_pad_template (klass, "video_%d")) {
1493     name = g_strdup_printf ("video_%d", mux->num_v_streams++);
1494     setcapsfunc = GST_DEBUG_FUNCPTR (gst_matroska_mux_video_pad_setcaps);
1495     context = (GstMatroskaTrackContext *)
1496         g_new0 (GstMatroskaTrackVideoContext, 1);
1497     context->type = GST_MATROSKA_TRACK_TYPE_VIDEO;
1498     context->name = g_strdup ("Video");
1499   } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%d")) {
1500     name = g_strdup_printf ("subtitle_%d", mux->num_t_streams++);
1501     setcapsfunc = GST_DEBUG_FUNCPTR (gst_matroska_mux_subtitle_pad_setcaps);
1502     context = (GstMatroskaTrackContext *)
1503         g_new0 (GstMatroskaTrackSubtitleContext, 1);
1504     context->type = GST_MATROSKA_TRACK_TYPE_SUBTITLE;
1505     context->name = g_strdup ("Subtitle");
1506   } else {
1507     GST_WARNING_OBJECT (mux, "This is not our template!");
1508     return NULL;
1509   }
1510
1511   newpad = gst_pad_new_from_template (templ, name);
1512   g_free (name);
1513   collect_pad = (GstMatroskaPad *)
1514       gst_collect_pads_add_pad_full (mux->collect, newpad,
1515       sizeof (GstMatroskaPad),
1516       (GstCollectDataDestroyNotify) gst_matroska_pad_free);
1517
1518   collect_pad->track = context;
1519   gst_matroska_pad_reset (collect_pad, FALSE);
1520
1521   /* FIXME: hacked way to override/extend the event function of
1522    * GstCollectPads; because it sets its own event function giving the
1523    * element no access to events.
1524    * TODO GstCollectPads should really give its 'users' a clean chance to
1525    * properly handle events that are not meant for collectpads itself.
1526    * Perhaps a callback or so, though rejected (?) in #340060.
1527    * This would allow (clean) transcoding of info from demuxer/streams
1528    * to another muxer */
1529   mux->collect_event = (GstPadEventFunction) GST_PAD_EVENTFUNC (newpad);
1530   gst_pad_set_event_function (newpad,
1531       GST_DEBUG_FUNCPTR (gst_matroska_mux_handle_sink_event));
1532
1533   gst_pad_set_setcaps_function (newpad, setcapsfunc);
1534   gst_pad_set_active (newpad, TRUE);
1535   gst_element_add_pad (element, newpad);
1536   mux->num_streams++;
1537
1538   return newpad;
1539 }
1540
1541 /**
1542  * gst_matroska_mux_release_pad:
1543  * @element: #GstMatroskaMux.
1544  * @pad: Pad to release.
1545  *
1546  * Release a previously requested pad.
1547 */
1548 static void
1549 gst_matroska_mux_release_pad (GstElement * element, GstPad * pad)
1550 {
1551   GstMatroskaMux *mux;
1552   GSList *walk;
1553
1554   mux = GST_MATROSKA_MUX (GST_PAD_PARENT (pad));
1555
1556   for (walk = mux->collect->data; walk; walk = g_slist_next (walk)) {
1557     GstCollectData *cdata = (GstCollectData *) walk->data;
1558     GstMatroskaPad *collect_pad = (GstMatroskaPad *) cdata;
1559
1560     if (cdata->pad == pad) {
1561       GstClockTime min_dur;     /* observed minimum duration */
1562
1563       if (GST_CLOCK_TIME_IS_VALID (collect_pad->start_ts) &&
1564           GST_CLOCK_TIME_IS_VALID (collect_pad->end_ts)) {
1565         min_dur = GST_CLOCK_DIFF (collect_pad->start_ts, collect_pad->end_ts);
1566         if (collect_pad->duration < min_dur)
1567           collect_pad->duration = min_dur;
1568       }
1569
1570       if (GST_CLOCK_TIME_IS_VALID (collect_pad->duration) &&
1571           mux->duration < collect_pad->duration)
1572         mux->duration = collect_pad->duration;
1573
1574       break;
1575     }
1576   }
1577
1578   gst_collect_pads_remove_pad (mux->collect, pad);
1579   if (gst_element_remove_pad (element, pad))
1580     mux->num_streams--;
1581 }
1582
1583
1584 /**
1585  * gst_matroska_mux_track_header:
1586  * @mux: #GstMatroskaMux
1587  * @context: Tack context.
1588  *
1589  * Write a track header.
1590  */
1591 static void
1592 gst_matroska_mux_track_header (GstMatroskaMux * mux,
1593     GstMatroskaTrackContext * context)
1594 {
1595   GstEbmlWrite *ebml = mux->ebml_write;
1596   guint64 master;
1597
1598   /* TODO: check if everything necessary is written and check default values */
1599
1600   /* track type goes before the type-specific stuff */
1601   gst_ebml_write_uint (ebml, GST_MATROSKA_ID_TRACKNUMBER, context->num);
1602   gst_ebml_write_uint (ebml, GST_MATROSKA_ID_TRACKTYPE, context->type);
1603
1604   gst_ebml_write_uint (ebml, GST_MATROSKA_ID_TRACKUID,
1605       gst_matroska_mux_create_uid ());
1606   if (context->default_duration) {
1607     gst_ebml_write_uint (ebml, GST_MATROSKA_ID_TRACKDEFAULTDURATION,
1608         context->default_duration);
1609   }
1610   if (context->language) {
1611     gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_TRACKLANGUAGE,
1612         context->language);
1613   }
1614
1615   /* type-specific stuff */
1616   switch (context->type) {
1617     case GST_MATROSKA_TRACK_TYPE_VIDEO:{
1618       GstMatroskaTrackVideoContext *videocontext =
1619           (GstMatroskaTrackVideoContext *) context;
1620
1621       master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TRACKVIDEO);
1622       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_VIDEOPIXELWIDTH,
1623           videocontext->pixel_width);
1624       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_VIDEOPIXELHEIGHT,
1625           videocontext->pixel_height);
1626       if (videocontext->display_width && videocontext->display_height) {
1627         gst_ebml_write_uint (ebml, GST_MATROSKA_ID_VIDEODISPLAYWIDTH,
1628             videocontext->display_width);
1629         gst_ebml_write_uint (ebml, GST_MATROSKA_ID_VIDEODISPLAYHEIGHT,
1630             videocontext->display_height);
1631       }
1632       if (context->flags & GST_MATROSKA_VIDEOTRACK_INTERLACED)
1633         gst_ebml_write_uint (ebml, GST_MATROSKA_ID_VIDEOFLAGINTERLACED, 1);
1634       if (videocontext->fourcc) {
1635         guint32 fcc_le = GUINT32_TO_LE (videocontext->fourcc);
1636
1637         gst_ebml_write_binary (ebml, GST_MATROSKA_ID_VIDEOCOLOURSPACE,
1638             (gpointer) & fcc_le, 4);
1639       }
1640       gst_ebml_write_master_finish (ebml, master);
1641
1642       break;
1643     }
1644
1645     case GST_MATROSKA_TRACK_TYPE_AUDIO:{
1646       GstMatroskaTrackAudioContext *audiocontext =
1647           (GstMatroskaTrackAudioContext *) context;
1648
1649       master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TRACKAUDIO);
1650       if (audiocontext->samplerate != 8000)
1651         gst_ebml_write_float (ebml, GST_MATROSKA_ID_AUDIOSAMPLINGFREQ,
1652             audiocontext->samplerate);
1653       if (audiocontext->channels != 1)
1654         gst_ebml_write_uint (ebml, GST_MATROSKA_ID_AUDIOCHANNELS,
1655             audiocontext->channels);
1656       if (audiocontext->bitdepth) {
1657         gst_ebml_write_uint (ebml, GST_MATROSKA_ID_AUDIOBITDEPTH,
1658             audiocontext->bitdepth);
1659       }
1660       gst_ebml_write_master_finish (ebml, master);
1661
1662       break;
1663     }
1664
1665     default:
1666       /* doesn't need type-specific data */
1667       break;
1668   }
1669
1670   gst_ebml_write_ascii (ebml, GST_MATROSKA_ID_CODECID, context->codec_id);
1671   if (context->codec_priv)
1672     gst_ebml_write_binary (ebml, GST_MATROSKA_ID_CODECPRIVATE,
1673         context->codec_priv, context->codec_priv_size);
1674   /* FIXME: until we have a nice way of getting the codecname
1675    * out of the caps, I'm not going to enable this. Too much
1676    * (useless, double, boring) work... */
1677   /* TODO: Use value from tags if any */
1678   /*gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_CODECNAME,
1679      context->codec_name); */
1680   gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_TRACKNAME, context->name);
1681 }
1682
1683
1684 /**
1685  * gst_matroska_mux_start:
1686  * @mux: #GstMatroskaMux
1687  *
1688  * Start a new matroska file (write headers etc...)
1689  */
1690 static void
1691 gst_matroska_mux_start (GstMatroskaMux * mux)
1692 {
1693   GstEbmlWrite *ebml = mux->ebml_write;
1694   guint32 seekhead_id[] = { GST_MATROSKA_ID_SEGMENTINFO,
1695     GST_MATROSKA_ID_TRACKS,
1696     GST_MATROSKA_ID_CUES,
1697     GST_MATROSKA_ID_TAGS,
1698     0
1699   };
1700   guint64 master, child;
1701   GSList *collected;
1702   int i;
1703   guint tracknum = 1;
1704   GstClockTime duration = 0;
1705   guint32 segment_uid[4];
1706   GTimeVal time = { 0, 0 };
1707
1708   /* we start with a EBML header */
1709   gst_ebml_write_header (ebml, "matroska", mux->matroska_version);
1710
1711   /* start a segment */
1712   mux->segment_pos =
1713       gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_SEGMENT);
1714   mux->segment_master = ebml->pos;
1715
1716   /* the rest of the header is cached */
1717   gst_ebml_write_set_cache (ebml, 0x1000);
1718
1719   /* seekhead (table of contents) - we set the positions later */
1720   mux->seekhead_pos = ebml->pos;
1721   master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_SEEKHEAD);
1722   for (i = 0; seekhead_id[i] != 0; i++) {
1723     child = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_SEEKENTRY);
1724     gst_ebml_write_uint (ebml, GST_MATROSKA_ID_SEEKID, seekhead_id[i]);
1725     gst_ebml_write_uint (ebml, GST_MATROSKA_ID_SEEKPOSITION, -1);
1726     gst_ebml_write_master_finish (ebml, child);
1727   }
1728   gst_ebml_write_master_finish (ebml, master);
1729
1730   /* segment info */
1731   mux->info_pos = ebml->pos;
1732   master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_SEGMENTINFO);
1733   for (i = 0; i < 4; i++) {
1734     segment_uid[i] = g_random_int ();
1735   }
1736   gst_ebml_write_binary (ebml, GST_MATROSKA_ID_SEGMENTUID,
1737       (guint8 *) segment_uid, 16);
1738   gst_ebml_write_uint (ebml, GST_MATROSKA_ID_TIMECODESCALE, mux->time_scale);
1739   mux->duration_pos = ebml->pos;
1740   /* get duration */
1741   for (collected = mux->collect->data; collected;
1742       collected = g_slist_next (collected)) {
1743     GstMatroskaPad *collect_pad;
1744     GstFormat format = GST_FORMAT_TIME;
1745     GstPad *thepad;
1746     gint64 trackduration;
1747
1748     collect_pad = (GstMatroskaPad *) collected->data;
1749     thepad = collect_pad->collect.pad;
1750
1751     /* Query the total length of the track. */
1752     GST_DEBUG_OBJECT (thepad, "querying peer duration");
1753     if (gst_pad_query_peer_duration (thepad, &format, &trackduration)) {
1754       GST_DEBUG_OBJECT (thepad, "duration: %" GST_TIME_FORMAT,
1755           GST_TIME_ARGS (trackduration));
1756       if (trackduration != GST_CLOCK_TIME_NONE && trackduration > duration) {
1757         duration = (GstClockTime) trackduration;
1758       }
1759     }
1760   }
1761   gst_ebml_write_float (ebml, GST_MATROSKA_ID_DURATION,
1762       gst_guint64_to_gdouble (duration) /
1763       gst_guint64_to_gdouble (mux->time_scale));
1764
1765   gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_MUXINGAPP,
1766       "GStreamer plugin version " PACKAGE_VERSION);
1767   if (mux->writing_app && mux->writing_app[0]) {
1768     gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_WRITINGAPP, mux->writing_app);
1769   }
1770   g_get_current_time (&time);
1771   gst_ebml_write_date (ebml, GST_MATROSKA_ID_DATEUTC, time.tv_sec);
1772   gst_ebml_write_master_finish (ebml, master);
1773
1774   /* tracks */
1775   mux->tracks_pos = ebml->pos;
1776   master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TRACKS);
1777
1778   for (collected = mux->collect->data; collected;
1779       collected = g_slist_next (collected)) {
1780     GstMatroskaPad *collect_pad;
1781     GstPad *thepad;
1782
1783     collect_pad = (GstMatroskaPad *) collected->data;
1784     thepad = collect_pad->collect.pad;
1785
1786     if (gst_pad_is_linked (thepad) && gst_pad_is_active (thepad) &&
1787         collect_pad->track->codec_id != 0) {
1788       collect_pad->track->num = tracknum++;
1789       child = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TRACKENTRY);
1790       gst_matroska_mux_track_header (mux, collect_pad->track);
1791       gst_ebml_write_master_finish (ebml, child);
1792     }
1793   }
1794   gst_ebml_write_master_finish (ebml, master);
1795
1796   /* lastly, flush the cache */
1797   gst_ebml_write_flush_cache (ebml);
1798 }
1799
1800 static void
1801 gst_matroska_mux_write_simple_tag (const GstTagList * list, const gchar * tag,
1802     gpointer data)
1803 {
1804   /* TODO: more sensible tag mappings */
1805   struct
1806   {
1807     gchar *matroska_tagname;
1808     gchar *gstreamer_tagname;
1809   }
1810   tag_conv[] = {
1811     {
1812     GST_MATROSKA_TAG_ID_TITLE, GST_TAG_TITLE}, {
1813     GST_MATROSKA_TAG_ID_AUTHOR, GST_TAG_ARTIST}, {
1814     GST_MATROSKA_TAG_ID_ALBUM, GST_TAG_ALBUM}, {
1815     GST_MATROSKA_TAG_ID_COMMENTS, GST_TAG_COMMENT}, {
1816     GST_MATROSKA_TAG_ID_BITSPS, GST_TAG_BITRATE}, {
1817     GST_MATROSKA_TAG_ID_BPS, GST_TAG_BITRATE}, {
1818     GST_MATROSKA_TAG_ID_ENCODER, GST_TAG_ENCODER}, {
1819     GST_MATROSKA_TAG_ID_DATE, GST_TAG_DATE}, {
1820     GST_MATROSKA_TAG_ID_ISRC, GST_TAG_ISRC}, {
1821     GST_MATROSKA_TAG_ID_COPYRIGHT, GST_TAG_COPYRIGHT}, {
1822     GST_MATROSKA_TAG_ID_BPM, GST_TAG_BEATS_PER_MINUTE}, {
1823     GST_MATROSKA_TAG_ID_TERMS_OF_USE, GST_TAG_LICENSE}, {
1824     GST_MATROSKA_TAG_ID_COMPOSER, GST_TAG_COMPOSER}, {
1825     GST_MATROSKA_TAG_ID_LEAD_PERFORMER, GST_TAG_PERFORMER}, {
1826     GST_MATROSKA_TAG_ID_GENRE, GST_TAG_GENRE}
1827   };
1828   GstEbmlWrite *ebml = (GstEbmlWrite *) data;
1829   guint i;
1830   guint64 simpletag_master;
1831
1832   for (i = 0; i < G_N_ELEMENTS (tag_conv); i++) {
1833     const gchar *tagname_gst = tag_conv[i].gstreamer_tagname;
1834     const gchar *tagname_mkv = tag_conv[i].matroska_tagname;
1835
1836     if (strcmp (tagname_gst, tag) == 0) {
1837       GValue src = { 0, };
1838       gchar *dest;
1839
1840       if (!gst_tag_list_copy_value (&src, list, tag))
1841         break;
1842       if ((dest = gst_value_serialize (&src))) {
1843
1844         simpletag_master = gst_ebml_write_master_start (ebml,
1845             GST_MATROSKA_ID_SIMPLETAG);
1846         gst_ebml_write_ascii (ebml, GST_MATROSKA_ID_TAGNAME, tagname_mkv);
1847         gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_TAGSTRING, dest);
1848         gst_ebml_write_master_finish (ebml, simpletag_master);
1849         g_free (dest);
1850       } else {
1851         GST_WARNING ("Can't transform tag '%s' to string", tagname_mkv);
1852       }
1853       g_value_unset (&src);
1854       break;
1855     }
1856   }
1857 }
1858
1859
1860 /**
1861  * gst_matroska_mux_finish:
1862  * @mux: #GstMatroskaMux
1863  *
1864  * Finish a new matroska file (write index etc...)
1865  */
1866 static void
1867 gst_matroska_mux_finish (GstMatroskaMux * mux)
1868 {
1869   GstEbmlWrite *ebml = mux->ebml_write;
1870   guint64 pos;
1871   guint64 duration = 0;
1872   GSList *collected;
1873   const GstTagList *tags;
1874
1875   /* finish last cluster */
1876   if (mux->cluster) {
1877     gst_ebml_write_master_finish (ebml, mux->cluster);
1878   }
1879
1880   /* cues */
1881   if (mux->index != NULL) {
1882     guint n;
1883     guint64 master, pointentry_master, trackpos_master;
1884
1885     mux->cues_pos = ebml->pos;
1886     gst_ebml_write_set_cache (ebml, 12 + 41 * mux->num_indexes);
1887     master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_CUES);
1888
1889     for (n = 0; n < mux->num_indexes; n++) {
1890       GstMatroskaIndex *idx = &mux->index[n];
1891
1892       pointentry_master = gst_ebml_write_master_start (ebml,
1893           GST_MATROSKA_ID_POINTENTRY);
1894       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CUETIME,
1895           idx->time / mux->time_scale);
1896       trackpos_master = gst_ebml_write_master_start (ebml,
1897           GST_MATROSKA_ID_CUETRACKPOSITIONS);
1898       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CUETRACK, idx->track);
1899       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CUECLUSTERPOSITION,
1900           idx->pos - mux->segment_master);
1901       gst_ebml_write_master_finish (ebml, trackpos_master);
1902       gst_ebml_write_master_finish (ebml, pointentry_master);
1903     }
1904
1905     gst_ebml_write_master_finish (ebml, master);
1906     gst_ebml_write_flush_cache (ebml);
1907   }
1908
1909   /* tags */
1910   tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (mux));
1911
1912   if (tags != NULL && !gst_tag_list_is_empty (tags)) {
1913     guint64 master_tags, master_tag;
1914
1915     GST_DEBUG ("Writing tags");
1916
1917     /* TODO: maybe limit via the TARGETS id by looking at the source pad */
1918     mux->tags_pos = ebml->pos;
1919     master_tags = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TAGS);
1920     master_tag = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TAG);
1921     gst_tag_list_foreach (tags, gst_matroska_mux_write_simple_tag, ebml);
1922     gst_ebml_write_master_finish (ebml, master_tag);
1923     gst_ebml_write_master_finish (ebml, master_tags);
1924   }
1925
1926   /* update seekhead. We know that:
1927    * - a seekhead contains 4 entries.
1928    * - order of entries is as above.
1929    * - a seekhead has a 4-byte header + 8-byte length
1930    * - each entry is 2-byte master, 2-byte ID pointer,
1931    *     2-byte length pointer, all 8/1-byte length, 4-
1932    *     byte ID and 8-byte length pointer, where the
1933    *     length pointer starts at 20.
1934    * - all entries are local to the segment (so pos - segment_master).
1935    * - so each entry is at 12 + 20 + num * 28. */
1936   gst_ebml_replace_uint (ebml, mux->seekhead_pos + 32,
1937       mux->info_pos - mux->segment_master);
1938   gst_ebml_replace_uint (ebml, mux->seekhead_pos + 60,
1939       mux->tracks_pos - mux->segment_master);
1940   if (mux->index != NULL) {
1941     gst_ebml_replace_uint (ebml, mux->seekhead_pos + 88,
1942         mux->cues_pos - mux->segment_master);
1943   } else {
1944     /* void'ify */
1945     guint64 my_pos = ebml->pos;
1946
1947     gst_ebml_write_seek (ebml, mux->seekhead_pos + 68);
1948     gst_ebml_write_buffer_header (ebml, GST_EBML_ID_VOID, 26);
1949     gst_ebml_write_seek (ebml, my_pos);
1950   }
1951   if (tags != NULL) {
1952     gst_ebml_replace_uint (ebml, mux->seekhead_pos + 116,
1953         mux->tags_pos - mux->segment_master);
1954   } else {
1955     /* void'ify */
1956     guint64 my_pos = ebml->pos;
1957
1958     gst_ebml_write_seek (ebml, mux->seekhead_pos + 96);
1959     gst_ebml_write_buffer_header (ebml, GST_EBML_ID_VOID, 26);
1960     gst_ebml_write_seek (ebml, my_pos);
1961   }
1962
1963   /* update duration */
1964   /* first get the overall duration */
1965   /* a released track may have left a duration in here */
1966   duration = mux->duration;
1967   for (collected = mux->collect->data; collected;
1968       collected = g_slist_next (collected)) {
1969     GstMatroskaPad *collect_pad;
1970     GstClockTime min_duration;  /* observed minimum duration */
1971
1972     collect_pad = (GstMatroskaPad *) collected->data;
1973
1974     GST_DEBUG_OBJECT (mux, "Pad %" GST_PTR_FORMAT " start ts %" GST_TIME_FORMAT
1975         " end ts %" GST_TIME_FORMAT, collect_pad,
1976         GST_TIME_ARGS (collect_pad->start_ts),
1977         GST_TIME_ARGS (collect_pad->end_ts));
1978
1979     if (GST_CLOCK_TIME_IS_VALID (collect_pad->start_ts) &&
1980         GST_CLOCK_TIME_IS_VALID (collect_pad->end_ts)) {
1981       min_duration =
1982           GST_CLOCK_DIFF (collect_pad->start_ts, collect_pad->end_ts);
1983       if (collect_pad->duration < min_duration)
1984         collect_pad->duration = min_duration;
1985       GST_DEBUG_OBJECT (collect_pad, "final track duration: %" GST_TIME_FORMAT,
1986           GST_TIME_ARGS (collect_pad->duration));
1987     }
1988
1989     if (GST_CLOCK_TIME_IS_VALID (collect_pad->duration) &&
1990         duration < collect_pad->duration)
1991       duration = collect_pad->duration;
1992   }
1993   if (duration != 0) {
1994     GST_DEBUG_OBJECT (mux, "final total duration: %" GST_TIME_FORMAT,
1995         GST_TIME_ARGS (duration));
1996     pos = mux->ebml_write->pos;
1997     gst_ebml_write_seek (ebml, mux->duration_pos);
1998     gst_ebml_write_float (ebml, GST_MATROSKA_ID_DURATION,
1999         gst_guint64_to_gdouble (duration) /
2000         gst_guint64_to_gdouble (mux->time_scale));
2001     gst_ebml_write_seek (ebml, pos);
2002   } else {
2003     /* void'ify */
2004     guint64 my_pos = ebml->pos;
2005
2006     gst_ebml_write_seek (ebml, mux->duration_pos);
2007     gst_ebml_write_buffer_header (ebml, GST_EBML_ID_VOID, 8);
2008     gst_ebml_write_seek (ebml, my_pos);
2009   }
2010
2011   /* finish segment - this also writes element length */
2012   gst_ebml_write_master_finish (ebml, mux->segment_pos);
2013 }
2014
2015
2016 /**
2017  * gst_matroska_mux_best_pad:
2018  * @mux: #GstMatroskaMux
2019  * @popped: True if at least one buffer was popped from #GstCollectPads
2020  *
2021  * Find a pad with the oldest data 
2022  * (data from this pad should be written first).
2023  *
2024  * Returns: Selected pad.
2025  */
2026 static GstMatroskaPad *
2027 gst_matroska_mux_best_pad (GstMatroskaMux * mux, gboolean * popped)
2028 {
2029   GSList *collected;
2030   GstMatroskaPad *best = NULL;
2031
2032   *popped = FALSE;
2033   for (collected = mux->collect->data; collected;
2034       collected = g_slist_next (collected)) {
2035     GstMatroskaPad *collect_pad;
2036
2037     collect_pad = (GstMatroskaPad *) collected->data;
2038     /* fetch a new buffer if needed */
2039     if (collect_pad->buffer == NULL) {
2040       collect_pad->buffer = gst_collect_pads_pop (mux->collect,
2041           (GstCollectData *) collect_pad);
2042
2043       if (collect_pad->buffer != NULL)
2044         *popped = TRUE;
2045     }
2046
2047     /* if we have a buffer check if it is better then the current best one */
2048     if (collect_pad->buffer != NULL) {
2049       if (best == NULL || !GST_BUFFER_TIMESTAMP_IS_VALID (collect_pad->buffer)
2050           || (GST_BUFFER_TIMESTAMP_IS_VALID (best->buffer)
2051               && GST_BUFFER_TIMESTAMP (collect_pad->buffer) <
2052               GST_BUFFER_TIMESTAMP (best->buffer))) {
2053         best = collect_pad;
2054       }
2055     }
2056   }
2057
2058   return best;
2059 }
2060
2061 /**
2062  * gst_matroska_mux_buffer_header:
2063  * @track: Track context.
2064  * @relative_timestamp: relative timestamp of the buffer
2065  * @flags: Buffer flags.
2066  *
2067  * Create a buffer containing buffer header.
2068  * 
2069  * Returns: New buffer.
2070  */
2071 GstBuffer *
2072 gst_matroska_mux_create_buffer_header (GstMatroskaTrackContext * track,
2073     gint16 relative_timestamp, int flags)
2074 {
2075   GstBuffer *hdr;
2076
2077   hdr = gst_buffer_new_and_alloc (4);
2078   /* track num - FIXME: what if num >= 0x80 (unlikely)? */
2079   GST_BUFFER_DATA (hdr)[0] = track->num | 0x80;
2080   /* time relative to clustertime */
2081   GST_WRITE_UINT16_BE (GST_BUFFER_DATA (hdr) + 1, relative_timestamp);
2082
2083   /* flags */
2084   GST_BUFFER_DATA (hdr)[3] = flags;
2085
2086   return hdr;
2087 }
2088
2089 static GstBuffer *
2090 gst_matroska_mux_handle_dirac_packet (GstMatroskaMux * mux,
2091     GstMatroskaPad * collect_pad, GstBuffer * buf)
2092 {
2093   GstMatroskaTrackVideoContext *ctx =
2094       (GstMatroskaTrackVideoContext *) collect_pad->track;
2095   const guint8 *data = GST_BUFFER_DATA (buf);
2096   guint size = GST_BUFFER_SIZE (buf);
2097   guint8 parse_code;
2098   guint32 next_parse_offset;
2099   GstBuffer *ret = NULL;
2100   gboolean is_picture = FALSE;
2101
2102   if (GST_BUFFER_SIZE (buf) < 13) {
2103     gst_buffer_unref (buf);
2104     return ret;
2105   }
2106
2107   /* Check if this buffer contains a picture packet */
2108   while (size >= 13) {
2109     if (GST_READ_UINT32_BE (data) != 0x42424344) {
2110       gst_buffer_unref (buf);
2111       return ret;
2112     }
2113
2114     parse_code = GST_READ_UINT8 (data + 4);
2115     if (parse_code == 0x00) {
2116       if (ctx->dirac_unit) {
2117         gst_buffer_unref (ctx->dirac_unit);
2118         ctx->dirac_unit = NULL;
2119       }
2120     } else if (parse_code & 0x08) {
2121       is_picture = TRUE;
2122       break;
2123     }
2124
2125     next_parse_offset = GST_READ_UINT32_BE (data + 5);
2126
2127     data += next_parse_offset;
2128     size -= next_parse_offset;
2129   }
2130
2131   if (ctx->dirac_unit)
2132     ctx->dirac_unit = gst_buffer_join (ctx->dirac_unit, gst_buffer_ref (buf));
2133   else
2134     ctx->dirac_unit = gst_buffer_ref (buf);
2135
2136   if (is_picture) {
2137     ret = gst_buffer_make_metadata_writable (ctx->dirac_unit);
2138     ctx->dirac_unit = NULL;
2139     gst_buffer_copy_metadata (ret, buf,
2140         GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS |
2141         GST_BUFFER_COPY_CAPS);
2142     gst_buffer_unref (buf);
2143   } else {
2144     gst_buffer_unref (buf);
2145     ret = NULL;
2146   }
2147
2148   return ret;
2149 }
2150
2151 /**
2152  * gst_matroska_mux_write_data:
2153  * @mux: #GstMatroskaMux
2154  * @collect_pad: #GstMatroskaPad with the data
2155  *
2156  * Write collected data (called from gst_matroska_mux_collected).
2157  *
2158  * Returns: Result of the gst_pad_push issued to write the data.
2159  */
2160 static GstFlowReturn
2161 gst_matroska_mux_write_data (GstMatroskaMux * mux, GstMatroskaPad * collect_pad)
2162 {
2163   GstEbmlWrite *ebml = mux->ebml_write;
2164   GstBuffer *buf, *hdr;
2165   guint64 cluster, blockgroup;
2166   gboolean write_duration;
2167   gint16 relative_timestamp;
2168   gint64 relative_timestamp64;
2169   guint64 block_duration;
2170   gboolean is_video_keyframe = FALSE;
2171
2172   /* write data */
2173   buf = collect_pad->buffer;
2174   collect_pad->buffer = NULL;
2175
2176   /* vorbis/theora headers are retrieved from caps and put in CodecPrivate */
2177   if (collect_pad->track->xiph_headers_to_skip > 0) {
2178     GST_LOG_OBJECT (collect_pad->collect.pad, "dropping streamheader buffer");
2179     gst_buffer_unref (buf);
2180     --collect_pad->track->xiph_headers_to_skip;
2181     return GST_FLOW_OK;
2182   }
2183
2184   /* for dirac we have to queue up everything up to a picture unit */
2185   if (collect_pad->track->codec_id != NULL &&
2186       strcmp (collect_pad->track->codec_id,
2187           GST_MATROSKA_CODEC_ID_VIDEO_DIRAC) == 0) {
2188     buf = gst_matroska_mux_handle_dirac_packet (mux, collect_pad, buf);
2189     if (!buf)
2190       return GST_FLOW_OK;
2191   }
2192
2193   /* hm, invalid timestamp (due to --to be fixed--- element upstream);
2194    * this would wreak havoc with time stored in matroska file */
2195   /* TODO: maybe calculate a timestamp by using the previous timestamp
2196    * and default duration */
2197   if (!GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2198     GST_WARNING_OBJECT (collect_pad->collect.pad,
2199         "Invalid buffer timestamp; dropping buffer");
2200     gst_buffer_unref (buf);
2201     return GST_FLOW_OK;
2202   }
2203
2204   /* set the timestamp for outgoing buffers */
2205   ebml->timestamp = GST_BUFFER_TIMESTAMP (buf);
2206
2207   if (collect_pad->track->type == GST_MATROSKA_TRACK_TYPE_VIDEO &&
2208       !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2209     GST_LOG_OBJECT (mux, "have video keyframe, ts=%" GST_TIME_FORMAT,
2210         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2211     is_video_keyframe = TRUE;
2212   }
2213
2214   if (mux->cluster) {
2215     /* start a new cluster every two seconds or at keyframe */
2216     if (mux->cluster_time + GST_SECOND * 2 < GST_BUFFER_TIMESTAMP (buf)
2217         || is_video_keyframe) {
2218
2219       gst_ebml_write_master_finish (ebml, mux->cluster);
2220       mux->cluster_pos = ebml->pos;
2221       mux->cluster =
2222           gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_CLUSTER);
2223       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CLUSTERTIMECODE,
2224           GST_BUFFER_TIMESTAMP (buf) / mux->time_scale);
2225       mux->cluster_time = GST_BUFFER_TIMESTAMP (buf);
2226     }
2227   } else {
2228     /* first cluster */
2229
2230     mux->cluster_pos = ebml->pos;
2231     mux->cluster = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_CLUSTER);
2232     gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CLUSTERTIMECODE,
2233         GST_BUFFER_TIMESTAMP (buf) / mux->time_scale);
2234     mux->cluster_time = GST_BUFFER_TIMESTAMP (buf);
2235   }
2236   cluster = mux->cluster;
2237
2238   /* update duration of this track */
2239   if (GST_BUFFER_DURATION_IS_VALID (buf))
2240     collect_pad->duration += GST_BUFFER_DURATION (buf);
2241
2242   /* We currently write an index entry for each keyframe in a
2243    * video track or one entry for each cluster in an audio track
2244    * for audio only files. This can be largely improved, such as doing
2245    * one for each keyframe or each second (for all-keyframe
2246    * streams), only the *first* video track. But that'll come later... */
2247
2248   /* TODO: index is useful for every track, should contain the number of
2249    * the block in the cluster which contains the timestamp
2250    */
2251   if (is_video_keyframe) {
2252     GstMatroskaIndex *idx;
2253
2254     if (mux->num_indexes % 32 == 0) {
2255       mux->index = g_renew (GstMatroskaIndex, mux->index,
2256           mux->num_indexes + 32);
2257     }
2258     idx = &mux->index[mux->num_indexes++];
2259
2260     idx->pos = mux->cluster_pos;
2261     idx->time = GST_BUFFER_TIMESTAMP (buf);
2262     idx->track = collect_pad->track->num;
2263   } else if ((collect_pad->track->type == GST_MATROSKA_TRACK_TYPE_AUDIO) &&
2264       (mux->num_streams == 1)) {
2265     GstMatroskaIndex *idx;
2266
2267     if (mux->num_indexes % 32 == 0) {
2268       mux->index = g_renew (GstMatroskaIndex, mux->index,
2269           mux->num_indexes + 32);
2270     }
2271     idx = &mux->index[mux->num_indexes++];
2272
2273     idx->pos = mux->cluster_pos;
2274     idx->time = GST_BUFFER_TIMESTAMP (buf);
2275     idx->track = collect_pad->track->num;
2276   }
2277
2278   /* Check if the duration differs from the default duration. */
2279   write_duration = FALSE;
2280   block_duration = GST_BUFFER_DURATION (buf);
2281   if (GST_BUFFER_DURATION_IS_VALID (buf)) {
2282     if (block_duration != collect_pad->track->default_duration) {
2283       write_duration = TRUE;
2284     }
2285   }
2286
2287   /* write the block, for matroska v2 use SimpleBlock if possible
2288    * one slice (*breath*).
2289    * FIXME: Need to do correct lacing! */
2290   relative_timestamp64 = GST_BUFFER_TIMESTAMP (buf) - mux->cluster_time;
2291   if (relative_timestamp64 >= 0) {
2292     /* round the timestamp */
2293     relative_timestamp64 += mux->time_scale / 2;
2294   } else {
2295     /* round the timestamp */
2296     relative_timestamp64 -= mux->time_scale / 2;
2297   }
2298   relative_timestamp = relative_timestamp64 / (gint64) mux->time_scale;
2299   if (mux->matroska_version > 1 && !write_duration) {
2300     int flags =
2301         GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT) ? 0 : 0x80;
2302
2303     hdr =
2304         gst_matroska_mux_create_buffer_header (collect_pad->track,
2305         relative_timestamp, flags);
2306     gst_ebml_write_buffer_header (ebml, GST_MATROSKA_ID_SIMPLEBLOCK,
2307         GST_BUFFER_SIZE (buf) + GST_BUFFER_SIZE (hdr));
2308     gst_ebml_write_buffer (ebml, hdr);
2309     gst_ebml_write_buffer (ebml, buf);
2310
2311     return gst_ebml_last_write_result (ebml);
2312   } else {
2313     blockgroup = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_BLOCKGROUP);
2314     hdr =
2315         gst_matroska_mux_create_buffer_header (collect_pad->track,
2316         relative_timestamp, 0);
2317     gst_ebml_write_buffer_header (ebml, GST_MATROSKA_ID_BLOCK,
2318         GST_BUFFER_SIZE (buf) + GST_BUFFER_SIZE (hdr));
2319     gst_ebml_write_buffer (ebml, hdr);
2320     gst_ebml_write_buffer (ebml, buf);
2321     if (write_duration) {
2322       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_BLOCKDURATION,
2323           block_duration / mux->time_scale);
2324     }
2325     gst_ebml_write_master_finish (ebml, blockgroup);
2326     return gst_ebml_last_write_result (ebml);
2327   }
2328 }
2329
2330
2331 /**
2332  * gst_matroska_mux_collected:
2333  * @pads: #GstCollectPads
2334  * @uuser_data: #GstMatroskaMux
2335  *
2336  * Collectpads callback.
2337  *
2338  * Returns: #GstFlowReturn
2339  */
2340 static GstFlowReturn
2341 gst_matroska_mux_collected (GstCollectPads * pads, gpointer user_data)
2342 {
2343   GstMatroskaMux *mux = GST_MATROSKA_MUX (user_data);
2344   GstMatroskaPad *best;
2345   gboolean popped;
2346   GstFlowReturn ret;
2347
2348   GST_DEBUG_OBJECT (mux, "Collected pads");
2349
2350   /* start with a header */
2351   if (mux->state == GST_MATROSKA_MUX_STATE_START) {
2352     if (mux->collect->data == NULL) {
2353       GST_ELEMENT_ERROR (mux, STREAM, MUX, (NULL),
2354           ("No input streams configured"));
2355       return GST_FLOW_ERROR;
2356     }
2357     mux->state = GST_MATROSKA_MUX_STATE_HEADER;
2358     gst_matroska_mux_start (mux);
2359     mux->state = GST_MATROSKA_MUX_STATE_DATA;
2360   }
2361
2362   do {
2363     /* which stream to write from? */
2364     best = gst_matroska_mux_best_pad (mux, &popped);
2365
2366     /* if there is no best pad, we have reached EOS */
2367     if (best == NULL) {
2368       GST_DEBUG_OBJECT (mux, "No best pad finishing...");
2369       gst_matroska_mux_finish (mux);
2370       gst_pad_push_event (mux->srcpad, gst_event_new_eos ());
2371       ret = GST_FLOW_UNEXPECTED;
2372       break;
2373     }
2374     GST_DEBUG_OBJECT (best->collect.pad, "best pad - buffer ts %"
2375         GST_TIME_FORMAT " dur %" GST_TIME_FORMAT,
2376         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (best->buffer)),
2377         GST_TIME_ARGS (GST_BUFFER_DURATION (best->buffer)));
2378
2379     /* make note of first and last encountered timestamps, so we can calculate
2380      * the actual duration later when we send an updated header on eos */
2381     if (GST_BUFFER_TIMESTAMP_IS_VALID (best->buffer)) {
2382       GstClockTime start_ts = GST_BUFFER_TIMESTAMP (best->buffer);
2383       GstClockTime end_ts = start_ts;
2384
2385       if (GST_BUFFER_DURATION_IS_VALID (best->buffer))
2386         end_ts += GST_BUFFER_DURATION (best->buffer);
2387       else if (best->track->default_duration)
2388         end_ts += best->track->default_duration;
2389
2390       if (!GST_CLOCK_TIME_IS_VALID (best->end_ts) || end_ts > best->end_ts)
2391         best->end_ts = end_ts;
2392
2393       if (G_UNLIKELY (best->start_ts == GST_CLOCK_TIME_NONE ||
2394               start_ts < best->start_ts))
2395         best->start_ts = start_ts;
2396     }
2397
2398     /* write one buffer */
2399     ret = gst_matroska_mux_write_data (mux, best);
2400   } while (ret == GST_FLOW_OK && !popped);
2401
2402   return ret;
2403 }
2404
2405
2406 /**
2407  * gst_matroska_mux_change_state:
2408  * @element: #GstMatroskaMux
2409  * @transition: State change transition.
2410  *
2411  * Change the muxer state.
2412  *
2413  * Returns: #GstStateChangeReturn
2414  */
2415 static GstStateChangeReturn
2416 gst_matroska_mux_change_state (GstElement * element, GstStateChange transition)
2417 {
2418   GstStateChangeReturn ret;
2419   GstMatroskaMux *mux = GST_MATROSKA_MUX (element);
2420
2421   switch (transition) {
2422     case GST_STATE_CHANGE_NULL_TO_READY:
2423       break;
2424     case GST_STATE_CHANGE_READY_TO_PAUSED:
2425       gst_collect_pads_start (mux->collect);
2426       break;
2427     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2428       break;
2429     case GST_STATE_CHANGE_PAUSED_TO_READY:
2430       gst_collect_pads_stop (mux->collect);
2431       break;
2432     default:
2433       break;
2434   }
2435
2436   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2437
2438   switch (transition) {
2439     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2440       break;
2441     case GST_STATE_CHANGE_PAUSED_TO_READY:
2442       gst_matroska_mux_reset (GST_ELEMENT (mux));
2443       break;
2444     case GST_STATE_CHANGE_READY_TO_NULL:
2445       break;
2446     default:
2447       break;
2448   }
2449
2450   return ret;
2451 }
2452
2453 static void
2454 gst_matroska_mux_set_property (GObject * object,
2455     guint prop_id, const GValue * value, GParamSpec * pspec)
2456 {
2457   GstMatroskaMux *mux;
2458
2459   g_return_if_fail (GST_IS_MATROSKA_MUX (object));
2460   mux = GST_MATROSKA_MUX (object);
2461
2462   switch (prop_id) {
2463     case ARG_WRITING_APP:
2464       if (!g_value_get_string (value)) {
2465         GST_WARNING_OBJECT (mux, "writing-app property can not be NULL");
2466         break;
2467       }
2468       g_free (mux->writing_app);
2469       mux->writing_app = g_value_dup_string (value);
2470       break;
2471     case ARG_MATROSKA_VERSION:
2472       mux->matroska_version = g_value_get_int (value);
2473       break;
2474     default:
2475       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2476       break;
2477   }
2478 }
2479
2480 static void
2481 gst_matroska_mux_get_property (GObject * object,
2482     guint prop_id, GValue * value, GParamSpec * pspec)
2483 {
2484   GstMatroskaMux *mux;
2485
2486   g_return_if_fail (GST_IS_MATROSKA_MUX (object));
2487   mux = GST_MATROSKA_MUX (object);
2488
2489   switch (prop_id) {
2490     case ARG_WRITING_APP:
2491       g_value_set_string (value, mux->writing_app);
2492       break;
2493     case ARG_MATROSKA_VERSION:
2494       g_value_set_int (value, mux->matroska_version);
2495       break;
2496     default:
2497       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2498       break;
2499   }
2500 }
2501
2502 gboolean
2503 gst_matroska_mux_plugin_init (GstPlugin * plugin)
2504 {
2505   return gst_element_register (plugin, "matroskamux",
2506       GST_RANK_NONE, GST_TYPE_MATROSKA_MUX);
2507 }