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