matroska: init endianess as such and signedness as boolean.
[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       } else {
1850         GST_WARNING ("Can't transform tag '%s' to string", tagname_mkv);
1851       }
1852       g_value_unset (&src);
1853       break;
1854     }
1855   }
1856 }
1857
1858
1859 /**
1860  * gst_matroska_mux_finish:
1861  * @mux: #GstMatroskaMux
1862  *
1863  * Finish a new matroska file (write index etc...)
1864  */
1865 static void
1866 gst_matroska_mux_finish (GstMatroskaMux * mux)
1867 {
1868   GstEbmlWrite *ebml = mux->ebml_write;
1869   guint64 pos;
1870   guint64 duration = 0;
1871   GSList *collected;
1872   const GstTagList *tags;
1873
1874   /* finish last cluster */
1875   if (mux->cluster) {
1876     gst_ebml_write_master_finish (ebml, mux->cluster);
1877   }
1878
1879   /* cues */
1880   if (mux->index != NULL) {
1881     guint n;
1882     guint64 master, pointentry_master, trackpos_master;
1883
1884     mux->cues_pos = ebml->pos;
1885     gst_ebml_write_set_cache (ebml, 12 + 41 * mux->num_indexes);
1886     master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_CUES);
1887
1888     for (n = 0; n < mux->num_indexes; n++) {
1889       GstMatroskaIndex *idx = &mux->index[n];
1890
1891       pointentry_master = gst_ebml_write_master_start (ebml,
1892           GST_MATROSKA_ID_POINTENTRY);
1893       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CUETIME,
1894           idx->time / mux->time_scale);
1895       trackpos_master = gst_ebml_write_master_start (ebml,
1896           GST_MATROSKA_ID_CUETRACKPOSITIONS);
1897       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CUETRACK, idx->track);
1898       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CUECLUSTERPOSITION,
1899           idx->pos - mux->segment_master);
1900       gst_ebml_write_master_finish (ebml, trackpos_master);
1901       gst_ebml_write_master_finish (ebml, pointentry_master);
1902     }
1903
1904     gst_ebml_write_master_finish (ebml, master);
1905     gst_ebml_write_flush_cache (ebml);
1906   }
1907
1908   /* tags */
1909   tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (mux));
1910
1911   if (tags != NULL && !gst_tag_list_is_empty (tags)) {
1912     guint64 master_tags, master_tag;
1913
1914     GST_DEBUG ("Writing tags");
1915
1916     /* TODO: maybe limit via the TARGETS id by looking at the source pad */
1917     mux->tags_pos = ebml->pos;
1918     master_tags = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TAGS);
1919     master_tag = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TAG);
1920     gst_tag_list_foreach (tags, gst_matroska_mux_write_simple_tag, ebml);
1921     gst_ebml_write_master_finish (ebml, master_tag);
1922     gst_ebml_write_master_finish (ebml, master_tags);
1923   }
1924
1925   /* update seekhead. We know that:
1926    * - a seekhead contains 4 entries.
1927    * - order of entries is as above.
1928    * - a seekhead has a 4-byte header + 8-byte length
1929    * - each entry is 2-byte master, 2-byte ID pointer,
1930    *     2-byte length pointer, all 8/1-byte length, 4-
1931    *     byte ID and 8-byte length pointer, where the
1932    *     length pointer starts at 20.
1933    * - all entries are local to the segment (so pos - segment_master).
1934    * - so each entry is at 12 + 20 + num * 28. */
1935   gst_ebml_replace_uint (ebml, mux->seekhead_pos + 32,
1936       mux->info_pos - mux->segment_master);
1937   gst_ebml_replace_uint (ebml, mux->seekhead_pos + 60,
1938       mux->tracks_pos - mux->segment_master);
1939   if (mux->index != NULL) {
1940     gst_ebml_replace_uint (ebml, mux->seekhead_pos + 88,
1941         mux->cues_pos - mux->segment_master);
1942   } else {
1943     /* void'ify */
1944     guint64 my_pos = ebml->pos;
1945
1946     gst_ebml_write_seek (ebml, mux->seekhead_pos + 68);
1947     gst_ebml_write_buffer_header (ebml, GST_EBML_ID_VOID, 26);
1948     gst_ebml_write_seek (ebml, my_pos);
1949   }
1950   if (tags != NULL) {
1951     gst_ebml_replace_uint (ebml, mux->seekhead_pos + 116,
1952         mux->tags_pos - mux->segment_master);
1953   } else {
1954     /* void'ify */
1955     guint64 my_pos = ebml->pos;
1956
1957     gst_ebml_write_seek (ebml, mux->seekhead_pos + 96);
1958     gst_ebml_write_buffer_header (ebml, GST_EBML_ID_VOID, 26);
1959     gst_ebml_write_seek (ebml, my_pos);
1960   }
1961
1962   /* update duration */
1963   /* first get the overall duration */
1964   /* a released track may have left a duration in here */
1965   duration = mux->duration;
1966   for (collected = mux->collect->data; collected;
1967       collected = g_slist_next (collected)) {
1968     GstMatroskaPad *collect_pad;
1969     GstClockTime min_duration;  /* observed minimum duration */
1970
1971     collect_pad = (GstMatroskaPad *) collected->data;
1972
1973     GST_DEBUG_OBJECT (mux, "Pad %" GST_PTR_FORMAT " start ts %" GST_TIME_FORMAT
1974         " end ts %" GST_TIME_FORMAT, collect_pad,
1975         GST_TIME_ARGS (collect_pad->start_ts),
1976         GST_TIME_ARGS (collect_pad->end_ts));
1977
1978     if (GST_CLOCK_TIME_IS_VALID (collect_pad->start_ts) &&
1979         GST_CLOCK_TIME_IS_VALID (collect_pad->end_ts)) {
1980       min_duration =
1981           GST_CLOCK_DIFF (collect_pad->start_ts, collect_pad->end_ts);
1982       if (collect_pad->duration < min_duration)
1983         collect_pad->duration = min_duration;
1984       GST_DEBUG_OBJECT (collect_pad, "final track duration: %" GST_TIME_FORMAT,
1985           GST_TIME_ARGS (collect_pad->duration));
1986     }
1987
1988     if (GST_CLOCK_TIME_IS_VALID (collect_pad->duration) &&
1989         duration < collect_pad->duration)
1990       duration = collect_pad->duration;
1991   }
1992   if (duration != 0) {
1993     GST_DEBUG_OBJECT (mux, "final total duration: %" GST_TIME_FORMAT,
1994         GST_TIME_ARGS (duration));
1995     pos = mux->ebml_write->pos;
1996     gst_ebml_write_seek (ebml, mux->duration_pos);
1997     gst_ebml_write_float (ebml, GST_MATROSKA_ID_DURATION,
1998         gst_guint64_to_gdouble (duration) /
1999         gst_guint64_to_gdouble (mux->time_scale));
2000     gst_ebml_write_seek (ebml, pos);
2001   } else {
2002     /* void'ify */
2003     guint64 my_pos = ebml->pos;
2004
2005     gst_ebml_write_seek (ebml, mux->duration_pos);
2006     gst_ebml_write_buffer_header (ebml, GST_EBML_ID_VOID, 8);
2007     gst_ebml_write_seek (ebml, my_pos);
2008   }
2009
2010   /* finish segment - this also writes element length */
2011   gst_ebml_write_master_finish (ebml, mux->segment_pos);
2012 }
2013
2014
2015 /**
2016  * gst_matroska_mux_best_pad:
2017  * @mux: #GstMatroskaMux
2018  * @popped: True if at least one buffer was popped from #GstCollectPads
2019  *
2020  * Find a pad with the oldest data 
2021  * (data from this pad should be written first).
2022  *
2023  * Returns: Selected pad.
2024  */
2025 static GstMatroskaPad *
2026 gst_matroska_mux_best_pad (GstMatroskaMux * mux, gboolean * popped)
2027 {
2028   GSList *collected;
2029   GstMatroskaPad *best = NULL;
2030
2031   *popped = FALSE;
2032   for (collected = mux->collect->data; collected;
2033       collected = g_slist_next (collected)) {
2034     GstMatroskaPad *collect_pad;
2035
2036     collect_pad = (GstMatroskaPad *) collected->data;
2037     /* fetch a new buffer if needed */
2038     if (collect_pad->buffer == NULL) {
2039       collect_pad->buffer = gst_collect_pads_pop (mux->collect,
2040           (GstCollectData *) collect_pad);
2041
2042       if (collect_pad->buffer != NULL)
2043         *popped = TRUE;
2044     }
2045
2046     /* if we have a buffer check if it is better then the current best one */
2047     if (collect_pad->buffer != NULL) {
2048       if (best == NULL || !GST_BUFFER_TIMESTAMP_IS_VALID (collect_pad->buffer)
2049           || (GST_BUFFER_TIMESTAMP_IS_VALID (best->buffer)
2050               && GST_BUFFER_TIMESTAMP (collect_pad->buffer) <
2051               GST_BUFFER_TIMESTAMP (best->buffer))) {
2052         best = collect_pad;
2053       }
2054     }
2055   }
2056
2057   return best;
2058 }
2059
2060 /**
2061  * gst_matroska_mux_buffer_header:
2062  * @track: Track context.
2063  * @relative_timestamp: relative timestamp of the buffer
2064  * @flags: Buffer flags.
2065  *
2066  * Create a buffer containing buffer header.
2067  * 
2068  * Returns: New buffer.
2069  */
2070 GstBuffer *
2071 gst_matroska_mux_create_buffer_header (GstMatroskaTrackContext * track,
2072     gint16 relative_timestamp, int flags)
2073 {
2074   GstBuffer *hdr;
2075
2076   hdr = gst_buffer_new_and_alloc (4);
2077   /* track num - FIXME: what if num >= 0x80 (unlikely)? */
2078   GST_BUFFER_DATA (hdr)[0] = track->num | 0x80;
2079   /* time relative to clustertime */
2080   GST_WRITE_UINT16_BE (GST_BUFFER_DATA (hdr) + 1, relative_timestamp);
2081
2082   /* flags */
2083   GST_BUFFER_DATA (hdr)[3] = flags;
2084
2085   return hdr;
2086 }
2087
2088 static GstBuffer *
2089 gst_matroska_mux_handle_dirac_packet (GstMatroskaMux * mux,
2090     GstMatroskaPad * collect_pad, GstBuffer * buf)
2091 {
2092   GstMatroskaTrackVideoContext *ctx =
2093       (GstMatroskaTrackVideoContext *) collect_pad->track;
2094   const guint8 *data = GST_BUFFER_DATA (buf);
2095   guint size = GST_BUFFER_SIZE (buf);
2096   guint8 parse_code;
2097   guint32 next_parse_offset;
2098   GstBuffer *ret = NULL;
2099   gboolean is_picture = FALSE;
2100
2101   if (GST_BUFFER_SIZE (buf) < 13) {
2102     gst_buffer_unref (buf);
2103     return ret;
2104   }
2105
2106   /* Check if this buffer contains a picture packet */
2107   while (size >= 13) {
2108     if (GST_READ_UINT32_BE (data) != 0x42424344) {
2109       gst_buffer_unref (buf);
2110       return ret;
2111     }
2112
2113     parse_code = GST_READ_UINT8 (data + 4);
2114     if (parse_code == 0x00) {
2115       if (ctx->dirac_unit) {
2116         gst_buffer_unref (ctx->dirac_unit);
2117         ctx->dirac_unit = NULL;
2118       }
2119     } else if (parse_code & 0x08) {
2120       is_picture = TRUE;
2121       break;
2122     }
2123
2124     next_parse_offset = GST_READ_UINT32_BE (data + 5);
2125
2126     data += next_parse_offset;
2127     size -= next_parse_offset;
2128   }
2129
2130   if (ctx->dirac_unit)
2131     ctx->dirac_unit = gst_buffer_join (ctx->dirac_unit, gst_buffer_ref (buf));
2132   else
2133     ctx->dirac_unit = gst_buffer_ref (buf);
2134
2135   if (is_picture) {
2136     ret = gst_buffer_make_metadata_writable (ctx->dirac_unit);
2137     ctx->dirac_unit = NULL;
2138     gst_buffer_copy_metadata (ret, buf,
2139         GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS |
2140         GST_BUFFER_COPY_CAPS);
2141     gst_buffer_unref (buf);
2142   } else {
2143     gst_buffer_unref (buf);
2144     ret = NULL;
2145   }
2146
2147   return ret;
2148 }
2149
2150 /**
2151  * gst_matroska_mux_write_data:
2152  * @mux: #GstMatroskaMux
2153  * @collect_pad: #GstMatroskaPad with the data
2154  *
2155  * Write collected data (called from gst_matroska_mux_collected).
2156  *
2157  * Returns: Result of the gst_pad_push issued to write the data.
2158  */
2159 static GstFlowReturn
2160 gst_matroska_mux_write_data (GstMatroskaMux * mux, GstMatroskaPad * collect_pad)
2161 {
2162   GstEbmlWrite *ebml = mux->ebml_write;
2163   GstBuffer *buf, *hdr;
2164   guint64 cluster, blockgroup;
2165   gboolean write_duration;
2166   gint16 relative_timestamp;
2167   gint64 relative_timestamp64;
2168   guint64 block_duration;
2169   gboolean is_video_keyframe = FALSE;
2170
2171   /* write data */
2172   buf = collect_pad->buffer;
2173   collect_pad->buffer = NULL;
2174
2175   /* vorbis/theora headers are retrieved from caps and put in CodecPrivate */
2176   if (collect_pad->track->xiph_headers_to_skip > 0) {
2177     GST_LOG_OBJECT (collect_pad->collect.pad, "dropping streamheader buffer");
2178     gst_buffer_unref (buf);
2179     --collect_pad->track->xiph_headers_to_skip;
2180     return GST_FLOW_OK;
2181   }
2182
2183   /* for dirac we have to queue up everything up to a picture unit */
2184   if (collect_pad->track->codec_id != NULL &&
2185       strcmp (collect_pad->track->codec_id,
2186           GST_MATROSKA_CODEC_ID_VIDEO_DIRAC) == 0) {
2187     buf = gst_matroska_mux_handle_dirac_packet (mux, collect_pad, buf);
2188     if (!buf)
2189       return GST_FLOW_OK;
2190   }
2191
2192   /* hm, invalid timestamp (due to --to be fixed--- element upstream);
2193    * this would wreak havoc with time stored in matroska file */
2194   /* TODO: maybe calculate a timestamp by using the previous timestamp
2195    * and default duration */
2196   if (!GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2197     GST_WARNING_OBJECT (collect_pad->collect.pad,
2198         "Invalid buffer timestamp; dropping buffer");
2199     gst_buffer_unref (buf);
2200     return GST_FLOW_OK;
2201   }
2202
2203   /* set the timestamp for outgoing buffers */
2204   ebml->timestamp = GST_BUFFER_TIMESTAMP (buf);
2205
2206   if (collect_pad->track->type == GST_MATROSKA_TRACK_TYPE_VIDEO &&
2207       !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2208     GST_LOG_OBJECT (mux, "have video keyframe, ts=%" GST_TIME_FORMAT,
2209         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2210     is_video_keyframe = TRUE;
2211   }
2212
2213   if (mux->cluster) {
2214     /* start a new cluster every two seconds or at keyframe */
2215     if (mux->cluster_time + GST_SECOND * 2 < GST_BUFFER_TIMESTAMP (buf)
2216         || is_video_keyframe) {
2217
2218       gst_ebml_write_master_finish (ebml, mux->cluster);
2219       mux->cluster_pos = ebml->pos;
2220       mux->cluster =
2221           gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_CLUSTER);
2222       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CLUSTERTIMECODE,
2223           GST_BUFFER_TIMESTAMP (buf) / mux->time_scale);
2224       mux->cluster_time = GST_BUFFER_TIMESTAMP (buf);
2225     }
2226   } else {
2227     /* first cluster */
2228
2229     mux->cluster_pos = ebml->pos;
2230     mux->cluster = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_CLUSTER);
2231     gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CLUSTERTIMECODE,
2232         GST_BUFFER_TIMESTAMP (buf) / mux->time_scale);
2233     mux->cluster_time = GST_BUFFER_TIMESTAMP (buf);
2234   }
2235   cluster = mux->cluster;
2236
2237   /* update duration of this track */
2238   if (GST_BUFFER_DURATION_IS_VALID (buf))
2239     collect_pad->duration += GST_BUFFER_DURATION (buf);
2240
2241   /* We currently write an index entry for each keyframe in a
2242    * video track or one entry for each cluster in an audio track
2243    * for audio only files. This can be largely improved, such as doing
2244    * one for each keyframe or each second (for all-keyframe
2245    * streams), only the *first* video track. But that'll come later... */
2246
2247   /* TODO: index is useful for every track, should contain the number of
2248    * the block in the cluster which contains the timestamp
2249    */
2250   if (is_video_keyframe) {
2251     GstMatroskaIndex *idx;
2252
2253     if (mux->num_indexes % 32 == 0) {
2254       mux->index = g_renew (GstMatroskaIndex, mux->index,
2255           mux->num_indexes + 32);
2256     }
2257     idx = &mux->index[mux->num_indexes++];
2258
2259     idx->pos = mux->cluster_pos;
2260     idx->time = GST_BUFFER_TIMESTAMP (buf);
2261     idx->track = collect_pad->track->num;
2262   } else if ((collect_pad->track->type == GST_MATROSKA_TRACK_TYPE_AUDIO) &&
2263       (mux->num_streams == 1)) {
2264     GstMatroskaIndex *idx;
2265
2266     if (mux->num_indexes % 32 == 0) {
2267       mux->index = g_renew (GstMatroskaIndex, mux->index,
2268           mux->num_indexes + 32);
2269     }
2270     idx = &mux->index[mux->num_indexes++];
2271
2272     idx->pos = mux->cluster_pos;
2273     idx->time = GST_BUFFER_TIMESTAMP (buf);
2274     idx->track = collect_pad->track->num;
2275   }
2276
2277   /* Check if the duration differs from the default duration. */
2278   write_duration = FALSE;
2279   block_duration = GST_BUFFER_DURATION (buf);
2280   if (GST_BUFFER_DURATION_IS_VALID (buf)) {
2281     if (block_duration != collect_pad->track->default_duration) {
2282       write_duration = TRUE;
2283     }
2284   }
2285
2286   /* write the block, for matroska v2 use SimpleBlock if possible
2287    * one slice (*breath*).
2288    * FIXME: Need to do correct lacing! */
2289   relative_timestamp64 = GST_BUFFER_TIMESTAMP (buf) - mux->cluster_time;
2290   if (relative_timestamp64 >= 0) {
2291     /* round the timestamp */
2292     relative_timestamp64 += mux->time_scale / 2;
2293   } else {
2294     /* round the timestamp */
2295     relative_timestamp64 -= mux->time_scale / 2;
2296   }
2297   relative_timestamp = relative_timestamp64 / (gint64) mux->time_scale;
2298   if (mux->matroska_version > 1 && !write_duration) {
2299     int flags =
2300         GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT) ? 0 : 0x80;
2301
2302     hdr =
2303         gst_matroska_mux_create_buffer_header (collect_pad->track,
2304         relative_timestamp, flags);
2305     gst_ebml_write_buffer_header (ebml, GST_MATROSKA_ID_SIMPLEBLOCK,
2306         GST_BUFFER_SIZE (buf) + GST_BUFFER_SIZE (hdr));
2307     gst_ebml_write_buffer (ebml, hdr);
2308     gst_ebml_write_buffer (ebml, buf);
2309
2310     return gst_ebml_last_write_result (ebml);
2311   } else {
2312     blockgroup = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_BLOCKGROUP);
2313     hdr =
2314         gst_matroska_mux_create_buffer_header (collect_pad->track,
2315         relative_timestamp, 0);
2316     gst_ebml_write_buffer_header (ebml, GST_MATROSKA_ID_BLOCK,
2317         GST_BUFFER_SIZE (buf) + GST_BUFFER_SIZE (hdr));
2318     gst_ebml_write_buffer (ebml, hdr);
2319     gst_ebml_write_buffer (ebml, buf);
2320     if (write_duration) {
2321       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_BLOCKDURATION,
2322           block_duration / mux->time_scale);
2323     }
2324     gst_ebml_write_master_finish (ebml, blockgroup);
2325     return gst_ebml_last_write_result (ebml);
2326   }
2327 }
2328
2329
2330 /**
2331  * gst_matroska_mux_collected:
2332  * @pads: #GstCollectPads
2333  * @uuser_data: #GstMatroskaMux
2334  *
2335  * Collectpads callback.
2336  *
2337  * Returns: #GstFlowReturn
2338  */
2339 static GstFlowReturn
2340 gst_matroska_mux_collected (GstCollectPads * pads, gpointer user_data)
2341 {
2342   GstMatroskaMux *mux = GST_MATROSKA_MUX (user_data);
2343   GstMatroskaPad *best;
2344   gboolean popped;
2345   GstFlowReturn ret;
2346
2347   GST_DEBUG_OBJECT (mux, "Collected pads");
2348
2349   /* start with a header */
2350   if (mux->state == GST_MATROSKA_MUX_STATE_START) {
2351     if (mux->collect->data == NULL) {
2352       GST_ELEMENT_ERROR (mux, STREAM, MUX, (NULL),
2353           ("No input streams configured"));
2354       return GST_FLOW_ERROR;
2355     }
2356     mux->state = GST_MATROSKA_MUX_STATE_HEADER;
2357     gst_matroska_mux_start (mux);
2358     mux->state = GST_MATROSKA_MUX_STATE_DATA;
2359   }
2360
2361   do {
2362     /* which stream to write from? */
2363     best = gst_matroska_mux_best_pad (mux, &popped);
2364
2365     /* if there is no best pad, we have reached EOS */
2366     if (best == NULL) {
2367       GST_DEBUG_OBJECT (mux, "No best pad finishing...");
2368       gst_matroska_mux_finish (mux);
2369       gst_pad_push_event (mux->srcpad, gst_event_new_eos ());
2370       ret = GST_FLOW_UNEXPECTED;
2371       break;
2372     }
2373     GST_DEBUG_OBJECT (best->collect.pad, "best pad - buffer ts %"
2374         GST_TIME_FORMAT " dur %" GST_TIME_FORMAT,
2375         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (best->buffer)),
2376         GST_TIME_ARGS (GST_BUFFER_DURATION (best->buffer)));
2377
2378     /* make note of first and last encountered timestamps, so we can calculate
2379      * the actual duration later when we send an updated header on eos */
2380     if (GST_BUFFER_TIMESTAMP_IS_VALID (best->buffer)) {
2381       GstClockTime start_ts = GST_BUFFER_TIMESTAMP (best->buffer);
2382       GstClockTime end_ts = start_ts;
2383
2384       if (GST_BUFFER_DURATION_IS_VALID (best->buffer))
2385         end_ts += GST_BUFFER_DURATION (best->buffer);
2386       else if (best->track->default_duration)
2387         end_ts += best->track->default_duration;
2388
2389       if (!GST_CLOCK_TIME_IS_VALID (best->end_ts) || end_ts > best->end_ts)
2390         best->end_ts = end_ts;
2391
2392       if (G_UNLIKELY (best->start_ts == GST_CLOCK_TIME_NONE ||
2393               start_ts < best->start_ts))
2394         best->start_ts = start_ts;
2395     }
2396
2397     /* write one buffer */
2398     ret = gst_matroska_mux_write_data (mux, best);
2399   } while (ret == GST_FLOW_OK && !popped);
2400
2401   return ret;
2402 }
2403
2404
2405 /**
2406  * gst_matroska_mux_change_state:
2407  * @element: #GstMatroskaMux
2408  * @transition: State change transition.
2409  *
2410  * Change the muxer state.
2411  *
2412  * Returns: #GstStateChangeReturn
2413  */
2414 static GstStateChangeReturn
2415 gst_matroska_mux_change_state (GstElement * element, GstStateChange transition)
2416 {
2417   GstStateChangeReturn ret;
2418   GstMatroskaMux *mux = GST_MATROSKA_MUX (element);
2419
2420   switch (transition) {
2421     case GST_STATE_CHANGE_NULL_TO_READY:
2422       break;
2423     case GST_STATE_CHANGE_READY_TO_PAUSED:
2424       gst_collect_pads_start (mux->collect);
2425       break;
2426     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2427       break;
2428     case GST_STATE_CHANGE_PAUSED_TO_READY:
2429       gst_collect_pads_stop (mux->collect);
2430       break;
2431     default:
2432       break;
2433   }
2434
2435   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2436
2437   switch (transition) {
2438     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2439       break;
2440     case GST_STATE_CHANGE_PAUSED_TO_READY:
2441       gst_matroska_mux_reset (GST_ELEMENT (mux));
2442       break;
2443     case GST_STATE_CHANGE_READY_TO_NULL:
2444       break;
2445     default:
2446       break;
2447   }
2448
2449   return ret;
2450 }
2451
2452 static void
2453 gst_matroska_mux_set_property (GObject * object,
2454     guint prop_id, const GValue * value, GParamSpec * pspec)
2455 {
2456   GstMatroskaMux *mux;
2457
2458   g_return_if_fail (GST_IS_MATROSKA_MUX (object));
2459   mux = GST_MATROSKA_MUX (object);
2460
2461   switch (prop_id) {
2462     case ARG_WRITING_APP:
2463       if (!g_value_get_string (value)) {
2464         GST_WARNING_OBJECT (mux, "writing-app property can not be NULL");
2465         break;
2466       }
2467       g_free (mux->writing_app);
2468       mux->writing_app = g_value_dup_string (value);
2469       break;
2470     case ARG_MATROSKA_VERSION:
2471       mux->matroska_version = g_value_get_int (value);
2472       break;
2473     default:
2474       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2475       break;
2476   }
2477 }
2478
2479 static void
2480 gst_matroska_mux_get_property (GObject * object,
2481     guint prop_id, GValue * value, GParamSpec * pspec)
2482 {
2483   GstMatroskaMux *mux;
2484
2485   g_return_if_fail (GST_IS_MATROSKA_MUX (object));
2486   mux = GST_MATROSKA_MUX (object);
2487
2488   switch (prop_id) {
2489     case ARG_WRITING_APP:
2490       g_value_set_string (value, mux->writing_app);
2491       break;
2492     case ARG_MATROSKA_VERSION:
2493       g_value_set_int (value, mux->matroska_version);
2494       break;
2495     default:
2496       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2497       break;
2498   }
2499 }
2500
2501 gboolean
2502 gst_matroska_mux_plugin_init (GstPlugin * plugin)
2503 {
2504   return gst_element_register (plugin, "matroskamux",
2505       GST_RANK_NONE, GST_TYPE_MATROSKA_MUX);
2506 }