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