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