Fix Forte compiler warnings.
[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     context->default_duration =
655         gst_util_uint64_scale_int (GST_SECOND, fps_d, fps_n);
656     GST_LOG_OBJECT (pad, "default duration = %" GST_TIME_FORMAT,
657         GST_TIME_ARGS (context->default_duration));
658   } else {
659     context->default_duration = 0;
660   }
661   if (gst_structure_get_fraction (structure, "pixel-aspect-ratio",
662           &pixel_width, &pixel_height)) {
663     if (pixel_width > pixel_height) {
664       videocontext->display_width = width * pixel_width / pixel_height;
665       videocontext->display_height = height;
666     } else if (pixel_width < pixel_height) {
667       videocontext->display_width = width;
668       videocontext->display_height = height * pixel_height / pixel_width;
669     } else {
670       videocontext->display_width = 0;
671       videocontext->display_height = 0;
672     }
673   } else {
674     videocontext->display_width = 0;
675     videocontext->display_height = 0;
676   }
677
678 skip_details:
679
680   videocontext->asr_mode = GST_MATROSKA_ASPECT_RATIO_MODE_FREE;
681   videocontext->fourcc = 0;
682
683   /* TODO: - check if we handle all codecs by the spec, i.e. codec private
684    *         data and other settings
685    *       - add new formats
686    */
687
688   /* extract codec_data, may turn out needed */
689   value = gst_structure_get_value (structure, "codec_data");
690   if (value)
691     codec_buf = gst_value_get_buffer (value);
692
693   /* find type */
694   if (!strcmp (mimetype, "video/x-raw-yuv")) {
695     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_UNCOMPRESSED);
696     gst_structure_get_fourcc (structure, "format", &videocontext->fourcc);
697
698     return TRUE;
699   } else if (!strcmp (mimetype, "image/jpeg")) {
700     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_MJPEG);
701
702     return TRUE;
703   } else if (!strcmp (mimetype, "video/x-xvid") /* MS/VfW compatibility cases */
704       ||!strcmp (mimetype, "video/x-huffyuv")
705       || !strcmp (mimetype, "video/x-divx")
706       || !strcmp (mimetype, "video/x-dv")
707       || !strcmp (mimetype, "video/x-h263")
708       || !strcmp (mimetype, "video/x-msmpeg")) {
709     BITMAPINFOHEADER *bih;
710     gint size = sizeof (BITMAPINFOHEADER);
711     guint32 fourcc = 0;
712
713     if (!strcmp (mimetype, "video/x-xvid"))
714       fourcc = GST_MAKE_FOURCC ('X', 'V', 'I', 'D');
715     else if (!strcmp (mimetype, "video/x-huffyuv"))
716       fourcc = GST_MAKE_FOURCC ('H', 'F', 'Y', 'U');
717     else if (!strcmp (mimetype, "video/x-dv"))
718       fourcc = GST_MAKE_FOURCC ('D', 'V', 'S', 'D');
719     else if (!strcmp (mimetype, "video/x-h263"))
720       fourcc = GST_MAKE_FOURCC ('H', '2', '6', '3');
721     else if (!strcmp (mimetype, "video/x-divx")) {
722       gint divxversion;
723
724       gst_structure_get_int (structure, "divxversion", &divxversion);
725       switch (divxversion) {
726         case 3:
727           fourcc = GST_MAKE_FOURCC ('D', 'I', 'V', '3');
728           break;
729         case 4:
730           fourcc = GST_MAKE_FOURCC ('D', 'I', 'V', 'X');
731           break;
732         case 5:
733           fourcc = GST_MAKE_FOURCC ('D', 'X', '5', '0');
734           break;
735       }
736     } else if (!strcmp (mimetype, "video/x-msmpeg")) {
737       gint msmpegversion;
738
739       gst_structure_get_int (structure, "msmpegversion", &msmpegversion);
740       switch (msmpegversion) {
741         case 41:
742           fourcc = GST_MAKE_FOURCC ('M', 'P', 'G', '4');
743           break;
744         case 42:
745           fourcc = GST_MAKE_FOURCC ('M', 'P', '4', '2');
746           break;
747         case 43:
748           goto msmpeg43;
749           break;
750       }
751     }
752
753     if (!fourcc)
754       return FALSE;
755
756     bih = g_new0 (BITMAPINFOHEADER, 1);
757     GST_WRITE_UINT32_LE (&bih->bi_size, size);
758     GST_WRITE_UINT32_LE (&bih->bi_width, videocontext->pixel_width);
759     GST_WRITE_UINT32_LE (&bih->bi_height, videocontext->pixel_height);
760     GST_WRITE_UINT32_LE (&bih->bi_compression, fourcc);
761     GST_WRITE_UINT16_LE (&bih->bi_planes, (guint16) 1);
762     GST_WRITE_UINT16_LE (&bih->bi_bit_count, (guint16) 24);
763     GST_WRITE_UINT32_LE (&bih->bi_size_image, videocontext->pixel_width *
764         videocontext->pixel_height * 3);
765
766     /* process codec private/initialization data, if any */
767     if (codec_buf) {
768       size += GST_BUFFER_SIZE (codec_buf);
769       bih = g_realloc (bih, size);
770       GST_WRITE_UINT32_LE (&bih->bi_size, size);
771       memcpy ((guint8 *) bih + sizeof (BITMAPINFOHEADER),
772           GST_BUFFER_DATA (codec_buf), GST_BUFFER_SIZE (codec_buf));
773     }
774
775     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC);
776     context->codec_priv = (gpointer) bih;
777     context->codec_priv_size = size;
778
779     return TRUE;
780   } else if (!strcmp (mimetype, "video/x-h264")) {
781     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_AVC);
782
783     if (context->codec_priv != NULL) {
784       g_free (context->codec_priv);
785       context->codec_priv = NULL;
786       context->codec_priv_size = 0;
787     }
788
789     /* Create avcC header */
790     if (codec_buf != NULL) {
791       context->codec_priv_size = GST_BUFFER_SIZE (codec_buf);
792       context->codec_priv = g_malloc0 (context->codec_priv_size);
793       memcpy (context->codec_priv, GST_BUFFER_DATA (codec_buf),
794           context->codec_priv_size);
795     }
796
797     return TRUE;
798   } else if (!strcmp (mimetype, "video/x-theora")) {
799     const GValue *streamheader;
800
801     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_THEORA);
802
803     if (context->codec_priv != NULL) {
804       g_free (context->codec_priv);
805       context->codec_priv = NULL;
806       context->codec_priv_size = 0;
807     }
808
809     streamheader = gst_structure_get_value (structure, "streamheader");
810     if (!theora_streamheader_to_codecdata (streamheader, context)) {
811       GST_ELEMENT_ERROR (mux, STREAM, MUX, (NULL),
812           ("theora stream headers missing or malformed"));
813       return FALSE;
814     }
815     return TRUE;
816   } else if (!strcmp (mimetype, "video/x-dirac")) {
817     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_DIRAC);
818
819     return TRUE;
820   } else if (!strcmp (mimetype, "video/mpeg")) {
821     gint mpegversion;
822
823     gst_structure_get_int (structure, "mpegversion", &mpegversion);
824     switch (mpegversion) {
825       case 1:
826         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_MPEG1);
827         break;
828       case 2:
829         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_MPEG2);
830         break;
831       case 4:
832         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_ASP);
833         break;
834       default:
835         return FALSE;
836     }
837
838     /* global headers may be in codec data */
839     if (codec_buf != NULL) {
840       context->codec_priv_size = GST_BUFFER_SIZE (codec_buf);
841       context->codec_priv = g_malloc0 (context->codec_priv_size);
842       memcpy (context->codec_priv, GST_BUFFER_DATA (codec_buf),
843           context->codec_priv_size);
844     }
845
846     return TRUE;
847   } else if (!strcmp (mimetype, "video/x-msmpeg")) {
848   msmpeg43:
849     /* can only make it here if preceding case verified it was version 3 */
850     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_MSMPEG4V3);
851
852     return TRUE;
853   } else if (!strcmp (mimetype, "video/x-pn-realvideo")) {
854     gint rmversion;
855     const GValue *mdpr_data;
856
857     gst_structure_get_int (structure, "rmversion", &rmversion);
858     switch (rmversion) {
859       case 1:
860         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO1);
861         break;
862       case 2:
863         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO2);
864         break;
865       case 3:
866         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO3);
867         break;
868       case 4:
869         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO4);
870         break;
871       default:
872         return FALSE;
873     }
874
875     mdpr_data = gst_structure_get_value (structure, "mdpr_data");
876     if (mdpr_data != NULL) {
877       guint8 *priv_data = NULL;
878       guint priv_data_size = 0;
879
880       GstBuffer *codec_data_buf = g_value_peek_pointer (mdpr_data);
881
882       priv_data_size = GST_BUFFER_SIZE (codec_data_buf);
883       priv_data = g_malloc0 (priv_data_size);
884
885       memcpy (priv_data, GST_BUFFER_DATA (codec_data_buf), priv_data_size);
886
887       context->codec_priv = priv_data;
888       context->codec_priv_size = priv_data_size;
889     }
890
891     return TRUE;
892   }
893
894   return FALSE;
895 }
896
897 static gboolean
898 xiph3_streamheader_to_codecdata (const GValue * streamheader,
899     GstMatroskaTrackContext * context, GstBuffer ** p_buf0)
900 {
901   GstBuffer *buf[3];
902   GArray *bufarr;
903   guint8 *priv_data;
904   guint i, offset, priv_data_size;
905
906   if (streamheader == NULL)
907     goto no_stream_headers;
908
909   if (G_VALUE_TYPE (streamheader) != GST_TYPE_ARRAY)
910     goto wrong_type;
911
912   bufarr = g_value_peek_pointer (streamheader);
913   if (bufarr->len != 3)
914     goto wrong_count;
915
916   context->xiph_headers_to_skip = bufarr->len;
917
918   for (i = 0; i < 3; i++) {
919     GValue *bufval = &g_array_index (bufarr, GValue, i);
920
921     if (G_VALUE_TYPE (bufval) != GST_TYPE_BUFFER)
922       goto wrong_content_type;
923
924     buf[i] = g_value_peek_pointer (bufval);
925   }
926
927   priv_data_size = 1;
928   priv_data_size += GST_BUFFER_SIZE (buf[0]) / 0xff + 1;
929   priv_data_size += GST_BUFFER_SIZE (buf[1]) / 0xff + 1;
930
931   for (i = 0; i < 3; ++i) {
932     priv_data_size += GST_BUFFER_SIZE (buf[i]);
933   }
934
935   priv_data = g_malloc0 (priv_data_size);
936
937   priv_data[0] = 2;
938   offset = 1;
939
940   for (i = 0; i < GST_BUFFER_SIZE (buf[0]) / 0xff; ++i) {
941     priv_data[offset++] = 0xff;
942   }
943   priv_data[offset++] = GST_BUFFER_SIZE (buf[0]) % 0xff;
944
945   for (i = 0; i < GST_BUFFER_SIZE (buf[1]) / 0xff; ++i) {
946     priv_data[offset++] = 0xff;
947   }
948   priv_data[offset++] = GST_BUFFER_SIZE (buf[1]) % 0xff;
949
950   for (i = 0; i < 3; ++i) {
951     memcpy (priv_data + offset, GST_BUFFER_DATA (buf[i]),
952         GST_BUFFER_SIZE (buf[i]));
953     offset += GST_BUFFER_SIZE (buf[i]);
954   }
955
956   context->codec_priv = priv_data;
957   context->codec_priv_size = priv_data_size;
958
959   if (p_buf0)
960     *p_buf0 = gst_buffer_ref (buf[0]);
961
962   return TRUE;
963
964 /* ERRORS */
965 no_stream_headers:
966   {
967     GST_WARNING ("required streamheaders missing in sink caps!");
968     return FALSE;
969   }
970 wrong_type:
971   {
972     GST_WARNING ("streamheaders are not a GST_TYPE_ARRAY, but a %s",
973         G_VALUE_TYPE_NAME (streamheader));
974     return FALSE;
975   }
976 wrong_count:
977   {
978     GST_WARNING ("got %u streamheaders, not 3 as expected", bufarr->len);
979     return FALSE;
980   }
981 wrong_content_type:
982   {
983     GST_WARNING ("streamheaders array does not contain GstBuffers");
984     return FALSE;
985   }
986 }
987
988 static gboolean
989 vorbis_streamheader_to_codecdata (const GValue * streamheader,
990     GstMatroskaTrackContext * context)
991 {
992   GstBuffer *buf0 = NULL;
993
994   if (!xiph3_streamheader_to_codecdata (streamheader, context, &buf0))
995     return FALSE;
996
997   if (buf0 == NULL || GST_BUFFER_SIZE (buf0) < 1 + 6 + 4) {
998     GST_WARNING ("First vorbis header too small, ignoring");
999   } else {
1000     if (memcmp (GST_BUFFER_DATA (buf0) + 1, "vorbis", 6) == 0) {
1001       GstMatroskaTrackAudioContext *audiocontext;
1002       guint8 *hdr;
1003
1004       hdr = GST_BUFFER_DATA (buf0) + 1 + 6 + 4;
1005       audiocontext = (GstMatroskaTrackAudioContext *) context;
1006       audiocontext->channels = GST_READ_UINT8 (hdr);
1007       audiocontext->samplerate = GST_READ_UINT32_LE (hdr + 1);
1008     }
1009   }
1010
1011   if (buf0)
1012     gst_buffer_unref (buf0);
1013
1014   return TRUE;
1015 }
1016
1017 static gboolean
1018 theora_streamheader_to_codecdata (const GValue * streamheader,
1019     GstMatroskaTrackContext * context)
1020 {
1021   GstBuffer *buf0 = NULL;
1022
1023   if (!xiph3_streamheader_to_codecdata (streamheader, context, &buf0))
1024     return FALSE;
1025
1026   if (buf0 == NULL || GST_BUFFER_SIZE (buf0) < 1 + 6 + 26) {
1027     GST_WARNING ("First theora header too small, ignoring");
1028   } else if (memcmp (GST_BUFFER_DATA (buf0), "\200theora\003\002", 9) != 0) {
1029     GST_WARNING ("First header not a theora identification header, ignoring");
1030   } else {
1031     GstMatroskaTrackVideoContext *videocontext;
1032     guint fps_num, fps_denom, par_num, par_denom;
1033     guint8 *hdr;
1034
1035     hdr = GST_BUFFER_DATA (buf0) + 1 + 6 + 3 + 2 + 2;
1036
1037     videocontext = (GstMatroskaTrackVideoContext *) context;
1038     videocontext->pixel_width = GST_READ_UINT32_BE (hdr) >> 8;
1039     videocontext->pixel_height = GST_READ_UINT32_BE (hdr + 3) >> 8;
1040     hdr += 3 + 3 + 1 + 1;
1041     fps_num = GST_READ_UINT32_BE (hdr);
1042     fps_denom = GST_READ_UINT32_BE (hdr + 4);
1043     context->default_duration = gst_util_uint64_scale_int (GST_SECOND,
1044         fps_denom, fps_num);
1045     hdr += 4 + 4;
1046     par_num = GST_READ_UINT32_BE (hdr) >> 8;
1047     par_denom = GST_READ_UINT32_BE (hdr + 3) >> 8;
1048     if (par_num > 0 && par_num > 0) {
1049       if (par_num > par_denom) {
1050         videocontext->display_width =
1051             videocontext->pixel_width * par_num / par_denom;
1052         videocontext->display_height = videocontext->pixel_height;
1053       } else if (par_num < par_denom) {
1054         videocontext->display_width = videocontext->pixel_width;
1055         videocontext->display_height =
1056             videocontext->pixel_height * par_denom / par_num;
1057       } else {
1058         videocontext->display_width = 0;
1059         videocontext->display_height = 0;
1060       }
1061     } else {
1062       videocontext->display_width = 0;
1063       videocontext->display_height = 0;
1064     }
1065     hdr += 3 + 3;
1066   }
1067
1068   if (buf0)
1069     gst_buffer_unref (buf0);
1070
1071   return TRUE;
1072 }
1073
1074 static gboolean
1075 flac_streamheader_to_codecdata (const GValue * streamheader,
1076     GstMatroskaTrackContext * context)
1077 {
1078   GArray *bufarr;
1079   gint i;
1080   GValue *bufval;
1081   GstBuffer *buffer;
1082
1083   if (streamheader == NULL || G_VALUE_TYPE (streamheader) != GST_TYPE_ARRAY) {
1084     GST_WARNING ("No or invalid streamheader field in the caps");
1085     return FALSE;
1086   }
1087
1088   bufarr = g_value_peek_pointer (streamheader);
1089   if (bufarr->len < 2) {
1090     GST_WARNING ("Too few headers in streamheader field");
1091     return FALSE;
1092   }
1093
1094   context->xiph_headers_to_skip = bufarr->len + 1;
1095
1096   bufval = &g_array_index (bufarr, GValue, 0);
1097   if (G_VALUE_TYPE (bufval) != GST_TYPE_BUFFER) {
1098     GST_WARNING ("streamheaders array does not contain GstBuffers");
1099     return FALSE;
1100   }
1101
1102   buffer = g_value_peek_pointer (bufval);
1103
1104   /* Need at least OggFLAC mapping header, fLaC marker and STREAMINFO block */
1105   if (GST_BUFFER_SIZE (buffer) < 9 + 4 + 4 + 34
1106       || memcmp (GST_BUFFER_DATA (buffer) + 1, "FLAC", 4) != 0
1107       || memcmp (GST_BUFFER_DATA (buffer) + 9, "fLaC", 4) != 0) {
1108     GST_WARNING ("Invalid streamheader for FLAC");
1109     return FALSE;
1110   }
1111
1112   context->codec_priv = g_malloc (GST_BUFFER_SIZE (buffer) - 9);
1113   context->codec_priv_size = GST_BUFFER_SIZE (buffer) - 9;
1114   memcpy (context->codec_priv, GST_BUFFER_DATA (buffer) + 9,
1115       GST_BUFFER_SIZE (buffer) - 9);
1116
1117   for (i = 1; i < bufarr->len; i++) {
1118     bufval = &g_array_index (bufarr, GValue, i);
1119
1120     if (G_VALUE_TYPE (bufval) != GST_TYPE_BUFFER) {
1121       g_free (context->codec_priv);
1122       context->codec_priv = NULL;
1123       context->codec_priv_size = 0;
1124       GST_WARNING ("streamheaders array does not contain GstBuffers");
1125       return FALSE;
1126     }
1127
1128     buffer = g_value_peek_pointer (bufval);
1129
1130     context->codec_priv =
1131         g_realloc (context->codec_priv,
1132         context->codec_priv_size + GST_BUFFER_SIZE (buffer));
1133     memcpy ((guint8 *) context->codec_priv + context->codec_priv_size,
1134         GST_BUFFER_DATA (buffer), GST_BUFFER_SIZE (buffer));
1135     context->codec_priv_size =
1136         context->codec_priv_size + GST_BUFFER_SIZE (buffer);
1137   }
1138
1139   return TRUE;
1140 }
1141
1142 static gchar *
1143 aac_codec_data_to_codec_id (const GstBuffer * buf)
1144 {
1145   gchar *result;
1146   gint profile;
1147
1148   /* default to MAIN */
1149   profile = 1;
1150
1151   if (GST_BUFFER_SIZE (buf) >= 2) {
1152     profile = GST_READ_UINT8 (GST_BUFFER_DATA (buf));
1153     profile >>= 3;
1154   }
1155
1156   switch (profile) {
1157     case 1:
1158       result = "MAIN";
1159       break;
1160     case 2:
1161       result = "LC";
1162       break;
1163     case 3:
1164       result = "SSR";
1165       break;
1166     case 4:
1167       result = "LTP";
1168       break;
1169     default:
1170       GST_WARNING ("unknown AAC profile, defaulting to MAIN");
1171       result = "MAIN";
1172       break;
1173   }
1174
1175   return result;
1176 }
1177
1178 /**
1179  * gst_matroska_mux_audio_pad_setcaps:
1180  * @pad: Pad which got the caps.
1181  * @caps: New caps.
1182  *
1183  * Setcaps function for audio sink pad.
1184  *
1185  * Returns: #TRUE on success.
1186  */
1187 static gboolean
1188 gst_matroska_mux_audio_pad_setcaps (GstPad * pad, GstCaps * caps)
1189 {
1190   GstMatroskaTrackContext *context = NULL;
1191   GstMatroskaTrackAudioContext *audiocontext;
1192   GstMatroskaMux *mux;
1193   GstMatroskaPad *collect_pad;
1194   const gchar *mimetype;
1195   gint samplerate = 0, channels = 0;
1196   GstStructure *structure;
1197
1198   mux = GST_MATROSKA_MUX (GST_PAD_PARENT (pad));
1199
1200   /* find context */
1201   collect_pad = (GstMatroskaPad *) gst_pad_get_element_private (pad);
1202   g_assert (collect_pad);
1203   context = collect_pad->track;
1204   g_assert (context);
1205   g_assert (context->type == GST_MATROSKA_TRACK_TYPE_AUDIO);
1206   audiocontext = (GstMatroskaTrackAudioContext *) context;
1207
1208   structure = gst_caps_get_structure (caps, 0);
1209   mimetype = gst_structure_get_name (structure);
1210
1211   /* general setup */
1212   gst_structure_get_int (structure, "rate", &samplerate);
1213   gst_structure_get_int (structure, "channels", &channels);
1214
1215   audiocontext->samplerate = samplerate;
1216   audiocontext->channels = channels;
1217   audiocontext->bitdepth = 0;
1218   context->default_duration = 0;
1219
1220   /* TODO: - check if we handle all codecs by the spec, i.e. codec private
1221    *         data and other settings
1222    *       - add new formats
1223    */
1224
1225   if (!strcmp (mimetype, "audio/mpeg")) {
1226     gint mpegversion = 0;
1227     const GValue *codec_data;
1228     const GstBuffer *buf = NULL;
1229
1230     codec_data = gst_structure_get_value (structure, "codec_data");
1231     if (codec_data)
1232       buf = gst_value_get_buffer (codec_data);
1233
1234     gst_structure_get_int (structure, "mpegversion", &mpegversion);
1235     switch (mpegversion) {
1236       case 1:{
1237         gint layer;
1238         gint version = 1;
1239         gint spf;
1240
1241         gst_structure_get_int (structure, "layer", &layer);
1242
1243         if (!gst_structure_get_int (structure, "mpegaudioversion", &version)) {
1244           GST_WARNING_OBJECT (mux,
1245               "Unable to determine MPEG audio version, assuming 1");
1246           version = 1;
1247         }
1248
1249         if (layer == 1)
1250           spf = 384;
1251         else if (layer == 2)
1252           spf = 1152;
1253         else if (version == 2)
1254           spf = 576;
1255         else
1256           spf = 1152;
1257
1258         context->default_duration =
1259             gst_util_uint64_scale (GST_SECOND, spf, audiocontext->samplerate);
1260
1261         switch (layer) {
1262           case 1:
1263             context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L1);
1264             break;
1265           case 2:
1266             context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L2);
1267             break;
1268           case 3:
1269             context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L3);
1270             break;
1271           default:
1272             return FALSE;
1273         }
1274         break;
1275       }
1276       case 2:
1277         if (buf) {
1278           context->codec_id =
1279               g_strdup_printf (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2 "%s",
1280               aac_codec_data_to_codec_id (buf));
1281         } else {
1282           GST_DEBUG_OBJECT (mux, "no AAC codec_data; not packetized");
1283           return FALSE;
1284         }
1285         break;
1286       case 4:
1287         if (buf) {
1288           context->codec_id =
1289               g_strdup_printf (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4 "%s",
1290               aac_codec_data_to_codec_id (buf));
1291         } else {
1292           GST_DEBUG_OBJECT (mux, "no AAC codec_data; not packetized");
1293           return FALSE;
1294         }
1295         break;
1296       default:
1297         return FALSE;
1298     }
1299
1300     return TRUE;
1301   } else if (!strcmp (mimetype, "audio/x-raw-int")) {
1302     gint endianness, width, depth;
1303     gboolean signedness = G_LITTLE_ENDIAN;
1304
1305     if (!gst_structure_get_int (structure, "width", &width) ||
1306         !gst_structure_get_int (structure, "depth", &depth) ||
1307         !gst_structure_get_boolean (structure, "signed", &signedness)) {
1308       GST_DEBUG_OBJECT (mux, "broken caps, width/depth/signed field missing");
1309       return FALSE;
1310     }
1311
1312     if (depth > 8 &&
1313         !gst_structure_get_int (structure, "endianness", &endianness)) {
1314       GST_DEBUG_OBJECT (mux, "broken caps, no endianness specified");
1315       return FALSE;
1316     }
1317
1318     if (width != depth) {
1319       GST_DEBUG_OBJECT (mux, "width must be same as depth!");
1320       return FALSE;
1321     }
1322
1323     /* FIXME: where is this spec'ed out? (tpm) */
1324     if ((width == 8 && signedness) || (width >= 16 && !signedness)) {
1325       GST_DEBUG_OBJECT (mux, "8-bit PCM must be unsigned, 16-bit PCM signed");
1326       return FALSE;
1327     }
1328
1329     audiocontext->bitdepth = depth;
1330     if (endianness == G_BIG_ENDIAN)
1331       context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE);
1332     else
1333       context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_LE);
1334
1335     return TRUE;
1336   } else if (!strcmp (mimetype, "audio/x-raw-float")) {
1337     gint width;
1338
1339     if (!gst_structure_get_int (structure, "width", &width)) {
1340       GST_DEBUG_OBJECT (mux, "broken caps, width field missing");
1341       return FALSE;
1342     }
1343
1344     audiocontext->bitdepth = width;
1345     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_PCM_FLOAT);
1346
1347     return TRUE;
1348   } else if (!strcmp (mimetype, "audio/x-vorbis")) {
1349     const GValue *streamheader;
1350
1351     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_VORBIS);
1352
1353     if (context->codec_priv != NULL) {
1354       g_free (context->codec_priv);
1355       context->codec_priv = NULL;
1356       context->codec_priv_size = 0;
1357     }
1358
1359     streamheader = gst_structure_get_value (structure, "streamheader");
1360     if (!vorbis_streamheader_to_codecdata (streamheader, context)) {
1361       GST_ELEMENT_ERROR (mux, STREAM, MUX, (NULL),
1362           ("vorbis stream headers missing or malformed"));
1363       return FALSE;
1364     }
1365     return TRUE;
1366   } else if (!strcmp (mimetype, "audio/x-flac")) {
1367     const GValue *streamheader;
1368
1369     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_FLAC);
1370     if (context->codec_priv != NULL) {
1371       g_free (context->codec_priv);
1372       context->codec_priv = NULL;
1373       context->codec_priv_size = 0;
1374     }
1375
1376     streamheader = gst_structure_get_value (structure, "streamheader");
1377     if (!flac_streamheader_to_codecdata (streamheader, context)) {
1378       GST_ELEMENT_ERROR (mux, STREAM, MUX, (NULL),
1379           ("flac stream headers missing or malformed"));
1380       return FALSE;
1381     }
1382     return TRUE;
1383   } else if (!strcmp (mimetype, "audio/x-ac3")) {
1384     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_AC3);
1385
1386     return TRUE;
1387   } else if (!strcmp (mimetype, "audio/x-tta")) {
1388     gint width;
1389
1390     /* TTA frame duration */
1391     context->default_duration = 1.04489795918367346939 * GST_SECOND;
1392
1393     gst_structure_get_int (structure, "width", &width);
1394     audiocontext->bitdepth = width;
1395     context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_TTA);
1396
1397     return TRUE;
1398   } else if (!strcmp (mimetype, "audio/x-pn-realaudio")) {
1399     gint raversion;
1400     const GValue *mdpr_data;
1401
1402     gst_structure_get_int (structure, "raversion", &raversion);
1403     switch (raversion) {
1404       case 1:
1405         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4);
1406         break;
1407       case 2:
1408         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_REAL_28_8);
1409         break;
1410       case 8:
1411         context->codec_id = g_strdup (GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK);
1412         break;
1413       default:
1414         return FALSE;
1415     }
1416
1417     mdpr_data = gst_structure_get_value (structure, "mdpr_data");
1418     if (mdpr_data != NULL) {
1419       guint8 *priv_data = NULL;
1420       guint priv_data_size = 0;
1421
1422       GstBuffer *codec_data_buf = g_value_peek_pointer (mdpr_data);
1423
1424       priv_data_size = GST_BUFFER_SIZE (codec_data_buf);
1425       priv_data = g_malloc0 (priv_data_size);
1426
1427       memcpy (priv_data, GST_BUFFER_DATA (codec_data_buf), priv_data_size);
1428
1429       context->codec_priv = priv_data;
1430       context->codec_priv_size = priv_data_size;
1431     }
1432
1433     return TRUE;
1434   }
1435
1436   return FALSE;
1437 }
1438
1439
1440 /**
1441  * gst_matroska_mux_subtitle_pad_setcaps:
1442  * @pad: Pad which got the caps.
1443  * @caps: New caps.
1444  *
1445  * Setcaps function for subtitle sink pad.
1446  *
1447  * Returns: #TRUE on success.
1448  */
1449 static gboolean
1450 gst_matroska_mux_subtitle_pad_setcaps (GstPad * pad, GstCaps * caps)
1451 {
1452   /* FIXME:
1453    * Consider this as boilerplate code for now. There is
1454    * no single subtitle creation element in GStreamer,
1455    * neither do I know how subtitling works at all. */
1456
1457   return FALSE;
1458 }
1459
1460
1461 /**
1462  * gst_matroska_mux_request_new_pad:
1463  * @element: #GstMatroskaMux.
1464  * @templ: #GstPadTemplate.
1465  * @pad_name: New pad name.
1466  *
1467  * Request pad function for sink templates.
1468  *
1469  * Returns: New #GstPad.
1470  */
1471 static GstPad *
1472 gst_matroska_mux_request_new_pad (GstElement * element,
1473     GstPadTemplate * templ, const gchar * pad_name)
1474 {
1475   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
1476   GstMatroskaMux *mux = GST_MATROSKA_MUX (element);
1477   GstMatroskaPad *collect_pad;
1478   GstPad *newpad = NULL;
1479   gchar *name = NULL;
1480   GstPadSetCapsFunction setcapsfunc = NULL;
1481   GstMatroskaTrackContext *context = NULL;
1482
1483   if (templ == gst_element_class_get_pad_template (klass, "audio_%d")) {
1484     name = g_strdup_printf ("audio_%d", mux->num_a_streams++);
1485     setcapsfunc = GST_DEBUG_FUNCPTR (gst_matroska_mux_audio_pad_setcaps);
1486     context = (GstMatroskaTrackContext *)
1487         g_new0 (GstMatroskaTrackAudioContext, 1);
1488     context->type = GST_MATROSKA_TRACK_TYPE_AUDIO;
1489     context->name = g_strdup ("Audio");
1490   } else if (templ == gst_element_class_get_pad_template (klass, "video_%d")) {
1491     name = g_strdup_printf ("video_%d", mux->num_v_streams++);
1492     setcapsfunc = GST_DEBUG_FUNCPTR (gst_matroska_mux_video_pad_setcaps);
1493     context = (GstMatroskaTrackContext *)
1494         g_new0 (GstMatroskaTrackVideoContext, 1);
1495     context->type = GST_MATROSKA_TRACK_TYPE_VIDEO;
1496     context->name = g_strdup ("Video");
1497   } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%d")) {
1498     name = g_strdup_printf ("subtitle_%d", mux->num_t_streams++);
1499     setcapsfunc = GST_DEBUG_FUNCPTR (gst_matroska_mux_subtitle_pad_setcaps);
1500     context = (GstMatroskaTrackContext *)
1501         g_new0 (GstMatroskaTrackSubtitleContext, 1);
1502     context->type = GST_MATROSKA_TRACK_TYPE_SUBTITLE;
1503     context->name = g_strdup ("Subtitle");
1504   } else {
1505     GST_WARNING_OBJECT (mux, "This is not our template!");
1506     return NULL;
1507   }
1508
1509   newpad = gst_pad_new_from_template (templ, name);
1510   g_free (name);
1511   collect_pad = (GstMatroskaPad *)
1512       gst_collect_pads_add_pad_full (mux->collect, newpad,
1513       sizeof (GstMatroskaPad),
1514       (GstCollectDataDestroyNotify) gst_matroska_pad_free);
1515
1516   collect_pad->track = context;
1517   gst_matroska_pad_reset (collect_pad, FALSE);
1518
1519   /* FIXME: hacked way to override/extend the event function of
1520    * GstCollectPads; because it sets its own event function giving the
1521    * element no access to events.
1522    * TODO GstCollectPads should really give its 'users' a clean chance to
1523    * properly handle events that are not meant for collectpads itself.
1524    * Perhaps a callback or so, though rejected (?) in #340060.
1525    * This would allow (clean) transcoding of info from demuxer/streams
1526    * to another muxer */
1527   mux->collect_event = (GstPadEventFunction) GST_PAD_EVENTFUNC (newpad);
1528   gst_pad_set_event_function (newpad,
1529       GST_DEBUG_FUNCPTR (gst_matroska_mux_handle_sink_event));
1530
1531   gst_pad_set_setcaps_function (newpad, setcapsfunc);
1532   gst_pad_set_active (newpad, TRUE);
1533   gst_element_add_pad (element, newpad);
1534   mux->num_streams++;
1535
1536   return newpad;
1537 }
1538
1539 /**
1540  * gst_matroska_mux_release_pad:
1541  * @element: #GstMatroskaMux.
1542  * @pad: Pad to release.
1543  *
1544  * Release a previously requested pad.
1545 */
1546 static void
1547 gst_matroska_mux_release_pad (GstElement * element, GstPad * pad)
1548 {
1549   GstMatroskaMux *mux;
1550   GSList *walk;
1551
1552   mux = GST_MATROSKA_MUX (GST_PAD_PARENT (pad));
1553
1554   for (walk = mux->collect->data; walk; walk = g_slist_next (walk)) {
1555     GstCollectData *cdata = (GstCollectData *) walk->data;
1556     GstMatroskaPad *collect_pad = (GstMatroskaPad *) cdata;
1557
1558     if (cdata->pad == pad) {
1559       GstClockTime min_dur;     /* observed minimum duration */
1560
1561       if (GST_CLOCK_TIME_IS_VALID (collect_pad->start_ts) &&
1562           GST_CLOCK_TIME_IS_VALID (collect_pad->end_ts)) {
1563         min_dur = GST_CLOCK_DIFF (collect_pad->start_ts, collect_pad->end_ts);
1564         if (collect_pad->duration < min_dur)
1565           collect_pad->duration = min_dur;
1566       }
1567
1568       if (GST_CLOCK_TIME_IS_VALID (collect_pad->duration) &&
1569           mux->duration < collect_pad->duration)
1570         mux->duration = collect_pad->duration;
1571
1572       break;
1573     }
1574   }
1575
1576   gst_collect_pads_remove_pad (mux->collect, pad);
1577   if (gst_element_remove_pad (element, pad))
1578     mux->num_streams--;
1579 }
1580
1581
1582 /**
1583  * gst_matroska_mux_track_header:
1584  * @mux: #GstMatroskaMux
1585  * @context: Tack context.
1586  *
1587  * Write a track header.
1588  */
1589 static void
1590 gst_matroska_mux_track_header (GstMatroskaMux * mux,
1591     GstMatroskaTrackContext * context)
1592 {
1593   GstEbmlWrite *ebml = mux->ebml_write;
1594   guint64 master;
1595
1596   /* TODO: check if everything necessary is written and check default values */
1597
1598   /* track type goes before the type-specific stuff */
1599   gst_ebml_write_uint (ebml, GST_MATROSKA_ID_TRACKNUMBER, context->num);
1600   gst_ebml_write_uint (ebml, GST_MATROSKA_ID_TRACKTYPE, context->type);
1601
1602   gst_ebml_write_uint (ebml, GST_MATROSKA_ID_TRACKUID,
1603       gst_matroska_mux_create_uid ());
1604   if (context->default_duration) {
1605     gst_ebml_write_uint (ebml, GST_MATROSKA_ID_TRACKDEFAULTDURATION,
1606         context->default_duration);
1607   }
1608   if (context->language) {
1609     gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_TRACKLANGUAGE,
1610         context->language);
1611   }
1612
1613   /* type-specific stuff */
1614   switch (context->type) {
1615     case GST_MATROSKA_TRACK_TYPE_VIDEO:{
1616       GstMatroskaTrackVideoContext *videocontext =
1617           (GstMatroskaTrackVideoContext *) context;
1618
1619       master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TRACKVIDEO);
1620       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_VIDEOPIXELWIDTH,
1621           videocontext->pixel_width);
1622       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_VIDEOPIXELHEIGHT,
1623           videocontext->pixel_height);
1624       if (videocontext->display_width && videocontext->display_height) {
1625         gst_ebml_write_uint (ebml, GST_MATROSKA_ID_VIDEODISPLAYWIDTH,
1626             videocontext->display_width);
1627         gst_ebml_write_uint (ebml, GST_MATROSKA_ID_VIDEODISPLAYHEIGHT,
1628             videocontext->display_height);
1629       }
1630       if (context->flags & GST_MATROSKA_VIDEOTRACK_INTERLACED)
1631         gst_ebml_write_uint (ebml, GST_MATROSKA_ID_VIDEOFLAGINTERLACED, 1);
1632       if (videocontext->fourcc) {
1633         guint32 fcc_le = GUINT32_TO_LE (videocontext->fourcc);
1634
1635         gst_ebml_write_binary (ebml, GST_MATROSKA_ID_VIDEOCOLOURSPACE,
1636             (gpointer) & fcc_le, 4);
1637       }
1638       gst_ebml_write_master_finish (ebml, master);
1639
1640       break;
1641     }
1642
1643     case GST_MATROSKA_TRACK_TYPE_AUDIO:{
1644       GstMatroskaTrackAudioContext *audiocontext =
1645           (GstMatroskaTrackAudioContext *) context;
1646
1647       master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TRACKAUDIO);
1648       if (audiocontext->samplerate != 8000)
1649         gst_ebml_write_float (ebml, GST_MATROSKA_ID_AUDIOSAMPLINGFREQ,
1650             audiocontext->samplerate);
1651       if (audiocontext->channels != 1)
1652         gst_ebml_write_uint (ebml, GST_MATROSKA_ID_AUDIOCHANNELS,
1653             audiocontext->channels);
1654       if (audiocontext->bitdepth) {
1655         gst_ebml_write_uint (ebml, GST_MATROSKA_ID_AUDIOBITDEPTH,
1656             audiocontext->bitdepth);
1657       }
1658       gst_ebml_write_master_finish (ebml, master);
1659
1660       break;
1661     }
1662
1663     default:
1664       /* doesn't need type-specific data */
1665       break;
1666   }
1667
1668   gst_ebml_write_ascii (ebml, GST_MATROSKA_ID_CODECID, context->codec_id);
1669   if (context->codec_priv)
1670     gst_ebml_write_binary (ebml, GST_MATROSKA_ID_CODECPRIVATE,
1671         context->codec_priv, context->codec_priv_size);
1672   /* FIXME: until we have a nice way of getting the codecname
1673    * out of the caps, I'm not going to enable this. Too much
1674    * (useless, double, boring) work... */
1675   /* TODO: Use value from tags if any */
1676   /*gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_CODECNAME,
1677      context->codec_name); */
1678   gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_TRACKNAME, context->name);
1679 }
1680
1681
1682 /**
1683  * gst_matroska_mux_start:
1684  * @mux: #GstMatroskaMux
1685  *
1686  * Start a new matroska file (write headers etc...)
1687  */
1688 static void
1689 gst_matroska_mux_start (GstMatroskaMux * mux)
1690 {
1691   GstEbmlWrite *ebml = mux->ebml_write;
1692   guint32 seekhead_id[] = { GST_MATROSKA_ID_SEGMENTINFO,
1693     GST_MATROSKA_ID_TRACKS,
1694     GST_MATROSKA_ID_CUES,
1695     GST_MATROSKA_ID_TAGS,
1696     0
1697   };
1698   guint64 master, child;
1699   GSList *collected;
1700   int i;
1701   guint tracknum = 1;
1702   GstClockTime duration = 0;
1703   guint32 segment_uid[4];
1704   GTimeVal time = { 0, 0 };
1705
1706   /* we start with a EBML header */
1707   gst_ebml_write_header (ebml, "matroska", mux->matroska_version);
1708
1709   /* start a segment */
1710   mux->segment_pos =
1711       gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_SEGMENT);
1712   mux->segment_master = ebml->pos;
1713
1714   /* the rest of the header is cached */
1715   gst_ebml_write_set_cache (ebml, 0x1000);
1716
1717   /* seekhead (table of contents) - we set the positions later */
1718   mux->seekhead_pos = ebml->pos;
1719   master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_SEEKHEAD);
1720   for (i = 0; seekhead_id[i] != 0; i++) {
1721     child = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_SEEKENTRY);
1722     gst_ebml_write_uint (ebml, GST_MATROSKA_ID_SEEKID, seekhead_id[i]);
1723     gst_ebml_write_uint (ebml, GST_MATROSKA_ID_SEEKPOSITION, -1);
1724     gst_ebml_write_master_finish (ebml, child);
1725   }
1726   gst_ebml_write_master_finish (ebml, master);
1727
1728   /* segment info */
1729   mux->info_pos = ebml->pos;
1730   master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_SEGMENTINFO);
1731   for (i = 0; i < 4; i++) {
1732     segment_uid[i] = g_random_int ();
1733   }
1734   gst_ebml_write_binary (ebml, GST_MATROSKA_ID_SEGMENTUID,
1735       (guint8 *) segment_uid, 16);
1736   gst_ebml_write_uint (ebml, GST_MATROSKA_ID_TIMECODESCALE, mux->time_scale);
1737   mux->duration_pos = ebml->pos;
1738   /* get duration */
1739   for (collected = mux->collect->data; collected;
1740       collected = g_slist_next (collected)) {
1741     GstMatroskaPad *collect_pad;
1742     GstFormat format = GST_FORMAT_TIME;
1743     GstPad *thepad;
1744     gint64 trackduration;
1745
1746     collect_pad = (GstMatroskaPad *) collected->data;
1747     thepad = collect_pad->collect.pad;
1748
1749     /* Query the total length of the track. */
1750     GST_DEBUG_OBJECT (thepad, "querying peer duration");
1751     if (gst_pad_query_peer_duration (thepad, &format, &trackduration)) {
1752       GST_DEBUG_OBJECT (thepad, "duration: %" GST_TIME_FORMAT,
1753           GST_TIME_ARGS (trackduration));
1754       if (trackduration != GST_CLOCK_TIME_NONE && trackduration > duration) {
1755         duration = (GstClockTime) trackduration;
1756       }
1757     }
1758   }
1759   gst_ebml_write_float (ebml, GST_MATROSKA_ID_DURATION,
1760       gst_guint64_to_gdouble (duration) /
1761       gst_guint64_to_gdouble (mux->time_scale));
1762
1763   gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_MUXINGAPP,
1764       "GStreamer plugin version " PACKAGE_VERSION);
1765   if (mux->writing_app && mux->writing_app[0]) {
1766     gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_WRITINGAPP, mux->writing_app);
1767   }
1768   g_get_current_time (&time);
1769   gst_ebml_write_date (ebml, GST_MATROSKA_ID_DATEUTC, time.tv_sec);
1770   gst_ebml_write_master_finish (ebml, master);
1771
1772   /* tracks */
1773   mux->tracks_pos = ebml->pos;
1774   master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TRACKS);
1775
1776   for (collected = mux->collect->data; collected;
1777       collected = g_slist_next (collected)) {
1778     GstMatroskaPad *collect_pad;
1779     GstPad *thepad;
1780
1781     collect_pad = (GstMatroskaPad *) collected->data;
1782     thepad = collect_pad->collect.pad;
1783
1784     if (gst_pad_is_linked (thepad) && gst_pad_is_active (thepad) &&
1785         collect_pad->track->codec_id != 0) {
1786       collect_pad->track->num = tracknum++;
1787       child = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TRACKENTRY);
1788       gst_matroska_mux_track_header (mux, collect_pad->track);
1789       gst_ebml_write_master_finish (ebml, child);
1790     }
1791   }
1792   gst_ebml_write_master_finish (ebml, master);
1793
1794   /* lastly, flush the cache */
1795   gst_ebml_write_flush_cache (ebml);
1796 }
1797
1798 static void
1799 gst_matroska_mux_write_simple_tag (const GstTagList * list, const gchar * tag,
1800     gpointer data)
1801 {
1802   /* TODO: more sensible tag mappings */
1803   struct
1804   {
1805     gchar *matroska_tagname;
1806     gchar *gstreamer_tagname;
1807   }
1808   tag_conv[] = {
1809     {
1810     GST_MATROSKA_TAG_ID_TITLE, GST_TAG_TITLE}, {
1811     GST_MATROSKA_TAG_ID_AUTHOR, GST_TAG_ARTIST}, {
1812     GST_MATROSKA_TAG_ID_ALBUM, GST_TAG_ALBUM}, {
1813     GST_MATROSKA_TAG_ID_COMMENTS, GST_TAG_COMMENT}, {
1814     GST_MATROSKA_TAG_ID_BITSPS, GST_TAG_BITRATE}, {
1815     GST_MATROSKA_TAG_ID_BPS, GST_TAG_BITRATE}, {
1816     GST_MATROSKA_TAG_ID_ENCODER, GST_TAG_ENCODER}, {
1817     GST_MATROSKA_TAG_ID_DATE, GST_TAG_DATE}, {
1818     GST_MATROSKA_TAG_ID_ISRC, GST_TAG_ISRC}, {
1819     GST_MATROSKA_TAG_ID_COPYRIGHT, GST_TAG_COPYRIGHT}, {
1820     GST_MATROSKA_TAG_ID_BPM, GST_TAG_BEATS_PER_MINUTE}, {
1821     GST_MATROSKA_TAG_ID_TERMS_OF_USE, GST_TAG_LICENSE}, {
1822     GST_MATROSKA_TAG_ID_COMPOSER, GST_TAG_COMPOSER}, {
1823     GST_MATROSKA_TAG_ID_LEAD_PERFORMER, GST_TAG_PERFORMER}, {
1824     GST_MATROSKA_TAG_ID_GENRE, GST_TAG_GENRE}
1825   };
1826   GstEbmlWrite *ebml = (GstEbmlWrite *) data;
1827   guint i;
1828   guint64 simpletag_master;
1829
1830   for (i = 0; i < G_N_ELEMENTS (tag_conv); i++) {
1831     const gchar *tagname_gst = tag_conv[i].gstreamer_tagname;
1832     const gchar *tagname_mkv = tag_conv[i].matroska_tagname;
1833
1834     if (strcmp (tagname_gst, tag) == 0) {
1835       GValue src = { 0, };
1836       gchar *dest;
1837
1838       if (!gst_tag_list_copy_value (&src, list, tag))
1839         break;
1840       if ((dest = gst_value_serialize (&src))) {
1841
1842         simpletag_master = gst_ebml_write_master_start (ebml,
1843             GST_MATROSKA_ID_SIMPLETAG);
1844         gst_ebml_write_ascii (ebml, GST_MATROSKA_ID_TAGNAME, tagname_mkv);
1845         gst_ebml_write_utf8 (ebml, GST_MATROSKA_ID_TAGSTRING, dest);
1846         gst_ebml_write_master_finish (ebml, simpletag_master);
1847       } else {
1848         GST_WARNING ("Can't transform tag '%s' to string", tagname_mkv);
1849       }
1850       g_value_unset (&src);
1851       break;
1852     }
1853   }
1854 }
1855
1856
1857 /**
1858  * gst_matroska_mux_finish:
1859  * @mux: #GstMatroskaMux
1860  *
1861  * Finish a new matroska file (write index etc...)
1862  */
1863 static void
1864 gst_matroska_mux_finish (GstMatroskaMux * mux)
1865 {
1866   GstEbmlWrite *ebml = mux->ebml_write;
1867   guint64 pos;
1868   guint64 duration = 0;
1869   GSList *collected;
1870   const GstTagList *tags;
1871
1872   /* finish last cluster */
1873   if (mux->cluster) {
1874     gst_ebml_write_master_finish (ebml, mux->cluster);
1875   }
1876
1877   /* cues */
1878   if (mux->index != NULL) {
1879     guint n;
1880     guint64 master, pointentry_master, trackpos_master;
1881
1882     mux->cues_pos = ebml->pos;
1883     gst_ebml_write_set_cache (ebml, 12 + 41 * mux->num_indexes);
1884     master = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_CUES);
1885
1886     for (n = 0; n < mux->num_indexes; n++) {
1887       GstMatroskaIndex *idx = &mux->index[n];
1888
1889       pointentry_master = gst_ebml_write_master_start (ebml,
1890           GST_MATROSKA_ID_POINTENTRY);
1891       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CUETIME,
1892           idx->time / mux->time_scale);
1893       trackpos_master = gst_ebml_write_master_start (ebml,
1894           GST_MATROSKA_ID_CUETRACKPOSITIONS);
1895       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CUETRACK, idx->track);
1896       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CUECLUSTERPOSITION,
1897           idx->pos - mux->segment_master);
1898       gst_ebml_write_master_finish (ebml, trackpos_master);
1899       gst_ebml_write_master_finish (ebml, pointentry_master);
1900     }
1901
1902     gst_ebml_write_master_finish (ebml, master);
1903     gst_ebml_write_flush_cache (ebml);
1904   }
1905
1906   /* tags */
1907   tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (mux));
1908
1909   if (tags != NULL && !gst_tag_list_is_empty (tags)) {
1910     guint64 master_tags, master_tag;
1911
1912     GST_DEBUG ("Writing tags");
1913
1914     /* TODO: maybe limit via the TARGETS id by looking at the source pad */
1915     mux->tags_pos = ebml->pos;
1916     master_tags = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TAGS);
1917     master_tag = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_TAG);
1918     gst_tag_list_foreach (tags, gst_matroska_mux_write_simple_tag, ebml);
1919     gst_ebml_write_master_finish (ebml, master_tag);
1920     gst_ebml_write_master_finish (ebml, master_tags);
1921   }
1922
1923   /* update seekhead. We know that:
1924    * - a seekhead contains 4 entries.
1925    * - order of entries is as above.
1926    * - a seekhead has a 4-byte header + 8-byte length
1927    * - each entry is 2-byte master, 2-byte ID pointer,
1928    *     2-byte length pointer, all 8/1-byte length, 4-
1929    *     byte ID and 8-byte length pointer, where the
1930    *     length pointer starts at 20.
1931    * - all entries are local to the segment (so pos - segment_master).
1932    * - so each entry is at 12 + 20 + num * 28. */
1933   gst_ebml_replace_uint (ebml, mux->seekhead_pos + 32,
1934       mux->info_pos - mux->segment_master);
1935   gst_ebml_replace_uint (ebml, mux->seekhead_pos + 60,
1936       mux->tracks_pos - mux->segment_master);
1937   if (mux->index != NULL) {
1938     gst_ebml_replace_uint (ebml, mux->seekhead_pos + 88,
1939         mux->cues_pos - mux->segment_master);
1940   } else {
1941     /* void'ify */
1942     guint64 my_pos = ebml->pos;
1943
1944     gst_ebml_write_seek (ebml, mux->seekhead_pos + 68);
1945     gst_ebml_write_buffer_header (ebml, GST_EBML_ID_VOID, 26);
1946     gst_ebml_write_seek (ebml, my_pos);
1947   }
1948   if (tags != NULL) {
1949     gst_ebml_replace_uint (ebml, mux->seekhead_pos + 116,
1950         mux->tags_pos - mux->segment_master);
1951   } else {
1952     /* void'ify */
1953     guint64 my_pos = ebml->pos;
1954
1955     gst_ebml_write_seek (ebml, mux->seekhead_pos + 96);
1956     gst_ebml_write_buffer_header (ebml, GST_EBML_ID_VOID, 26);
1957     gst_ebml_write_seek (ebml, my_pos);
1958   }
1959
1960   /* update duration */
1961   /* first get the overall duration */
1962   /* a released track may have left a duration in here */
1963   duration = mux->duration;
1964   for (collected = mux->collect->data; collected;
1965       collected = g_slist_next (collected)) {
1966     GstMatroskaPad *collect_pad;
1967     GstClockTime min_duration;  /* observed minimum duration */
1968
1969     collect_pad = (GstMatroskaPad *) collected->data;
1970
1971     GST_DEBUG_OBJECT (mux, "Pad %" GST_PTR_FORMAT " start ts %" GST_TIME_FORMAT
1972         " end ts %" GST_TIME_FORMAT, collect_pad,
1973         GST_TIME_ARGS (collect_pad->start_ts),
1974         GST_TIME_ARGS (collect_pad->end_ts));
1975
1976     if (GST_CLOCK_TIME_IS_VALID (collect_pad->start_ts) &&
1977         GST_CLOCK_TIME_IS_VALID (collect_pad->end_ts)) {
1978       min_duration =
1979           GST_CLOCK_DIFF (collect_pad->start_ts, collect_pad->end_ts);
1980       if (collect_pad->duration < min_duration)
1981         collect_pad->duration = min_duration;
1982       GST_DEBUG_OBJECT (collect_pad, "final track duration: %" GST_TIME_FORMAT,
1983           GST_TIME_ARGS (collect_pad->duration));
1984     }
1985
1986     if (GST_CLOCK_TIME_IS_VALID (collect_pad->duration) &&
1987         duration < collect_pad->duration)
1988       duration = collect_pad->duration;
1989   }
1990   if (duration != 0) {
1991     GST_DEBUG_OBJECT (mux, "final total duration: %" GST_TIME_FORMAT,
1992         GST_TIME_ARGS (duration));
1993     pos = mux->ebml_write->pos;
1994     gst_ebml_write_seek (ebml, mux->duration_pos);
1995     gst_ebml_write_float (ebml, GST_MATROSKA_ID_DURATION,
1996         gst_guint64_to_gdouble (duration) /
1997         gst_guint64_to_gdouble (mux->time_scale));
1998     gst_ebml_write_seek (ebml, pos);
1999   } else {
2000     /* void'ify */
2001     guint64 my_pos = ebml->pos;
2002
2003     gst_ebml_write_seek (ebml, mux->duration_pos);
2004     gst_ebml_write_buffer_header (ebml, GST_EBML_ID_VOID, 8);
2005     gst_ebml_write_seek (ebml, my_pos);
2006   }
2007
2008   /* finish segment - this also writes element length */
2009   gst_ebml_write_master_finish (ebml, mux->segment_pos);
2010 }
2011
2012
2013 /**
2014  * gst_matroska_mux_best_pad:
2015  * @mux: #GstMatroskaMux
2016  * @popped: True if at least one buffer was popped from #GstCollectPads
2017  *
2018  * Find a pad with the oldest data 
2019  * (data from this pad should be written first).
2020  *
2021  * Returns: Selected pad.
2022  */
2023 static GstMatroskaPad *
2024 gst_matroska_mux_best_pad (GstMatroskaMux * mux, gboolean * popped)
2025 {
2026   GSList *collected;
2027   GstMatroskaPad *best = NULL;
2028
2029   *popped = FALSE;
2030   for (collected = mux->collect->data; collected;
2031       collected = g_slist_next (collected)) {
2032     GstMatroskaPad *collect_pad;
2033
2034     collect_pad = (GstMatroskaPad *) collected->data;
2035     /* fetch a new buffer if needed */
2036     if (collect_pad->buffer == NULL) {
2037       collect_pad->buffer = gst_collect_pads_pop (mux->collect,
2038           (GstCollectData *) collect_pad);
2039
2040       if (collect_pad->buffer != NULL)
2041         *popped = TRUE;
2042     }
2043
2044     /* if we have a buffer check if it is better then the current best one */
2045     if (collect_pad->buffer != NULL) {
2046       if (best == NULL || !GST_BUFFER_TIMESTAMP_IS_VALID (collect_pad->buffer)
2047           || (GST_BUFFER_TIMESTAMP_IS_VALID (best->buffer)
2048               && GST_BUFFER_TIMESTAMP (collect_pad->buffer) <
2049               GST_BUFFER_TIMESTAMP (best->buffer))) {
2050         best = collect_pad;
2051       }
2052     }
2053   }
2054
2055   return best;
2056 }
2057
2058 /**
2059  * gst_matroska_mux_buffer_header:
2060  * @track: Track context.
2061  * @relative_timestamp: relative timestamp of the buffer
2062  * @flags: Buffer flags.
2063  *
2064  * Create a buffer containing buffer header.
2065  * 
2066  * Returns: New buffer.
2067  */
2068 GstBuffer *
2069 gst_matroska_mux_create_buffer_header (GstMatroskaTrackContext * track,
2070     gint16 relative_timestamp, int flags)
2071 {
2072   GstBuffer *hdr;
2073
2074   hdr = gst_buffer_new_and_alloc (4);
2075   /* track num - FIXME: what if num >= 0x80 (unlikely)? */
2076   GST_BUFFER_DATA (hdr)[0] = track->num | 0x80;
2077   /* time relative to clustertime */
2078   GST_WRITE_UINT16_BE (GST_BUFFER_DATA (hdr) + 1, relative_timestamp);
2079
2080   /* flags */
2081   GST_BUFFER_DATA (hdr)[3] = flags;
2082
2083   return hdr;
2084 }
2085
2086 static GstBuffer *
2087 gst_matroska_mux_handle_dirac_packet (GstMatroskaMux * mux,
2088     GstMatroskaPad * collect_pad, GstBuffer * buf)
2089 {
2090   GstMatroskaTrackVideoContext *ctx =
2091       (GstMatroskaTrackVideoContext *) collect_pad->track;
2092   const guint8 *data = GST_BUFFER_DATA (buf);
2093   guint size = GST_BUFFER_SIZE (buf);
2094   guint8 parse_code;
2095   guint32 next_parse_offset;
2096   GstBuffer *ret = NULL;
2097   gboolean is_picture = FALSE;
2098
2099   if (GST_BUFFER_SIZE (buf) < 13) {
2100     gst_buffer_unref (buf);
2101     return ret;
2102   }
2103
2104   /* Check if this buffer contains a picture packet */
2105   while (size >= 13) {
2106     if (GST_READ_UINT32_BE (data) != 0x42424344) {
2107       gst_buffer_unref (buf);
2108       return ret;
2109     }
2110
2111     parse_code = GST_READ_UINT8 (data + 4);
2112     if (parse_code == 0x00) {
2113       if (ctx->dirac_unit) {
2114         gst_buffer_unref (ctx->dirac_unit);
2115         ctx->dirac_unit = NULL;
2116       }
2117     } else if (parse_code & 0x08) {
2118       is_picture = TRUE;
2119       break;
2120     }
2121
2122     next_parse_offset = GST_READ_UINT32_BE (data + 5);
2123
2124     data += next_parse_offset;
2125     size -= next_parse_offset;
2126   }
2127
2128   if (ctx->dirac_unit)
2129     ctx->dirac_unit = gst_buffer_join (ctx->dirac_unit, gst_buffer_ref (buf));
2130   else
2131     ctx->dirac_unit = gst_buffer_ref (buf);
2132
2133   if (is_picture) {
2134     ret = gst_buffer_make_metadata_writable (ctx->dirac_unit);
2135     ctx->dirac_unit = NULL;
2136     gst_buffer_copy_metadata (ret, buf,
2137         GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS |
2138         GST_BUFFER_COPY_CAPS);
2139     gst_buffer_unref (buf);
2140   } else {
2141     gst_buffer_unref (buf);
2142     ret = NULL;
2143   }
2144
2145   return ret;
2146 }
2147
2148 /**
2149  * gst_matroska_mux_write_data:
2150  * @mux: #GstMatroskaMux
2151  * @collect_pad: #GstMatroskaPad with the data
2152  *
2153  * Write collected data (called from gst_matroska_mux_collected).
2154  *
2155  * Returns: Result of the gst_pad_push issued to write the data.
2156  */
2157 static GstFlowReturn
2158 gst_matroska_mux_write_data (GstMatroskaMux * mux, GstMatroskaPad * collect_pad)
2159 {
2160   GstEbmlWrite *ebml = mux->ebml_write;
2161   GstBuffer *buf, *hdr;
2162   guint64 cluster, blockgroup;
2163   gboolean write_duration;
2164   gint16 relative_timestamp;
2165   gint64 relative_timestamp64;
2166   guint64 block_duration;
2167   gboolean is_video_keyframe = FALSE;
2168
2169   /* write data */
2170   buf = collect_pad->buffer;
2171   collect_pad->buffer = NULL;
2172
2173   /* vorbis/theora headers are retrieved from caps and put in CodecPrivate */
2174   if (collect_pad->track->xiph_headers_to_skip > 0) {
2175     GST_LOG_OBJECT (collect_pad->collect.pad, "dropping streamheader buffer");
2176     gst_buffer_unref (buf);
2177     --collect_pad->track->xiph_headers_to_skip;
2178     return GST_FLOW_OK;
2179   }
2180
2181   /* for dirac we have to queue up everything up to a picture unit */
2182   if (collect_pad->track->codec_id != NULL &&
2183       strcmp (collect_pad->track->codec_id,
2184           GST_MATROSKA_CODEC_ID_VIDEO_DIRAC) == 0) {
2185     buf = gst_matroska_mux_handle_dirac_packet (mux, collect_pad, buf);
2186     if (!buf)
2187       return GST_FLOW_OK;
2188   }
2189
2190   /* hm, invalid timestamp (due to --to be fixed--- element upstream);
2191    * this would wreak havoc with time stored in matroska file */
2192   /* TODO: maybe calculate a timestamp by using the previous timestamp
2193    * and default duration */
2194   if (!GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
2195     GST_WARNING_OBJECT (collect_pad->collect.pad,
2196         "Invalid buffer timestamp; dropping buffer");
2197     gst_buffer_unref (buf);
2198     return GST_FLOW_OK;
2199   }
2200
2201   /* set the timestamp for outgoing buffers */
2202   ebml->timestamp = GST_BUFFER_TIMESTAMP (buf);
2203
2204   if (collect_pad->track->type == GST_MATROSKA_TRACK_TYPE_VIDEO &&
2205       !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2206     GST_LOG_OBJECT (mux, "have video keyframe, ts=%" GST_TIME_FORMAT,
2207         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2208     is_video_keyframe = TRUE;
2209   }
2210
2211   if (mux->cluster) {
2212     /* start a new cluster every two seconds or at keyframe */
2213     if (mux->cluster_time + GST_SECOND * 2 < GST_BUFFER_TIMESTAMP (buf)
2214         || is_video_keyframe) {
2215
2216       gst_ebml_write_master_finish (ebml, mux->cluster);
2217       mux->cluster_pos = ebml->pos;
2218       mux->cluster =
2219           gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_CLUSTER);
2220       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CLUSTERTIMECODE,
2221           GST_BUFFER_TIMESTAMP (buf) / mux->time_scale);
2222       mux->cluster_time = GST_BUFFER_TIMESTAMP (buf);
2223     }
2224   } else {
2225     /* first cluster */
2226
2227     mux->cluster_pos = ebml->pos;
2228     mux->cluster = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_CLUSTER);
2229     gst_ebml_write_uint (ebml, GST_MATROSKA_ID_CLUSTERTIMECODE,
2230         GST_BUFFER_TIMESTAMP (buf) / mux->time_scale);
2231     mux->cluster_time = GST_BUFFER_TIMESTAMP (buf);
2232   }
2233   cluster = mux->cluster;
2234
2235   /* update duration of this track */
2236   if (GST_BUFFER_DURATION_IS_VALID (buf))
2237     collect_pad->duration += GST_BUFFER_DURATION (buf);
2238
2239   /* We currently write an index entry for each keyframe in a
2240    * video track or one entry for each cluster in an audio track
2241    * for audio only files. This can be largely improved, such as doing
2242    * one for each keyframe or each second (for all-keyframe
2243    * streams), only the *first* video track. But that'll come later... */
2244
2245   /* TODO: index is useful for every track, should contain the number of
2246    * the block in the cluster which contains the timestamp
2247    */
2248   if (is_video_keyframe) {
2249     GstMatroskaIndex *idx;
2250
2251     if (mux->num_indexes % 32 == 0) {
2252       mux->index = g_renew (GstMatroskaIndex, mux->index,
2253           mux->num_indexes + 32);
2254     }
2255     idx = &mux->index[mux->num_indexes++];
2256
2257     idx->pos = mux->cluster_pos;
2258     idx->time = GST_BUFFER_TIMESTAMP (buf);
2259     idx->track = collect_pad->track->num;
2260   } else if ((collect_pad->track->type == GST_MATROSKA_TRACK_TYPE_AUDIO) &&
2261       (mux->num_streams == 1)) {
2262     GstMatroskaIndex *idx;
2263
2264     if (mux->num_indexes % 32 == 0) {
2265       mux->index = g_renew (GstMatroskaIndex, mux->index,
2266           mux->num_indexes + 32);
2267     }
2268     idx = &mux->index[mux->num_indexes++];
2269
2270     idx->pos = mux->cluster_pos;
2271     idx->time = GST_BUFFER_TIMESTAMP (buf);
2272     idx->track = collect_pad->track->num;
2273   }
2274
2275   /* Check if the duration differs from the default duration. */
2276   write_duration = FALSE;
2277   block_duration = GST_BUFFER_DURATION (buf);
2278   if (GST_BUFFER_DURATION_IS_VALID (buf)) {
2279     if (block_duration != collect_pad->track->default_duration) {
2280       write_duration = TRUE;
2281     }
2282   }
2283
2284   /* write the block, for matroska v2 use SimpleBlock if possible
2285    * one slice (*breath*).
2286    * FIXME: Need to do correct lacing! */
2287   relative_timestamp64 = GST_BUFFER_TIMESTAMP (buf) - mux->cluster_time;
2288   if (relative_timestamp64 >= 0) {
2289     /* round the timestamp */
2290     relative_timestamp64 += mux->time_scale / 2;
2291   } else {
2292     /* round the timestamp */
2293     relative_timestamp64 -= mux->time_scale / 2;
2294   }
2295   relative_timestamp = relative_timestamp64 / (gint64) mux->time_scale;
2296   if (mux->matroska_version > 1 && !write_duration) {
2297     int flags =
2298         GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT) ? 0 : 0x80;
2299
2300     hdr =
2301         gst_matroska_mux_create_buffer_header (collect_pad->track,
2302         relative_timestamp, flags);
2303     gst_ebml_write_buffer_header (ebml, GST_MATROSKA_ID_SIMPLEBLOCK,
2304         GST_BUFFER_SIZE (buf) + GST_BUFFER_SIZE (hdr));
2305     gst_ebml_write_buffer (ebml, hdr);
2306     gst_ebml_write_buffer (ebml, buf);
2307
2308     return gst_ebml_last_write_result (ebml);
2309   } else {
2310     blockgroup = gst_ebml_write_master_start (ebml, GST_MATROSKA_ID_BLOCKGROUP);
2311     hdr =
2312         gst_matroska_mux_create_buffer_header (collect_pad->track,
2313         relative_timestamp, 0);
2314     gst_ebml_write_buffer_header (ebml, GST_MATROSKA_ID_BLOCK,
2315         GST_BUFFER_SIZE (buf) + GST_BUFFER_SIZE (hdr));
2316     gst_ebml_write_buffer (ebml, hdr);
2317     gst_ebml_write_buffer (ebml, buf);
2318     if (write_duration) {
2319       gst_ebml_write_uint (ebml, GST_MATROSKA_ID_BLOCKDURATION,
2320           block_duration / mux->time_scale);
2321     }
2322     gst_ebml_write_master_finish (ebml, blockgroup);
2323     return gst_ebml_last_write_result (ebml);
2324   }
2325 }
2326
2327
2328 /**
2329  * gst_matroska_mux_collected:
2330  * @pads: #GstCollectPads
2331  * @uuser_data: #GstMatroskaMux
2332  *
2333  * Collectpads callback.
2334  *
2335  * Returns: #GstFlowReturn
2336  */
2337 static GstFlowReturn
2338 gst_matroska_mux_collected (GstCollectPads * pads, gpointer user_data)
2339 {
2340   GstMatroskaMux *mux = GST_MATROSKA_MUX (user_data);
2341   GstMatroskaPad *best;
2342   gboolean popped;
2343   GstFlowReturn ret;
2344
2345   GST_DEBUG_OBJECT (mux, "Collected pads");
2346
2347   /* start with a header */
2348   if (mux->state == GST_MATROSKA_MUX_STATE_START) {
2349     if (mux->collect->data == NULL) {
2350       GST_ELEMENT_ERROR (mux, STREAM, MUX, (NULL),
2351           ("No input streams configured"));
2352       return GST_FLOW_ERROR;
2353     }
2354     mux->state = GST_MATROSKA_MUX_STATE_HEADER;
2355     gst_matroska_mux_start (mux);
2356     mux->state = GST_MATROSKA_MUX_STATE_DATA;
2357   }
2358
2359   do {
2360     /* which stream to write from? */
2361     best = gst_matroska_mux_best_pad (mux, &popped);
2362
2363     /* if there is no best pad, we have reached EOS */
2364     if (best == NULL) {
2365       GST_DEBUG_OBJECT (mux, "No best pad finishing...");
2366       gst_matroska_mux_finish (mux);
2367       gst_pad_push_event (mux->srcpad, gst_event_new_eos ());
2368       ret = GST_FLOW_UNEXPECTED;
2369       break;
2370     }
2371     GST_DEBUG_OBJECT (best->collect.pad, "best pad - buffer ts %"
2372         GST_TIME_FORMAT " dur %" GST_TIME_FORMAT,
2373         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (best->buffer)),
2374         GST_TIME_ARGS (GST_BUFFER_DURATION (best->buffer)));
2375
2376     /* make note of first and last encountered timestamps, so we can calculate
2377      * the actual duration later when we send an updated header on eos */
2378     if (GST_BUFFER_TIMESTAMP_IS_VALID (best->buffer)) {
2379       GstClockTime start_ts = GST_BUFFER_TIMESTAMP (best->buffer);
2380       GstClockTime end_ts = start_ts;
2381
2382       if (GST_BUFFER_DURATION_IS_VALID (best->buffer))
2383         end_ts += GST_BUFFER_DURATION (best->buffer);
2384       else if (best->track->default_duration)
2385         end_ts += best->track->default_duration;
2386
2387       if (!GST_CLOCK_TIME_IS_VALID (best->end_ts) || end_ts > best->end_ts)
2388         best->end_ts = end_ts;
2389
2390       if (G_UNLIKELY (best->start_ts == GST_CLOCK_TIME_NONE ||
2391               start_ts < best->start_ts))
2392         best->start_ts = start_ts;
2393     }
2394
2395     /* write one buffer */
2396     ret = gst_matroska_mux_write_data (mux, best);
2397   } while (ret == GST_FLOW_OK && !popped);
2398
2399   return ret;
2400 }
2401
2402
2403 /**
2404  * gst_matroska_mux_change_state:
2405  * @element: #GstMatroskaMux
2406  * @transition: State change transition.
2407  *
2408  * Change the muxer state.
2409  *
2410  * Returns: #GstStateChangeReturn
2411  */
2412 static GstStateChangeReturn
2413 gst_matroska_mux_change_state (GstElement * element, GstStateChange transition)
2414 {
2415   GstStateChangeReturn ret;
2416   GstMatroskaMux *mux = GST_MATROSKA_MUX (element);
2417
2418   switch (transition) {
2419     case GST_STATE_CHANGE_NULL_TO_READY:
2420       break;
2421     case GST_STATE_CHANGE_READY_TO_PAUSED:
2422       gst_collect_pads_start (mux->collect);
2423       break;
2424     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2425       break;
2426     case GST_STATE_CHANGE_PAUSED_TO_READY:
2427       gst_collect_pads_stop (mux->collect);
2428       break;
2429     default:
2430       break;
2431   }
2432
2433   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2434
2435   switch (transition) {
2436     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2437       break;
2438     case GST_STATE_CHANGE_PAUSED_TO_READY:
2439       gst_matroska_mux_reset (GST_ELEMENT (mux));
2440       break;
2441     case GST_STATE_CHANGE_READY_TO_NULL:
2442       break;
2443     default:
2444       break;
2445   }
2446
2447   return ret;
2448 }
2449
2450 static void
2451 gst_matroska_mux_set_property (GObject * object,
2452     guint prop_id, const GValue * value, GParamSpec * pspec)
2453 {
2454   GstMatroskaMux *mux;
2455
2456   g_return_if_fail (GST_IS_MATROSKA_MUX (object));
2457   mux = GST_MATROSKA_MUX (object);
2458
2459   switch (prop_id) {
2460     case ARG_WRITING_APP:
2461       if (!g_value_get_string (value)) {
2462         GST_WARNING_OBJECT (mux, "writing-app property can not be NULL");
2463         break;
2464       }
2465       g_free (mux->writing_app);
2466       mux->writing_app = g_value_dup_string (value);
2467       break;
2468     case ARG_MATROSKA_VERSION:
2469       mux->matroska_version = g_value_get_int (value);
2470       break;
2471     default:
2472       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2473       break;
2474   }
2475 }
2476
2477 static void
2478 gst_matroska_mux_get_property (GObject * object,
2479     guint prop_id, GValue * value, GParamSpec * pspec)
2480 {
2481   GstMatroskaMux *mux;
2482
2483   g_return_if_fail (GST_IS_MATROSKA_MUX (object));
2484   mux = GST_MATROSKA_MUX (object);
2485
2486   switch (prop_id) {
2487     case ARG_WRITING_APP:
2488       g_value_set_string (value, mux->writing_app);
2489       break;
2490     case ARG_MATROSKA_VERSION:
2491       g_value_set_int (value, mux->matroska_version);
2492       break;
2493     default:
2494       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2495       break;
2496   }
2497 }
2498
2499 gboolean
2500 gst_matroska_mux_plugin_init (GstPlugin * plugin)
2501 {
2502   return gst_element_register (plugin, "matroskamux",
2503       GST_RANK_NONE, GST_TYPE_MATROSKA_MUX);
2504 }