tizen 2.0 init
[framework/multimedia/gst-plugins-good0.10.git] / gst / avi / gstavimux.c
1 /* AVI muxer plugin for GStreamer
2  * Copyright (C) 2002 Ronald Bultje <rbultje@ronald.bitfreak.net>
3  *           (C) 2006 Mark Nauwelaerts <manauw@skynet.be>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /* based on:
22  * - the old avimuxer (by Wim Taymans)
23  * - xawtv's aviwriter (by Gerd Knorr)
24  * - mjpegtools' avilib (by Rainer Johanni)
25  * - openDML large-AVI docs
26  */
27
28 /**
29  * SECTION:element-avimux
30  *
31  * Muxes raw or compressed audio and/or video streams into an AVI file.
32  *
33  * <refsect2>
34  * <title>Example launch lines</title>
35  * <para>(write everything in one line, without the backslash characters)</para>
36  * |[
37  * gst-launch videotestsrc num-buffers=250 \
38  * ! 'video/x-raw-yuv,format=(fourcc)I420,width=320,height=240,framerate=(fraction)25/1' \
39  * ! queue ! mux. \
40  * audiotestsrc num-buffers=440 ! audioconvert \
41  * ! 'audio/x-raw-int,rate=44100,channels=2' ! queue ! mux. \
42  * avimux name=mux ! filesink location=test.avi
43  * ]| This will create an .AVI file containing an uncompressed video stream
44  * with a test picture and an uncompressed audio stream containing a
45  * test sound.
46  * |[
47  * gst-launch videotestsrc num-buffers=250 \
48  * ! 'video/x-raw-yuv,format=(fourcc)I420,width=320,height=240,framerate=(fraction)25/1' \
49  * ! xvidenc ! queue ! mux. \
50  * audiotestsrc num-buffers=440 ! audioconvert ! 'audio/x-raw-int,rate=44100,channels=2' \
51  * ! lame ! queue ! mux. \
52  * avimux name=mux ! filesink location=test.avi
53  * ]| This will create an .AVI file containing the same test video and sound
54  * as above, only that both streams will be compressed this time. This will
55  * only work if you have the necessary encoder elements installed of course.
56  * </refsect2>
57  */
58
59 #ifdef HAVE_CONFIG_H
60 #include "config.h"
61 #endif
62
63 #include "gst/gst-i18n-plugin.h"
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67
68 #include <gst/video/video.h>
69 #include <gst/base/gstbytewriter.h>
70
71 #include "gstavimux.h"
72
73 GST_DEBUG_CATEGORY_STATIC (avimux_debug);
74 #define GST_CAT_DEFAULT avimux_debug
75
76 enum
77 {
78   ARG_0,
79   ARG_BIGFILE
80 };
81
82 #define DEFAULT_BIGFILE TRUE
83
84 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
85     GST_PAD_SRC,
86     GST_PAD_ALWAYS,
87     GST_STATIC_CAPS ("video/x-msvideo")
88     );
89
90 static GstStaticPadTemplate video_sink_factory =
91     GST_STATIC_PAD_TEMPLATE ("video_%d",
92     GST_PAD_SINK,
93     GST_PAD_REQUEST,
94     GST_STATIC_CAPS ("video/x-raw-yuv, "
95         "format = (fourcc) { YUY2, I420 }, "
96         "width = (int) [ 16, 4096 ], "
97         "height = (int) [ 16, 4096 ], "
98         "framerate = (fraction) [ 0, MAX ]; "
99         "image/jpeg, "
100         "width = (int) [ 16, 4096 ], "
101         "height = (int) [ 16, 4096 ], "
102         "framerate = (fraction) [ 0, MAX ]; "
103         "video/x-divx, "
104         "width = (int) [ 16, 4096 ], "
105         "height = (int) [ 16, 4096 ], "
106         "framerate = (fraction) [ 0, MAX ], "
107         "divxversion = (int) [ 3, 5 ]; "
108         "video/x-xvid, "
109         "width = (int) [ 16, 4096 ], "
110         "height = (int) [ 16, 4096 ], "
111         "framerate = (fraction) [ 0, MAX ]; "
112         "video/x-3ivx, "
113         "width = (int) [ 16, 4096 ], "
114         "height = (int) [ 16, 4096 ], "
115         "framerate = (fraction) [ 0, MAX ]; "
116         "video/x-msmpeg, "
117         "width = (int) [ 16, 4096 ], "
118         "height = (int) [ 16, 4096 ], "
119         "framerate = (fraction) [ 0, MAX ], "
120         "msmpegversion = (int) [ 41, 43 ]; "
121         "video/mpeg, "
122         "width = (int) [ 16, 4096 ], "
123         "height = (int) [ 16, 4096 ], "
124         "framerate = (fraction) [ 0, MAX ], "
125         "mpegversion = (int) { 1, 2, 4}, "
126         "systemstream = (boolean) FALSE; "
127         "video/x-h263, "
128         "width = (int) [ 16, 4096 ], "
129         "height = (int) [ 16, 4096 ], "
130         "framerate = (fraction) [ 0, MAX ]; "
131         "video/x-h264, "
132         "stream-format = (string) byte-stream, "
133         "alignment = (string) au, "
134         "width = (int) [ 16, 4096 ], "
135         "height = (int) [ 16, 4096 ], "
136         "framerate = (fraction) [ 0, MAX ]; "
137         "video/x-dv, "
138         "width = (int) 720, "
139         "height = (int) { 576, 480 }, "
140         "framerate = (fraction) [ 0, MAX ], "
141         "systemstream = (boolean) FALSE; "
142         "video/x-huffyuv, "
143         "width = (int) [ 16, 4096 ], "
144         "height = (int) [ 16, 4096 ], " "framerate = (fraction) [ 0, MAX ];"
145         "video/x-wmv, "
146         "width = (int) [ 16, 4096 ], "
147         "height = (int) [ 16, 4096 ], " "framerate = (fraction) [ 0, MAX ], "
148         "wmvversion = (int) [ 1, 3];"
149         "image/x-jpc, "
150         "width = (int) [ 1, 2147483647 ], "
151         "height = (int) [ 1, 2147483647 ], "
152         "framerate = (fraction) [ 0, MAX ];"
153         "video/x-vp8, "
154         "width = (int) [ 1, 2147483647 ], "
155         "height = (int) [ 1, 2147483647 ], "
156         "framerate = (fraction) [ 0, MAX ]")
157     );
158
159 static GstStaticPadTemplate audio_sink_factory =
160     GST_STATIC_PAD_TEMPLATE ("audio_%d",
161     GST_PAD_SINK,
162     GST_PAD_REQUEST,
163     GST_STATIC_CAPS ("audio/x-raw-int, "
164         "endianness = (int) LITTLE_ENDIAN, "
165         "signed = (boolean) { TRUE, FALSE }, "
166         "width = (int) { 8, 16 }, "
167         "depth = (int) { 8, 16 }, "
168         "rate = (int) [ 1000, 96000 ], "
169         "channels = (int) [ 1, 2 ]; "
170         "audio/mpeg, "
171         "mpegversion = (int) 1, "
172         "layer = (int) [ 1, 3 ], "
173         "rate = (int) [ 1000, 96000 ], " "channels = (int) [ 1, 2 ]; "
174         "audio/mpeg, "
175         "mpegversion = (int) 4, "
176         "stream-format = (string) raw, "
177         "rate = (int) [ 1000, 96000 ], " "channels = (int) [ 1, 2 ]; "
178 /*#if 0 VC6 doesn't support #if here ...
179         "audio/x-vorbis, "
180         "rate = (int) [ 1000, 96000 ], " "channels = (int) [ 1, 2 ]; "
181 #endif*/
182         "audio/x-ac3, "
183         "rate = (int) [ 1000, 96000 ], " "channels = (int) [ 1, 2 ]; "
184         "audio/x-alaw, "
185         "rate = (int) [ 1000, 48000 ], " "channels = (int) [ 1, 2 ]; "
186         "audio/x-mulaw, "
187         "rate = (int) [ 1000, 48000 ], " "channels = (int) [ 1, 2 ]; "
188         "audio/x-wma, "
189         "rate = (int) [ 1000, 96000 ], " "channels = (int) [ 1, 2 ], "
190         "wmaversion = (int) [ 1, 2 ] ")
191     );
192
193 static void gst_avi_mux_base_init (gpointer g_class);
194 static void gst_avi_mux_class_init (GstAviMuxClass * klass);
195 static void gst_avi_mux_init (GstAviMux * avimux);
196 static void gst_avi_mux_pad_reset (GstAviPad * avipad, gboolean free);
197
198 static GstFlowReturn gst_avi_mux_collect_pads (GstCollectPads * pads,
199     GstAviMux * avimux);
200 static gboolean gst_avi_mux_handle_event (GstPad * pad, GstEvent * event);
201 static GstPad *gst_avi_mux_request_new_pad (GstElement * element,
202     GstPadTemplate * templ, const gchar * name);
203 static void gst_avi_mux_release_pad (GstElement * element, GstPad * pad);
204 static void gst_avi_mux_set_property (GObject * object,
205     guint prop_id, const GValue * value, GParamSpec * pspec);
206 static void gst_avi_mux_get_property (GObject * object,
207     guint prop_id, GValue * value, GParamSpec * pspec);
208 static GstStateChangeReturn gst_avi_mux_change_state (GstElement * element,
209     GstStateChange transition);
210
211 static GstElementClass *parent_class = NULL;
212
213 GType
214 gst_avi_mux_get_type (void)
215 {
216   static GType avimux_type = 0;
217
218   if (!avimux_type) {
219     static const GTypeInfo avimux_info = {
220       sizeof (GstAviMuxClass),
221       gst_avi_mux_base_init,
222       NULL,
223       (GClassInitFunc) gst_avi_mux_class_init,
224       NULL,
225       NULL,
226       sizeof (GstAviMux),
227       0,
228       (GInstanceInitFunc) gst_avi_mux_init,
229     };
230     static const GInterfaceInfo tag_setter_info = {
231       NULL,
232       NULL,
233       NULL
234     };
235
236     avimux_type =
237         g_type_register_static (GST_TYPE_ELEMENT, "GstAviMux", &avimux_info, 0);
238     g_type_add_interface_static (avimux_type, GST_TYPE_TAG_SETTER,
239         &tag_setter_info);
240   }
241   return avimux_type;
242 }
243
244 static void
245 gst_avi_mux_base_init (gpointer g_class)
246 {
247   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
248
249   gst_element_class_add_static_pad_template (element_class, &src_factory);
250   gst_element_class_add_static_pad_template (element_class,
251       &audio_sink_factory);
252   gst_element_class_add_static_pad_template (element_class,
253       &video_sink_factory);
254
255   gst_element_class_set_details_simple (element_class, "Avi muxer",
256       "Codec/Muxer",
257       "Muxes audio and video into an avi stream",
258       "GStreamer maintainers <gstreamer-devel@lists.sourceforge.net>");
259
260   GST_DEBUG_CATEGORY_INIT (avimux_debug, "avimux", 0, "Muxer for AVI streams");
261 }
262
263 static void
264 gst_avi_mux_finalize (GObject * object)
265 {
266   GstAviMux *mux = GST_AVI_MUX (object);
267   GSList *node;
268
269   /* completely free each sinkpad */
270   node = mux->sinkpads;
271   while (node) {
272     GstAviPad *avipad = (GstAviPad *) node->data;
273
274     node = node->next;
275
276     gst_avi_mux_pad_reset (avipad, TRUE);
277     g_free (avipad);
278   }
279   g_slist_free (mux->sinkpads);
280   mux->sinkpads = NULL;
281
282   g_free (mux->idx);
283   mux->idx = NULL;
284
285   gst_object_unref (mux->collect);
286
287   G_OBJECT_CLASS (parent_class)->finalize (object);
288 }
289
290 static void
291 gst_avi_mux_class_init (GstAviMuxClass * klass)
292 {
293   GObjectClass *gobject_class;
294   GstElementClass *gstelement_class;
295
296   gobject_class = (GObjectClass *) klass;
297   gstelement_class = (GstElementClass *) klass;
298
299   parent_class = g_type_class_peek_parent (klass);
300
301   gobject_class->get_property = gst_avi_mux_get_property;
302   gobject_class->set_property = gst_avi_mux_set_property;
303   gobject_class->finalize = gst_avi_mux_finalize;
304
305   g_object_class_install_property (gobject_class, ARG_BIGFILE,
306       g_param_spec_boolean ("bigfile", "Bigfile Support (>2GB)",
307           "Support for openDML-2.0 (big) AVI files", DEFAULT_BIGFILE,
308           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
309
310   gstelement_class->request_new_pad =
311       GST_DEBUG_FUNCPTR (gst_avi_mux_request_new_pad);
312   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_avi_mux_release_pad);
313   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_avi_mux_change_state);
314 }
315
316 /* reset pad to initial state
317  * free - if true, release all, not only stream related, data */
318 static void
319 gst_avi_mux_pad_reset (GstAviPad * avipad, gboolean free)
320 {
321   /* generic part */
322   memset (&(avipad->hdr), 0, sizeof (gst_riff_strh));
323
324   memset (&(avipad->idx[0]), 0, sizeof (avipad->idx));
325
326   if (free) {
327     g_free (avipad->tag);
328     avipad->tag = NULL;
329     g_free (avipad->idx_tag);
330     avipad->idx_tag = NULL;
331   }
332
333   if (avipad->is_video) {
334     GstAviVideoPad *vidpad = (GstAviVideoPad *) avipad;
335
336     avipad->hdr.type = GST_MAKE_FOURCC ('v', 'i', 'd', 's');
337     if (vidpad->vids_codec_data) {
338       gst_buffer_unref (vidpad->vids_codec_data);
339       vidpad->vids_codec_data = NULL;
340     }
341
342     if (vidpad->prepend_buffer) {
343       gst_buffer_unref (vidpad->prepend_buffer);
344       vidpad->prepend_buffer = NULL;
345     }
346
347     memset (&(vidpad->vids), 0, sizeof (gst_riff_strf_vids));
348     memset (&(vidpad->vprp), 0, sizeof (gst_riff_vprp));
349   } else {
350     GstAviAudioPad *audpad = (GstAviAudioPad *) avipad;
351
352     audpad->samples = 0;
353
354     avipad->hdr.type = GST_MAKE_FOURCC ('a', 'u', 'd', 's');
355     if (audpad->auds_codec_data) {
356       gst_buffer_unref (audpad->auds_codec_data);
357       audpad->auds_codec_data = NULL;
358     }
359
360     memset (&(audpad->auds), 0, sizeof (gst_riff_strf_auds));
361   }
362 }
363
364 static void
365 gst_avi_mux_reset (GstAviMux * avimux)
366 {
367   GSList *node, *newlist = NULL;
368
369   /* free and reset each sinkpad */
370   node = avimux->sinkpads;
371   while (node) {
372     GstAviPad *avipad = (GstAviPad *) node->data;
373
374     node = node->next;
375
376     gst_avi_mux_pad_reset (avipad, FALSE);
377     /* if this pad has collectdata, keep it, otherwise dump it completely */
378     if (avipad->collect)
379       newlist = g_slist_append (newlist, avipad);
380     else {
381       gst_avi_mux_pad_reset (avipad, TRUE);
382       g_free (avipad);
383     }
384   }
385
386   /* free the old list of sinkpads, only keep the real collecting ones */
387   g_slist_free (avimux->sinkpads);
388   avimux->sinkpads = newlist;
389
390   /* avi data */
391   avimux->num_frames = 0;
392   memset (&(avimux->avi_hdr), 0, sizeof (gst_riff_avih));
393   avimux->avi_hdr.max_bps = 10000000;
394   avimux->codec_data_size = 0;
395
396   if (avimux->tags_snap) {
397     gst_tag_list_free (avimux->tags_snap);
398     avimux->tags_snap = NULL;
399   }
400
401   g_free (avimux->idx);
402   avimux->idx = NULL;
403
404   /* state info */
405   avimux->write_header = TRUE;
406
407   /* tags */
408   gst_tag_setter_reset_tags (GST_TAG_SETTER (avimux));
409 }
410
411 static void
412 gst_avi_mux_init (GstAviMux * avimux)
413 {
414   avimux->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
415   gst_pad_use_fixed_caps (avimux->srcpad);
416   gst_element_add_pad (GST_ELEMENT (avimux), avimux->srcpad);
417
418   /* property */
419   avimux->enable_large_avi = DEFAULT_BIGFILE;
420
421   avimux->collect = gst_collect_pads_new ();
422   gst_collect_pads_set_function (avimux->collect,
423       (GstCollectPadsFunction) (GST_DEBUG_FUNCPTR (gst_avi_mux_collect_pads)),
424       avimux);
425
426   /* set to clean state */
427   gst_avi_mux_reset (avimux);
428 }
429
430 static gboolean
431 gst_avi_mux_vidsink_set_caps (GstPad * pad, GstCaps * vscaps)
432 {
433   GstAviMux *avimux;
434   GstAviVideoPad *avipad;
435   GstAviCollectData *collect_pad;
436   GstStructure *structure;
437   const gchar *mimetype;
438   const GValue *fps, *par;
439   const GValue *codec_data;
440   gint width, height;
441   gint par_n, par_d;
442   gboolean codec_data_in_headers = TRUE;
443
444   avimux = GST_AVI_MUX (gst_pad_get_parent (pad));
445
446   /* find stream data */
447   collect_pad = (GstAviCollectData *) gst_pad_get_element_private (pad);
448   g_assert (collect_pad);
449   avipad = (GstAviVideoPad *) collect_pad->avipad;
450   g_assert (avipad);
451   g_assert (avipad->parent.is_video);
452   g_assert (avipad->parent.hdr.type == GST_MAKE_FOURCC ('v', 'i', 'd', 's'));
453
454   GST_DEBUG_OBJECT (avimux, "%s:%s, caps=%" GST_PTR_FORMAT,
455       GST_DEBUG_PAD_NAME (pad), vscaps);
456
457   structure = gst_caps_get_structure (vscaps, 0);
458   mimetype = gst_structure_get_name (structure);
459
460   /* global */
461   avipad->vids.size = sizeof (gst_riff_strf_vids);
462   avipad->vids.planes = 1;
463   if (!gst_structure_get_int (structure, "width", &width) ||
464       !gst_structure_get_int (structure, "height", &height)) {
465     goto refuse_caps;
466   }
467
468   avipad->vids.width = width;
469   avipad->vids.height = height;
470
471   fps = gst_structure_get_value (structure, "framerate");
472   if (fps == NULL || !GST_VALUE_HOLDS_FRACTION (fps))
473     goto refuse_caps;
474
475   avipad->parent.hdr.rate = gst_value_get_fraction_numerator (fps);
476   avipad->parent.hdr.scale = gst_value_get_fraction_denominator (fps);
477
478   /* (pixel) aspect ratio data, if any */
479   par = gst_structure_get_value (structure, "pixel-aspect-ratio");
480   /* only use video properties header if there is non-trivial aspect info */
481   if (par && GST_VALUE_HOLDS_FRACTION (par) &&
482       ((par_n = gst_value_get_fraction_numerator (par)) !=
483           (par_d = gst_value_get_fraction_denominator (par)))) {
484     GValue to_ratio = { 0, };
485     guint ratio_n, ratio_d;
486
487     /* some fraction voodoo to obtain simplest possible ratio */
488     g_value_init (&to_ratio, GST_TYPE_FRACTION);
489     gst_value_set_fraction (&to_ratio, width * par_n, height * par_d);
490     ratio_n = gst_value_get_fraction_numerator (&to_ratio);
491     ratio_d = gst_value_get_fraction_denominator (&to_ratio);
492     GST_DEBUG_OBJECT (avimux, "generating vprp data with aspect ratio %d/%d",
493         ratio_n, ratio_d);
494     /* simply fill in */
495     avipad->vprp.vert_rate = avipad->parent.hdr.rate / avipad->parent.hdr.scale;
496     avipad->vprp.hor_t_total = width;
497     avipad->vprp.vert_lines = height;
498     avipad->vprp.aspect = (ratio_n) << 16 | (ratio_d & 0xffff);
499     avipad->vprp.width = width;
500     avipad->vprp.height = height;
501     avipad->vprp.fields = 1;
502     avipad->vprp.field_info[0].compressed_bm_height = height;
503     avipad->vprp.field_info[0].compressed_bm_width = width;
504     avipad->vprp.field_info[0].valid_bm_height = height;
505     avipad->vprp.field_info[0].valid_bm_width = width;
506   }
507
508   if (!strcmp (mimetype, "video/x-raw-yuv")) {
509     guint32 format;
510
511     gst_structure_get_fourcc (structure, "format", &format);
512     avipad->vids.compression = format;
513     switch (format) {
514       case GST_MAKE_FOURCC ('Y', 'U', 'Y', '2'):
515         avipad->vids.bit_cnt = 16;
516         break;
517       case GST_MAKE_FOURCC ('I', '4', '2', '0'):
518         avipad->vids.bit_cnt = 12;
519         break;
520     }
521   } else {
522     avipad->vids.bit_cnt = 24;
523     avipad->vids.compression = 0;
524
525     /* find format */
526     if (!strcmp (mimetype, "video/x-huffyuv")) {
527       avipad->vids.compression = GST_MAKE_FOURCC ('H', 'F', 'Y', 'U');
528     } else if (!strcmp (mimetype, "image/jpeg")) {
529       avipad->vids.compression = GST_MAKE_FOURCC ('M', 'J', 'P', 'G');
530     } else if (!strcmp (mimetype, "video/x-divx")) {
531       gint divxversion;
532
533       gst_structure_get_int (structure, "divxversion", &divxversion);
534       switch (divxversion) {
535         case 3:
536           avipad->vids.compression = GST_MAKE_FOURCC ('D', 'I', 'V', '3');
537           break;
538         case 4:
539           avipad->vids.compression = GST_MAKE_FOURCC ('D', 'I', 'V', 'X');
540           break;
541         case 5:
542           avipad->vids.compression = GST_MAKE_FOURCC ('D', 'X', '5', '0');
543           break;
544       }
545     } else if (!strcmp (mimetype, "video/x-xvid")) {
546       avipad->vids.compression = GST_MAKE_FOURCC ('X', 'V', 'I', 'D');
547     } else if (!strcmp (mimetype, "video/x-3ivx")) {
548       avipad->vids.compression = GST_MAKE_FOURCC ('3', 'I', 'V', '2');
549     } else if (gst_structure_has_name (structure, "video/x-msmpeg")) {
550       gint msmpegversion;
551
552       gst_structure_get_int (structure, "msmpegversion", &msmpegversion);
553       switch (msmpegversion) {
554         case 41:
555           avipad->vids.compression = GST_MAKE_FOURCC ('M', 'P', 'G', '4');
556           break;
557         case 42:
558           avipad->vids.compression = GST_MAKE_FOURCC ('M', 'P', '4', '2');
559           break;
560         case 43:
561           avipad->vids.compression = GST_MAKE_FOURCC ('M', 'P', '4', '3');
562           break;
563         default:
564           GST_INFO ("unhandled msmpegversion : %d, fall back to fourcc=MPEG",
565               msmpegversion);
566           avipad->vids.compression = GST_MAKE_FOURCC ('M', 'P', 'E', 'G');
567           break;
568       }
569     } else if (!strcmp (mimetype, "video/x-dv")) {
570       avipad->vids.compression = GST_MAKE_FOURCC ('D', 'V', 'S', 'D');
571     } else if (!strcmp (mimetype, "video/x-h263")) {
572       avipad->vids.compression = GST_MAKE_FOURCC ('H', '2', '6', '3');
573     } else if (!strcmp (mimetype, "video/x-h264")) {
574       avipad->vids.compression = GST_MAKE_FOURCC ('H', '2', '6', '4');
575     } else if (!strcmp (mimetype, "video/mpeg")) {
576       gint mpegversion;
577
578       gst_structure_get_int (structure, "mpegversion", &mpegversion);
579
580       switch (mpegversion) {
581         case 2:
582           avipad->vids.compression = GST_MAKE_FOURCC ('M', 'P', 'G', '2');
583           break;
584         case 4:
585           /* mplayer/ffmpeg might not work with DIVX, but with FMP4 */
586           avipad->vids.compression = GST_MAKE_FOURCC ('D', 'I', 'V', 'X');
587
588           /* DIVX/XVID in AVI store the codec_data chunk as part of the
589              first data buffer. So for this case, we prepend the codec_data
590              blob (if any) to that first buffer */
591           codec_data_in_headers = FALSE;
592           break;
593         default:
594           GST_INFO ("unhandled mpegversion : %d, fall back to fourcc=MPEG",
595               mpegversion);
596           avipad->vids.compression = GST_MAKE_FOURCC ('M', 'P', 'E', 'G');
597           break;
598       }
599     } else if (!strcmp (mimetype, "video/x-wmv")) {
600       gint wmvversion;
601
602       if (gst_structure_get_int (structure, "wmvversion", &wmvversion)) {
603         switch (wmvversion) {
604           case 1:
605             avipad->vids.compression = GST_MAKE_FOURCC ('W', 'M', 'V', '1');
606             break;
607           case 2:
608             avipad->vids.compression = GST_MAKE_FOURCC ('W', 'M', 'V', '2');
609             break;
610           case 3:
611             avipad->vids.compression = GST_MAKE_FOURCC ('W', 'M', 'V', '3');
612           default:
613             break;
614         }
615       }
616     } else if (!strcmp (mimetype, "image/x-jpc")) {
617       avipad->vids.compression = GST_MAKE_FOURCC ('M', 'J', '2', 'C');
618     } else if (!strcmp (mimetype, "video/x-vp8")) {
619       avipad->vids.compression = GST_MAKE_FOURCC ('V', 'P', '8', '0');
620     }
621
622     if (!avipad->vids.compression)
623       goto refuse_caps;
624   }
625
626   /* codec initialization data, if any */
627   codec_data = gst_structure_get_value (structure, "codec_data");
628   if (codec_data) {
629     if (codec_data_in_headers) {
630       avipad->vids_codec_data = gst_value_get_buffer (codec_data);
631       gst_buffer_ref (avipad->vids_codec_data);
632       /* keep global track of size */
633       avimux->codec_data_size += GST_BUFFER_SIZE (avipad->vids_codec_data);
634     } else {
635       avipad->prepend_buffer =
636           gst_buffer_ref (gst_value_get_buffer (codec_data));
637     }
638   }
639
640   avipad->parent.hdr.fcc_handler = avipad->vids.compression;
641   avipad->vids.image_size = avipad->vids.height * avipad->vids.width;
642   /* hm, maybe why avi only handles one stream well ... */
643   avimux->avi_hdr.width = avipad->vids.width;
644   avimux->avi_hdr.height = avipad->vids.height;
645   avimux->avi_hdr.us_frame = 1000000. * avipad->parent.hdr.scale /
646       avipad->parent.hdr.rate;
647
648   gst_object_unref (avimux);
649   return TRUE;
650
651 refuse_caps:
652   {
653     GST_WARNING_OBJECT (avimux, "refused caps %" GST_PTR_FORMAT, vscaps);
654     gst_object_unref (avimux);
655     return FALSE;
656   }
657 }
658
659 static GstFlowReturn
660 gst_avi_mux_audsink_scan_mpeg_audio (GstAviMux * avimux, GstAviPad * avipad,
661     GstBuffer * buffer)
662 {
663   guint8 *data;
664   guint size;
665   guint spf;
666   guint32 header;
667   gulong layer;
668   gulong version;
669   gint lsf, mpg25;
670
671   data = GST_BUFFER_DATA (buffer);
672   size = GST_BUFFER_SIZE (buffer);
673
674   if (size < 4)
675     goto not_parsed;
676
677   header = GST_READ_UINT32_BE (data);
678
679   if ((header & 0xffe00000) != 0xffe00000)
680     goto not_parsed;
681
682   /* thanks go to mp3parse */
683   if (header & (1 << 20)) {
684     lsf = (header & (1 << 19)) ? 0 : 1;
685     mpg25 = 0;
686   } else {
687     lsf = 1;
688     mpg25 = 1;
689   }
690
691   version = 1 + lsf + mpg25;
692   layer = 4 - ((header >> 17) & 0x3);
693
694   /* see http://www.codeproject.com/audio/MPEGAudioInfo.asp */
695   if (layer == 1)
696     spf = 384;
697   else if (layer == 2)
698     spf = 1152;
699   else if (version == 1) {
700     spf = 1152;
701   } else {
702     /* MPEG-2 or "2.5" */
703     spf = 576;
704   }
705
706   if (G_UNLIKELY (avipad->hdr.scale <= 1))
707     avipad->hdr.scale = spf;
708   else if (G_UNLIKELY (avipad->hdr.scale != spf)) {
709     GST_WARNING_OBJECT (avimux, "input mpeg audio has varying frame size");
710     goto cbr_fallback;
711   }
712
713   return GST_FLOW_OK;
714
715   /* EXITS */
716 not_parsed:
717   {
718     GST_WARNING_OBJECT (avimux, "input mpeg audio is not parsed");
719     /* fall-through */
720   }
721 cbr_fallback:
722   {
723     GST_WARNING_OBJECT (avimux, "falling back to CBR muxing");
724     avipad->hdr.scale = 1;
725     /* no need to check further */
726     avipad->hook = NULL;
727     return GST_FLOW_OK;
728   }
729 }
730
731 static void
732 gst_avi_mux_audsink_set_fields (GstAviMux * avimux, GstAviAudioPad * avipad)
733 {
734   if (avipad->parent.hdr.scale > 1) {
735     /* vbr case: fixed duration per frame/chunk */
736     avipad->parent.hdr.rate = avipad->auds.rate;
737     avipad->parent.hdr.samplesize = 0;
738     /* FIXME ?? some rumours say this should be largest audio chunk size */
739     avipad->auds.blockalign = avipad->parent.hdr.scale;
740   } else {
741     /* by spec, hdr.rate is av_bps related, is calculated that way in stop_file,
742      * and reduces to sample rate in PCM like cases */
743     avipad->parent.hdr.rate = avipad->auds.av_bps / avipad->auds.blockalign;
744     avipad->parent.hdr.samplesize = avipad->auds.blockalign;
745     avipad->parent.hdr.scale = 1;
746   }
747 }
748
749 static gboolean
750 gst_avi_mux_audsink_set_caps (GstPad * pad, GstCaps * vscaps)
751 {
752   GstAviMux *avimux;
753   GstAviAudioPad *avipad;
754   GstAviCollectData *collect_pad;
755   GstStructure *structure;
756   const gchar *mimetype;
757   const GValue *codec_data;
758   gint channels, rate;
759
760   avimux = GST_AVI_MUX (gst_pad_get_parent (pad));
761
762   /* find stream data */
763   collect_pad = (GstAviCollectData *) gst_pad_get_element_private (pad);
764   g_assert (collect_pad);
765   avipad = (GstAviAudioPad *) collect_pad->avipad;
766   g_assert (avipad);
767   g_assert (!avipad->parent.is_video);
768   g_assert (avipad->parent.hdr.type == GST_MAKE_FOURCC ('a', 'u', 'd', 's'));
769
770   GST_DEBUG_OBJECT (avimux, "%s:%s, caps=%" GST_PTR_FORMAT,
771       GST_DEBUG_PAD_NAME (pad), vscaps);
772
773   structure = gst_caps_get_structure (vscaps, 0);
774   mimetype = gst_structure_get_name (structure);
775
776   /* we want these for all */
777   if (!gst_structure_get_int (structure, "channels", &channels) ||
778       !gst_structure_get_int (structure, "rate", &rate)) {
779     goto refuse_caps;
780   }
781
782   avipad->auds.channels = channels;
783   avipad->auds.rate = rate;
784
785   /* codec initialization data, if any */
786   codec_data = gst_structure_get_value (structure, "codec_data");
787   if (codec_data) {
788     avipad->auds_codec_data = gst_value_get_buffer (codec_data);
789     gst_buffer_ref (avipad->auds_codec_data);
790     /* keep global track of size */
791     avimux->codec_data_size += GST_BUFFER_SIZE (avipad->auds_codec_data);
792   }
793
794   if (!strcmp (mimetype, "audio/x-raw-int")) {
795     gint width, depth;
796     gboolean signedness;
797
798     avipad->auds.format = GST_RIFF_WAVE_FORMAT_PCM;
799
800     if (!gst_structure_get_int (structure, "width", &width) ||
801         !gst_structure_get_int (structure, "depth", &depth) ||
802         !gst_structure_get_boolean (structure, "signed", &signedness)) {
803       GST_DEBUG_OBJECT (avimux,
804           "broken caps, width/depth/signed field missing");
805       goto refuse_caps;
806     }
807
808     /* no clear place to put different values for these while keeping to spec */
809     if (width != depth) {
810       GST_DEBUG_OBJECT (avimux, "width must be same as depth!");
811       goto refuse_caps;
812     }
813
814     /* because that's the way the caps will be recreated from riff data */
815     if ((width == 8 && signedness) || (width == 16 && !signedness)) {
816       GST_DEBUG_OBJECT (avimux,
817           "8-bit PCM must be unsigned, 16-bit PCM signed");
818       goto refuse_caps;
819     }
820
821     avipad->auds.blockalign = width;
822     avipad->auds.size = (width == 8) ? 8 : depth;
823
824     /* set some more info straight */
825     avipad->auds.blockalign /= 8;
826     avipad->auds.blockalign *= avipad->auds.channels;
827     avipad->auds.av_bps = avipad->auds.blockalign * avipad->auds.rate;
828   } else {
829     avipad->auds.format = 0;
830     /* set some defaults */
831     avipad->auds.blockalign = 1;
832     avipad->auds.av_bps = 0;
833     avipad->auds.size = 16;
834
835     if (!strcmp (mimetype, "audio/mpeg")) {
836       gint mpegversion;
837
838       gst_structure_get_int (structure, "mpegversion", &mpegversion);
839       switch (mpegversion) {
840         case 1:{
841           gint layer = 3;
842           gboolean parsed = FALSE;
843
844           gst_structure_get_int (structure, "layer", &layer);
845           gst_structure_get_boolean (structure, "parsed", &parsed);
846           switch (layer) {
847             case 3:
848               avipad->auds.format = GST_RIFF_WAVE_FORMAT_MPEGL3;
849               break;
850             case 1:
851             case 2:
852               avipad->auds.format = GST_RIFF_WAVE_FORMAT_MPEGL12;
853               break;
854           }
855           if (parsed) {
856             /* treat as VBR, should also cover CBR case;
857              * setup hook to parse frame header and determine spf */
858             avipad->parent.hook = gst_avi_mux_audsink_scan_mpeg_audio;
859           } else {
860             GST_WARNING_OBJECT (avimux, "unparsed MPEG audio input (?), "
861                 "doing CBR muxing");
862           }
863           break;
864         }
865         case 4:
866         {
867           GstBuffer *codec_data_buf = avipad->auds_codec_data;
868           const gchar *stream_format;
869           guint codec;
870
871           stream_format = gst_structure_get_string (structure, "stream-format");
872           if (stream_format) {
873             if (strcmp (stream_format, "raw") != 0) {
874               GST_WARNING_OBJECT (avimux, "AAC's stream format '%s' is not "
875                   "supported, please use 'raw'", stream_format);
876               break;
877             }
878           } else {
879             GST_WARNING_OBJECT (avimux, "AAC's stream-format not specified, "
880                 "assuming 'raw'");
881           }
882
883           /* vbr case needs some special handling */
884           if (!codec_data_buf || GST_BUFFER_SIZE (codec_data_buf) < 2) {
885             GST_WARNING_OBJECT (avimux, "no (valid) codec_data for AAC audio");
886             break;
887           }
888           avipad->auds.format = GST_RIFF_WAVE_FORMAT_AAC;
889           /* need to determine frame length */
890           codec = GST_READ_UINT16_BE (GST_BUFFER_DATA (codec_data_buf));
891           avipad->parent.hdr.scale = (codec & 0x4) ? 960 : 1024;
892           break;
893         }
894       }
895     } else if (!strcmp (mimetype, "audio/x-vorbis")) {
896       avipad->auds.format = GST_RIFF_WAVE_FORMAT_VORBIS3;
897     } else if (!strcmp (mimetype, "audio/x-ac3")) {
898       avipad->auds.format = GST_RIFF_WAVE_FORMAT_A52;
899     } else if (!strcmp (mimetype, "audio/x-alaw")) {
900       avipad->auds.format = GST_RIFF_WAVE_FORMAT_ALAW;
901       avipad->auds.size = 8;
902       avipad->auds.blockalign = avipad->auds.channels;
903       avipad->auds.av_bps = avipad->auds.blockalign * avipad->auds.rate;
904     } else if (!strcmp (mimetype, "audio/x-mulaw")) {
905       avipad->auds.format = GST_RIFF_WAVE_FORMAT_MULAW;
906       avipad->auds.size = 8;
907       avipad->auds.blockalign = avipad->auds.channels;
908       avipad->auds.av_bps = avipad->auds.blockalign * avipad->auds.rate;
909     } else if (!strcmp (mimetype, "audio/x-wma")) {
910       gint version;
911       gint bitrate;
912       gint block_align;
913
914       if (gst_structure_get_int (structure, "wmaversion", &version)) {
915         switch (version) {
916           case 1:
917             avipad->auds.format = GST_RIFF_WAVE_FORMAT_WMAV1;
918             break;
919           case 2:
920             avipad->auds.format = GST_RIFF_WAVE_FORMAT_WMAV2;
921             break;
922           default:
923             break;
924         }
925       }
926
927       if (avipad->auds.format != 0) {
928         if (gst_structure_get_int (structure, "block_align", &block_align)) {
929           avipad->auds.blockalign = block_align;
930         }
931         if (gst_structure_get_int (structure, "bitrate", &bitrate)) {
932           avipad->auds.av_bps = bitrate / 8;
933         }
934       }
935     }
936   }
937
938   if (!avipad->auds.format)
939     goto refuse_caps;
940
941   avipad->parent.hdr.fcc_handler = avipad->auds.format;
942   gst_avi_mux_audsink_set_fields (avimux, avipad);
943
944   gst_object_unref (avimux);
945   return TRUE;
946
947 refuse_caps:
948   {
949     GST_WARNING_OBJECT (avimux, "refused caps %" GST_PTR_FORMAT, vscaps);
950     gst_object_unref (avimux);
951     return FALSE;
952   }
953 }
954
955
956 static GstPad *
957 gst_avi_mux_request_new_pad (GstElement * element,
958     GstPadTemplate * templ, const gchar * req_name)
959 {
960   GstAviMux *avimux;
961   GstPad *newpad;
962   GstAviPad *avipad;
963   GstElementClass *klass;
964   gchar *name = NULL;
965   const gchar *pad_name = NULL;
966   GstPadSetCapsFunction setcapsfunc = NULL;
967   gint pad_id;
968
969   g_return_val_if_fail (templ != NULL, NULL);
970
971   if (templ->direction != GST_PAD_SINK)
972     goto wrong_direction;
973
974   g_return_val_if_fail (GST_IS_AVI_MUX (element), NULL);
975   avimux = GST_AVI_MUX (element);
976
977   if (!avimux->write_header)
978     goto too_late;
979
980   klass = GST_ELEMENT_GET_CLASS (element);
981
982   /* FIXME-0.11: use %d instead of %02d for pad_names */
983
984   if (templ == gst_element_class_get_pad_template (klass, "audio_%d")) {
985     /* don't mix named and unnamed pads, if the pad already exists we fail when
986      * trying to add it */
987     if (req_name != NULL && sscanf (req_name, "audio_%02d", &pad_id) == 1) {
988       pad_name = req_name;
989     } else {
990       name = g_strdup_printf ("audio_%02d", avimux->audio_pads++);
991       pad_name = name;
992     }
993     setcapsfunc = GST_DEBUG_FUNCPTR (gst_avi_mux_audsink_set_caps);
994
995     /* init pad specific data */
996     avipad = g_malloc0 (sizeof (GstAviAudioPad));
997     avipad->is_video = FALSE;
998     avipad->hdr.type = GST_MAKE_FOURCC ('a', 'u', 'd', 's');
999     /* audio goes last */
1000     avimux->sinkpads = g_slist_append (avimux->sinkpads, avipad);
1001   } else if (templ == gst_element_class_get_pad_template (klass, "video_%d")) {
1002     /* though streams are pretty generic and relatively self-contained,
1003      * some video info goes in a single avi header -and therefore mux struct-
1004      * so video restricted to one stream */
1005     if (avimux->video_pads > 0)
1006       goto too_many_video_pads;
1007
1008     /* setup pad */
1009     pad_name = "video_00";
1010     avimux->video_pads++;
1011     setcapsfunc = GST_DEBUG_FUNCPTR (gst_avi_mux_vidsink_set_caps);
1012
1013     /* init pad specific data */
1014     avipad = g_malloc0 (sizeof (GstAviVideoPad));
1015     avipad->is_video = TRUE;
1016     avipad->hdr.type = GST_MAKE_FOURCC ('v', 'i', 'd', 's');
1017     /* video goes first */
1018     avimux->sinkpads = g_slist_prepend (avimux->sinkpads, avipad);
1019   } else
1020     goto wrong_template;
1021
1022   newpad = gst_pad_new_from_template (templ, pad_name);
1023   gst_pad_set_setcaps_function (newpad, setcapsfunc);
1024
1025   g_free (name);
1026
1027   avipad->collect = gst_collect_pads_add_pad (avimux->collect,
1028       newpad, sizeof (GstAviCollectData));
1029   ((GstAviCollectData *) (avipad->collect))->avipad = avipad;
1030   /* FIXME: hacked way to override/extend the event function of
1031    * GstCollectPads; because it sets its own event function giving the
1032    * element no access to events */
1033   avimux->collect_event = (GstPadEventFunction) GST_PAD_EVENTFUNC (newpad);
1034   gst_pad_set_event_function (newpad,
1035       GST_DEBUG_FUNCPTR (gst_avi_mux_handle_event));
1036
1037   if (!gst_element_add_pad (element, newpad))
1038     goto pad_add_failed;
1039
1040   GST_DEBUG_OBJECT (newpad, "Added new request pad");
1041
1042   return newpad;
1043
1044   /* ERRORS */
1045 wrong_direction:
1046   {
1047     g_warning ("avimux: request pad that is not a SINK pad\n");
1048     return NULL;
1049   }
1050 too_late:
1051   {
1052     g_warning ("avimux: request pad cannot be added after streaming started\n");
1053     return NULL;
1054   }
1055 wrong_template:
1056   {
1057     g_warning ("avimux: this is not our template!\n");
1058     return NULL;
1059   }
1060 too_many_video_pads:
1061   {
1062     GST_WARNING_OBJECT (avimux, "Can only have one video stream");
1063     return NULL;
1064   }
1065 pad_add_failed:
1066   {
1067     GST_WARNING_OBJECT (avimux, "Adding the new pad '%s' failed", pad_name);
1068     gst_object_unref (newpad);
1069     return NULL;
1070   }
1071 }
1072
1073 static void
1074 gst_avi_mux_release_pad (GstElement * element, GstPad * pad)
1075 {
1076   GstAviMux *avimux = GST_AVI_MUX (element);
1077   GSList *node;
1078
1079   node = avimux->sinkpads;
1080   while (node) {
1081     GstAviPad *avipad = (GstAviPad *) node->data;
1082
1083     if (avipad->collect->pad == pad) {
1084       /* pad count should not be adjusted,
1085        * as it also represent number of streams present */
1086       avipad->collect = NULL;
1087       GST_DEBUG_OBJECT (avimux, "removed pad '%s'", GST_PAD_NAME (pad));
1088       gst_collect_pads_remove_pad (avimux->collect, pad);
1089       gst_element_remove_pad (element, pad);
1090       /* if not started yet, we can remove any sign this pad ever existed */
1091       /* in this case _start will take care of the real pad count */
1092       if (avimux->write_header) {
1093         avimux->sinkpads = g_slist_remove (avimux->sinkpads, avipad);
1094         gst_avi_mux_pad_reset (avipad, TRUE);
1095         g_free (avipad);
1096       }
1097       return;
1098     }
1099
1100     node = node->next;
1101   }
1102
1103   g_warning ("Unknown pad %s", GST_PAD_NAME (pad));
1104 }
1105
1106 static inline guint
1107 gst_avi_mux_start_chunk (GstByteWriter * bw, const gchar * tag, guint32 fourcc)
1108 {
1109   guint chunk_offset;
1110
1111   if (tag)
1112     gst_byte_writer_put_data (bw, (const guint8 *) tag, 4);
1113   else
1114     gst_byte_writer_put_uint32_le (bw, fourcc);
1115
1116   chunk_offset = gst_byte_writer_get_pos (bw);
1117   /* real chunk size comes later */
1118   gst_byte_writer_put_uint32_le (bw, 0);
1119
1120   return chunk_offset;
1121 }
1122
1123 static inline void
1124 gst_avi_mux_end_chunk (GstByteWriter * bw, guint chunk_offset)
1125 {
1126   guint size;
1127
1128   size = gst_byte_writer_get_pos (bw);
1129
1130   gst_byte_writer_set_pos (bw, chunk_offset);
1131   gst_byte_writer_put_uint32_le (bw, size - chunk_offset - 4);
1132   gst_byte_writer_set_pos (bw, size);
1133
1134   /* arrange for even padding */
1135   if (size & 1)
1136     gst_byte_writer_put_uint8 (bw, 0);
1137 }
1138
1139 /* maybe some of these functions should be moved to riff.h? */
1140
1141 static void
1142 gst_avi_mux_write_tag (const GstTagList * list, const gchar * tag,
1143     gpointer data)
1144 {
1145   const struct
1146   {
1147     guint32 fcc;
1148     const gchar *tag;
1149   } rifftags[] = {
1150     {
1151     GST_RIFF_INFO_IARL, GST_TAG_LOCATION}, {
1152     GST_RIFF_INFO_IART, GST_TAG_ARTIST}, {
1153     GST_RIFF_INFO_ICMT, GST_TAG_COMMENT}, {
1154     GST_RIFF_INFO_ICOP, GST_TAG_COPYRIGHT}, {
1155     GST_RIFF_INFO_ICRD, GST_TAG_DATE}, {
1156     GST_RIFF_INFO_IGNR, GST_TAG_GENRE}, {
1157     GST_RIFF_INFO_IKEY, GST_TAG_KEYWORDS}, {
1158     GST_RIFF_INFO_INAM, GST_TAG_TITLE}, {
1159     GST_RIFF_INFO_ISFT, GST_TAG_ENCODER}, {
1160     GST_RIFF_INFO_ISRC, GST_TAG_ISRC}, {
1161     0, NULL}
1162   };
1163   gint n;
1164   gchar *str;
1165   GstByteWriter *bw = data;
1166   guint chunk;
1167
1168   for (n = 0; rifftags[n].fcc != 0; n++) {
1169     if (!strcmp (rifftags[n].tag, tag) &&
1170         gst_tag_list_get_string (list, tag, &str) && str) {
1171       chunk = gst_avi_mux_start_chunk (bw, NULL, rifftags[n].fcc);
1172       gst_byte_writer_put_string (bw, str);
1173       gst_avi_mux_end_chunk (bw, chunk);
1174       g_free (str);
1175       break;
1176     }
1177   }
1178 }
1179
1180 static GstBuffer *
1181 gst_avi_mux_riff_get_avi_header (GstAviMux * avimux)
1182 {
1183   const GstTagList *tags;
1184   GstBuffer *buffer;
1185   gint size = 0;
1186   GstByteWriter bw;
1187   GSList *node;
1188   guint avih, riff, hdrl;
1189
1190   GST_DEBUG_OBJECT (avimux, "creating avi header, data_size %u, idx_size %u",
1191       avimux->data_size, avimux->idx_size);
1192
1193   if (avimux->tags_snap)
1194     tags = avimux->tags_snap;
1195   else {
1196     /* need to make snapshot of current state of tags to ensure the same set
1197      * is used next time around during header rewrite at the end */
1198     tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (avimux));
1199     if (tags)
1200       tags = avimux->tags_snap = gst_tag_list_copy (tags);
1201   }
1202
1203   gst_byte_writer_init_with_size (&bw, 1024, FALSE);
1204
1205   /* avi header metadata */
1206   riff = gst_avi_mux_start_chunk (&bw, "RIFF", 0);
1207   gst_byte_writer_put_data (&bw, (guint8 *) "AVI ", 4);
1208   hdrl = gst_avi_mux_start_chunk (&bw, "LIST", 0);
1209   gst_byte_writer_put_data (&bw, (guint8 *) "hdrl", 4);
1210
1211   avih = gst_avi_mux_start_chunk (&bw, "avih", 0);
1212   /* the AVI header itself */
1213   gst_byte_writer_put_uint32_le (&bw, avimux->avi_hdr.us_frame);
1214   gst_byte_writer_put_uint32_le (&bw, avimux->avi_hdr.max_bps);
1215   gst_byte_writer_put_uint32_le (&bw, avimux->avi_hdr.pad_gran);
1216   gst_byte_writer_put_uint32_le (&bw, avimux->avi_hdr.flags);
1217   gst_byte_writer_put_uint32_le (&bw, avimux->avi_hdr.tot_frames);
1218   gst_byte_writer_put_uint32_le (&bw, avimux->avi_hdr.init_frames);
1219   gst_byte_writer_put_uint32_le (&bw, avimux->avi_hdr.streams);
1220   gst_byte_writer_put_uint32_le (&bw, avimux->avi_hdr.bufsize);
1221   gst_byte_writer_put_uint32_le (&bw, avimux->avi_hdr.width);
1222   gst_byte_writer_put_uint32_le (&bw, avimux->avi_hdr.height);
1223   gst_byte_writer_put_uint32_le (&bw, avimux->avi_hdr.scale);
1224   gst_byte_writer_put_uint32_le (&bw, avimux->avi_hdr.rate);
1225   gst_byte_writer_put_uint32_le (&bw, avimux->avi_hdr.start);
1226   gst_byte_writer_put_uint32_le (&bw, avimux->avi_hdr.length);
1227   gst_avi_mux_end_chunk (&bw, avih);
1228
1229   /* stream data */
1230   node = avimux->sinkpads;
1231   while (node) {
1232     GstAviPad *avipad = (GstAviPad *) node->data;
1233     GstAviVideoPad *vidpad = (GstAviVideoPad *) avipad;
1234     GstAviAudioPad *audpad = (GstAviAudioPad *) avipad;
1235     gint codec_size = 0;
1236     guint strh, strl, strf, indx;
1237
1238     /* stream list metadata */
1239     strl = gst_avi_mux_start_chunk (&bw, "LIST", 0);
1240     gst_byte_writer_put_data (&bw, (guint8 *) "strl", 4);
1241
1242     /* generic header */
1243     strh = gst_avi_mux_start_chunk (&bw, "strh", 0);
1244     gst_byte_writer_put_uint32_le (&bw, avipad->hdr.type);
1245     gst_byte_writer_put_uint32_le (&bw, avipad->hdr.fcc_handler);
1246     gst_byte_writer_put_uint32_le (&bw, avipad->hdr.flags);
1247     gst_byte_writer_put_uint32_le (&bw, avipad->hdr.priority);
1248     gst_byte_writer_put_uint32_le (&bw, avipad->hdr.init_frames);
1249     gst_byte_writer_put_uint32_le (&bw, avipad->hdr.scale);
1250     gst_byte_writer_put_uint32_le (&bw, avipad->hdr.rate);
1251     gst_byte_writer_put_uint32_le (&bw, avipad->hdr.start);
1252     gst_byte_writer_put_uint32_le (&bw, avipad->hdr.length);
1253     gst_byte_writer_put_uint32_le (&bw, avipad->hdr.bufsize);
1254     gst_byte_writer_put_uint32_le (&bw, avipad->hdr.quality);
1255     gst_byte_writer_put_uint32_le (&bw, avipad->hdr.samplesize);
1256     gst_byte_writer_put_uint16_le (&bw, 0);
1257     gst_byte_writer_put_uint16_le (&bw, 0);
1258     gst_byte_writer_put_uint16_le (&bw, 0);
1259     gst_byte_writer_put_uint16_le (&bw, 0);
1260     gst_avi_mux_end_chunk (&bw, strh);
1261
1262     if (avipad->is_video) {
1263       codec_size = vidpad->vids_codec_data ?
1264           GST_BUFFER_SIZE (vidpad->vids_codec_data) : 0;
1265       /* the video header */
1266       strf = gst_avi_mux_start_chunk (&bw, "strf", 0);
1267       /* the actual header */
1268       gst_byte_writer_put_uint32_le (&bw, vidpad->vids.size + codec_size);
1269       gst_byte_writer_put_uint32_le (&bw, vidpad->vids.width);
1270       gst_byte_writer_put_uint32_le (&bw, vidpad->vids.height);
1271       gst_byte_writer_put_uint16_le (&bw, vidpad->vids.planes);
1272       gst_byte_writer_put_uint16_le (&bw, vidpad->vids.bit_cnt);
1273       gst_byte_writer_put_uint32_le (&bw, vidpad->vids.compression);
1274       gst_byte_writer_put_uint32_le (&bw, vidpad->vids.image_size);
1275       gst_byte_writer_put_uint32_le (&bw, vidpad->vids.xpels_meter);
1276       gst_byte_writer_put_uint32_le (&bw, vidpad->vids.ypels_meter);
1277       gst_byte_writer_put_uint32_le (&bw, vidpad->vids.num_colors);
1278       gst_byte_writer_put_uint32_le (&bw, vidpad->vids.imp_colors);
1279       if (vidpad->vids_codec_data) {
1280         gst_byte_writer_put_data (&bw,
1281             GST_BUFFER_DATA (vidpad->vids_codec_data),
1282             GST_BUFFER_SIZE (vidpad->vids_codec_data));
1283       }
1284       gst_avi_mux_end_chunk (&bw, strf);
1285
1286       /* add video property data, mainly for aspect ratio, if any */
1287       if (vidpad->vprp.aspect) {
1288         gint f;
1289         guint vprp;
1290
1291         /* let's be on the safe side */
1292         vidpad->vprp.fields = MIN (vidpad->vprp.fields,
1293             GST_RIFF_VPRP_VIDEO_FIELDS);
1294         /* the vprp header */
1295         vprp = gst_avi_mux_start_chunk (&bw, "vprp", 0);
1296         /* the actual data */
1297         gst_byte_writer_put_uint32_le (&bw, vidpad->vprp.format_token);
1298         gst_byte_writer_put_uint32_le (&bw, vidpad->vprp.standard);
1299         gst_byte_writer_put_uint32_le (&bw, vidpad->vprp.vert_rate);
1300         gst_byte_writer_put_uint32_le (&bw, vidpad->vprp.hor_t_total);
1301         gst_byte_writer_put_uint32_le (&bw, vidpad->vprp.vert_lines);
1302         gst_byte_writer_put_uint32_le (&bw, vidpad->vprp.aspect);
1303         gst_byte_writer_put_uint32_le (&bw, vidpad->vprp.width);
1304         gst_byte_writer_put_uint32_le (&bw, vidpad->vprp.height);
1305         gst_byte_writer_put_uint32_le (&bw, vidpad->vprp.fields);
1306
1307         for (f = 0; f < vidpad->vprp.fields; ++f) {
1308           gst_riff_vprp_video_field_desc *fd;
1309
1310           fd = &(vidpad->vprp.field_info[f]);
1311           gst_byte_writer_put_uint32_le (&bw, fd->compressed_bm_height);
1312           gst_byte_writer_put_uint32_le (&bw, fd->compressed_bm_width);
1313           gst_byte_writer_put_uint32_le (&bw, fd->valid_bm_height);
1314           gst_byte_writer_put_uint32_le (&bw, fd->valid_bm_width);
1315           gst_byte_writer_put_uint32_le (&bw, fd->valid_bm_x_offset);
1316           gst_byte_writer_put_uint32_le (&bw, fd->valid_bm_y_offset);
1317           gst_byte_writer_put_uint32_le (&bw, fd->video_x_t_offset);
1318           gst_byte_writer_put_uint32_le (&bw, fd->video_y_start);
1319         }
1320         gst_avi_mux_end_chunk (&bw, vprp);
1321       }
1322     } else {
1323       codec_size = audpad->auds_codec_data ?
1324           GST_BUFFER_SIZE (audpad->auds_codec_data) : 0;
1325       /* the audio header */
1326       strf = gst_avi_mux_start_chunk (&bw, "strf", 0);
1327       /* the actual header */
1328       gst_byte_writer_put_uint16_le (&bw, audpad->auds.format);
1329       gst_byte_writer_put_uint16_le (&bw, audpad->auds.channels);
1330       gst_byte_writer_put_uint32_le (&bw, audpad->auds.rate);
1331       gst_byte_writer_put_uint32_le (&bw, audpad->auds.av_bps);
1332       gst_byte_writer_put_uint16_le (&bw, audpad->auds.blockalign);
1333       gst_byte_writer_put_uint16_le (&bw, audpad->auds.size);
1334       gst_byte_writer_put_uint16_le (&bw, codec_size);
1335       if (audpad->auds_codec_data) {
1336         gst_byte_writer_put_data (&bw,
1337             GST_BUFFER_DATA (audpad->auds_codec_data),
1338             GST_BUFFER_SIZE (audpad->auds_codec_data));
1339       }
1340       gst_avi_mux_end_chunk (&bw, strf);
1341     }
1342
1343     /* odml superindex chunk */
1344     if (avipad->idx_index > 0)
1345       indx = gst_avi_mux_start_chunk (&bw, "indx", 0);
1346     else
1347       indx = gst_avi_mux_start_chunk (&bw, "JUNK", 0);
1348     gst_byte_writer_put_uint16_le (&bw, 4);     /* bytes per entry */
1349     gst_byte_writer_put_uint8 (&bw, 0); /* index subtype */
1350     gst_byte_writer_put_uint8 (&bw, GST_AVI_INDEX_OF_INDEXES);  /* index type */
1351     gst_byte_writer_put_uint32_le (&bw, avipad->idx_index);     /* entries in use */
1352     gst_byte_writer_put_data (&bw, (guint8 *) avipad->tag, 4);  /* stream id */
1353     gst_byte_writer_put_uint32_le (&bw, 0);     /* reserved */
1354     gst_byte_writer_put_uint32_le (&bw, 0);     /* reserved */
1355     gst_byte_writer_put_uint32_le (&bw, 0);     /* reserved */
1356     gst_byte_writer_put_data (&bw, (guint8 *) avipad->idx,
1357         GST_AVI_SUPERINDEX_COUNT * sizeof (gst_avi_superindex_entry));
1358     gst_avi_mux_end_chunk (&bw, indx);
1359
1360     /* end strl for this stream */
1361     gst_avi_mux_end_chunk (&bw, strl);
1362
1363     node = node->next;
1364   }
1365
1366   if (avimux->video_pads > 0) {
1367     guint odml, dmlh;
1368     /* odml header */
1369     odml = gst_avi_mux_start_chunk (&bw, "LIST", 0);
1370     gst_byte_writer_put_data (&bw, (guint8 *) "odml", 4);
1371     dmlh = gst_avi_mux_start_chunk (&bw, "dmlh", 0);
1372     gst_byte_writer_put_uint32_le (&bw, avimux->total_frames);
1373     gst_avi_mux_end_chunk (&bw, dmlh);
1374     gst_avi_mux_end_chunk (&bw, odml);
1375   }
1376
1377   /* end hdrl */
1378   gst_avi_mux_end_chunk (&bw, hdrl);
1379
1380   /* tags */
1381   if (tags) {
1382     guint info;
1383
1384     info = gst_avi_mux_start_chunk (&bw, "LIST", 0);
1385     gst_byte_writer_put_data (&bw, (guint8 *) "INFO", 4);
1386
1387     gst_tag_list_foreach (tags, gst_avi_mux_write_tag, &bw);
1388     if (info + 8 == gst_byte_writer_get_pos (&bw)) {
1389       /* no tags writen, remove the empty INFO LIST as it is useless
1390        * and prevents playback in vlc */
1391       gst_byte_writer_set_pos (&bw, info - 4);
1392     } else {
1393       gst_avi_mux_end_chunk (&bw, info);
1394     }
1395   }
1396
1397   /* pop RIFF */
1398   gst_avi_mux_end_chunk (&bw, riff);
1399
1400   /* avi data header */
1401   gst_byte_writer_put_data (&bw, (guint8 *) "LIST", 4);
1402   gst_byte_writer_put_uint32_le (&bw, avimux->data_size);
1403   gst_byte_writer_put_data (&bw, (guint8 *) "movi", 4);
1404
1405   /* now get the data */
1406   buffer = gst_byte_writer_reset_and_get_buffer (&bw);
1407
1408   /* ... but RIFF includes more than just header */
1409   size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buffer) + 4);
1410   size += 8 + avimux->data_size + avimux->idx_size;
1411   GST_WRITE_UINT32_LE (GST_BUFFER_DATA (buffer) + 4, size);
1412
1413   GST_MEMDUMP_OBJECT (avimux, "avi header", GST_BUFFER_DATA (buffer),
1414       GST_BUFFER_SIZE (buffer));
1415
1416   return buffer;
1417 }
1418
1419 static GstBuffer *
1420 gst_avi_mux_riff_get_avix_header (guint32 datax_size)
1421 {
1422   GstBuffer *buffer;
1423   guint8 *buffdata;
1424
1425   buffer = gst_buffer_new_and_alloc (24);
1426   buffdata = GST_BUFFER_DATA (buffer);
1427
1428   memcpy (buffdata + 0, "RIFF", 4);
1429   GST_WRITE_UINT32_LE (buffdata + 4, datax_size + 3 * 4);
1430   memcpy (buffdata + 8, "AVIX", 4);
1431   memcpy (buffdata + 12, "LIST", 4);
1432   GST_WRITE_UINT32_LE (buffdata + 16, datax_size);
1433   memcpy (buffdata + 20, "movi", 4);
1434
1435   return buffer;
1436 }
1437
1438 static inline GstBuffer *
1439 gst_avi_mux_riff_get_header (GstAviPad * avipad, guint32 video_frame_size)
1440 {
1441   GstBuffer *buffer;
1442   guint8 *buffdata;
1443
1444   buffer = gst_buffer_new_and_alloc (8);
1445   buffdata = GST_BUFFER_DATA (buffer);
1446   memcpy (buffdata + 0, avipad->tag, 4);
1447   GST_WRITE_UINT32_LE (buffdata + 4, video_frame_size);
1448
1449   return buffer;
1450 }
1451
1452 /* write an odml index chunk in the movi list */
1453 static GstFlowReturn
1454 gst_avi_mux_write_avix_index (GstAviMux * avimux, GstAviPad * avipad,
1455     gchar * code, gchar * chunk, gst_avi_superindex_entry * super_index,
1456     gint * super_index_count)
1457 {
1458   GstFlowReturn res;
1459   GstBuffer *buffer;
1460   guint8 *buffdata, *data;
1461   gst_riff_index_entry *entry;
1462   gint i;
1463   guint32 size, entry_count;
1464   gboolean is_pcm = FALSE;
1465   guint32 pcm_samples = 0;
1466
1467   /* check if it is pcm */
1468   if (avipad && !avipad->is_video) {
1469     GstAviAudioPad *audiopad = (GstAviAudioPad *) avipad;
1470     if (audiopad->auds.format == GST_RIFF_WAVE_FORMAT_PCM) {
1471       pcm_samples = audiopad->samples;
1472       is_pcm = TRUE;
1473     }
1474   }
1475
1476   /* allocate the maximum possible */
1477   buffer = gst_buffer_new_and_alloc (32 + 8 * avimux->idx_index);
1478   buffdata = GST_BUFFER_DATA (buffer);
1479
1480   /* general index chunk info */
1481   memcpy (buffdata + 0, chunk, 4);      /* chunk id */
1482   GST_WRITE_UINT32_LE (buffdata + 4, 0);        /* chunk size; fill later */
1483   GST_WRITE_UINT16_LE (buffdata + 8, 2);        /* index entry is 2 words */
1484   buffdata[10] = 0;             /* index subtype */
1485   buffdata[11] = GST_AVI_INDEX_OF_CHUNKS;       /* index type: AVI_INDEX_OF_CHUNKS */
1486   GST_WRITE_UINT32_LE (buffdata + 12, 0);       /* entries in use; fill later */
1487   memcpy (buffdata + 16, code, 4);      /* stream to which index refers */
1488   GST_WRITE_UINT64_LE (buffdata + 20, avimux->avix_start);      /* base offset */
1489   GST_WRITE_UINT32_LE (buffdata + 28, 0);       /* reserved */
1490   buffdata += 32;
1491
1492   /* now the actual index entries */
1493   i = avimux->idx_index;
1494   entry = avimux->idx;
1495   while (i > 0) {
1496     if (memcmp (&entry->id, code, 4) == 0) {
1497       /* enter relative offset to the data (!) */
1498       GST_WRITE_UINT32_LE (buffdata, GUINT32_FROM_LE (entry->offset) + 8);
1499       /* msb is set if not (!) keyframe */
1500       GST_WRITE_UINT32_LE (buffdata + 4, GUINT32_FROM_LE (entry->size)
1501           | (GUINT32_FROM_LE (entry->flags)
1502               & GST_RIFF_IF_KEYFRAME ? 0 : 1U << 31));
1503       buffdata += 8;
1504     }
1505     i--;
1506     entry++;
1507   }
1508
1509   /* ok, now we know the size and no of entries, fill in where needed */
1510   data = GST_BUFFER_DATA (buffer);
1511   GST_BUFFER_SIZE (buffer) = size = buffdata - data;
1512   GST_WRITE_UINT32_LE (data + 4, size - 8);
1513   entry_count = (size - 32) / 8;
1514   GST_WRITE_UINT32_LE (data + 12, entry_count);
1515
1516   /* decorate and send */
1517   gst_buffer_set_caps (buffer, GST_PAD_CAPS (avimux->srcpad));
1518   if ((res = gst_pad_push (avimux->srcpad, buffer)) != GST_FLOW_OK)
1519     return res;
1520
1521   /* keep track of this in superindex (if room) ... */
1522   if (*super_index_count < GST_AVI_SUPERINDEX_COUNT) {
1523     i = *super_index_count;
1524     super_index[i].offset = GUINT64_TO_LE (avimux->total_data);
1525     super_index[i].size = GUINT32_TO_LE (size);
1526     if (is_pcm) {
1527       super_index[i].duration = GUINT32_TO_LE (pcm_samples);
1528     } else {
1529       super_index[i].duration = GUINT32_TO_LE (entry_count);
1530     }
1531     (*super_index_count)++;
1532   } else
1533     GST_WARNING_OBJECT (avimux, "No more room in superindex of stream %s",
1534         code);
1535
1536   /* ... and in size */
1537   avimux->total_data += size;
1538   if (avimux->is_bigfile)
1539     avimux->datax_size += size;
1540   else
1541     avimux->data_size += size;
1542
1543   return GST_FLOW_OK;
1544 }
1545
1546 /* some other usable functions (thankyou xawtv ;-) ) */
1547
1548 static void
1549 gst_avi_mux_add_index (GstAviMux * avimux, GstAviPad * avipad, guint32 flags,
1550     guint32 size)
1551 {
1552   gchar *code = avipad->tag;
1553   if (avimux->idx_index == avimux->idx_count) {
1554     avimux->idx_count += 256;
1555     avimux->idx =
1556         g_realloc (avimux->idx,
1557         avimux->idx_count * sizeof (gst_riff_index_entry));
1558   }
1559
1560   /* in case of pcm audio, we need to count the number of samples for
1561    * putting in the indx entries */
1562   if (!avipad->is_video) {
1563     GstAviAudioPad *audiopad = (GstAviAudioPad *) avipad;
1564     if (audiopad->auds.format == GST_RIFF_WAVE_FORMAT_PCM) {
1565       audiopad->samples += size / audiopad->auds.blockalign;
1566     }
1567   }
1568
1569   memcpy (&(avimux->idx[avimux->idx_index].id), code, 4);
1570   avimux->idx[avimux->idx_index].flags = GUINT32_TO_LE (flags);
1571   avimux->idx[avimux->idx_index].offset = GUINT32_TO_LE (avimux->idx_offset);
1572   avimux->idx[avimux->idx_index].size = GUINT32_TO_LE (size);
1573   avimux->idx_index++;
1574 }
1575
1576 static GstFlowReturn
1577 gst_avi_mux_write_index (GstAviMux * avimux)
1578 {
1579   GstFlowReturn res;
1580   GstBuffer *buffer;
1581   guint8 *buffdata;
1582
1583   buffer = gst_buffer_new_and_alloc (8);
1584   buffdata = GST_BUFFER_DATA (buffer);
1585   memcpy (buffdata + 0, "idx1", 4);
1586   GST_WRITE_UINT32_LE (buffdata + 4,
1587       avimux->idx_index * sizeof (gst_riff_index_entry));
1588
1589   gst_buffer_set_caps (buffer, GST_PAD_CAPS (avimux->srcpad));
1590   res = gst_pad_push (avimux->srcpad, buffer);
1591   if (res != GST_FLOW_OK)
1592     return res;
1593
1594   buffer = gst_buffer_new ();
1595   GST_BUFFER_SIZE (buffer) = avimux->idx_index * sizeof (gst_riff_index_entry);
1596   GST_BUFFER_DATA (buffer) = (guint8 *) avimux->idx;
1597   GST_BUFFER_MALLOCDATA (buffer) = GST_BUFFER_DATA (buffer);
1598   avimux->idx = NULL;           /* will be free()'ed by gst_buffer_unref() */
1599   avimux->total_data += GST_BUFFER_SIZE (buffer) + 8;
1600
1601   gst_buffer_set_caps (buffer, GST_PAD_CAPS (avimux->srcpad));
1602   res = gst_pad_push (avimux->srcpad, buffer);
1603   if (res != GST_FLOW_OK)
1604     return res;
1605
1606   avimux->idx_size += avimux->idx_index * sizeof (gst_riff_index_entry) + 8;
1607
1608   /* update header */
1609   avimux->avi_hdr.flags |= GST_RIFF_AVIH_HASINDEX;
1610   return GST_FLOW_OK;
1611 }
1612
1613 static GstFlowReturn
1614 gst_avi_mux_bigfile (GstAviMux * avimux, gboolean last)
1615 {
1616   GstFlowReturn res = GST_FLOW_OK;
1617   GstBuffer *header;
1618   GstEvent *event;
1619   GSList *node;
1620
1621   /* first some odml standard index chunks in the movi list */
1622   node = avimux->sinkpads;
1623   while (node) {
1624     GstAviPad *avipad = (GstAviPad *) node->data;
1625
1626     node = node->next;
1627
1628     res = gst_avi_mux_write_avix_index (avimux, avipad, avipad->tag,
1629         avipad->idx_tag, avipad->idx, &avipad->idx_index);
1630     if (res != GST_FLOW_OK)
1631       return res;
1632   }
1633
1634   if (avimux->is_bigfile) {
1635     /* search back */
1636     event = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES,
1637         avimux->avix_start, GST_CLOCK_TIME_NONE, avimux->avix_start);
1638     /* if the event succeeds */
1639     gst_pad_push_event (avimux->srcpad, event);
1640
1641     /* rewrite AVIX header */
1642     header = gst_avi_mux_riff_get_avix_header (avimux->datax_size);
1643     gst_buffer_set_caps (header, GST_PAD_CAPS (avimux->srcpad));
1644     res = gst_pad_push (avimux->srcpad, header);
1645
1646     /* go back to current location, at least try */
1647     event = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES,
1648         avimux->total_data, GST_CLOCK_TIME_NONE, avimux->total_data);
1649     gst_pad_push_event (avimux->srcpad, event);
1650
1651     if (res != GST_FLOW_OK)
1652       return res;
1653   } else {                      /* write a standard index in the first riff chunk */
1654     res = gst_avi_mux_write_index (avimux);
1655     /* the index data/buffer is freed by pushing it */
1656     avimux->idx_count = 0;
1657     if (res != GST_FLOW_OK)
1658       return res;
1659   }
1660
1661   avimux->avix_start = avimux->total_data;
1662
1663   if (last)
1664     return res;
1665
1666   avimux->is_bigfile = TRUE;
1667   avimux->numx_frames = 0;
1668   avimux->datax_size = 4;       /* movi tag */
1669   avimux->idx_index = 0;
1670   node = avimux->sinkpads;
1671   while (node) {
1672     GstAviPad *avipad = (GstAviPad *) node->data;
1673     node = node->next;
1674     if (!avipad->is_video) {
1675       GstAviAudioPad *audiopad = (GstAviAudioPad *) avipad;
1676       audiopad->samples = 0;
1677     }
1678   }
1679
1680   header = gst_avi_mux_riff_get_avix_header (0);
1681   avimux->total_data += GST_BUFFER_SIZE (header);
1682   /* avix_start is used as base offset for the odml index chunk */
1683   avimux->idx_offset = avimux->total_data - avimux->avix_start;
1684   gst_buffer_set_caps (header, GST_PAD_CAPS (avimux->srcpad));
1685   return gst_pad_push (avimux->srcpad, header);
1686 }
1687
1688 /* enough header blabla now, let's go on to actually writing the headers */
1689
1690 static GstFlowReturn
1691 gst_avi_mux_start_file (GstAviMux * avimux)
1692 {
1693   GstFlowReturn res;
1694   GstBuffer *header;
1695   GSList *node;
1696   GstCaps *caps;
1697
1698   avimux->total_data = 0;
1699   avimux->total_frames = 0;
1700   avimux->data_size = 4;        /* movi tag */
1701   avimux->datax_size = 0;
1702   avimux->num_frames = 0;
1703   avimux->numx_frames = 0;
1704   avimux->avix_start = 0;
1705
1706   avimux->idx_index = 0;
1707   avimux->idx_offset = 0;       /* see 10 lines below */
1708   avimux->idx_size = 0;
1709   avimux->idx_count = 0;
1710   avimux->idx = NULL;
1711
1712   /* state */
1713   avimux->write_header = FALSE;
1714   avimux->restart = FALSE;
1715
1716   /* init streams, see what we've got */
1717   node = avimux->sinkpads;
1718   avimux->audio_pads = avimux->video_pads = 0;
1719   while (node) {
1720     GstAviPad *avipad = (GstAviPad *) node->data;
1721
1722     node = node->next;
1723
1724     if (!avipad->is_video) {
1725       /* audio stream numbers must start at 1 iff there is a video stream 0;
1726        * request_pad inserts video pad at head of list, so this test suffices */
1727       if (avimux->video_pads)
1728         avimux->audio_pads++;
1729       avipad->tag = g_strdup_printf ("%02uwb", avimux->audio_pads);
1730       avipad->idx_tag = g_strdup_printf ("ix%02u", avimux->audio_pads);
1731       if (!avimux->video_pads)
1732         avimux->audio_pads++;
1733     } else {
1734       avipad->tag = g_strdup_printf ("%02udb", avimux->video_pads);
1735       avipad->idx_tag = g_strdup_printf ("ix%02u", avimux->video_pads++);
1736     }
1737   }
1738
1739   caps = gst_caps_copy (gst_pad_get_pad_template_caps (avimux->srcpad));
1740   gst_pad_set_caps (avimux->srcpad, caps);
1741   gst_caps_unref (caps);
1742
1743   /* let downstream know we think in BYTES and expect to do seeking later on */
1744   gst_pad_push_event (avimux->srcpad,
1745       gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES, 0, -1, 0));
1746
1747   /* header */
1748   avimux->avi_hdr.streams = g_slist_length (avimux->sinkpads);
1749   avimux->is_bigfile = FALSE;
1750
1751   header = gst_avi_mux_riff_get_avi_header (avimux);
1752   avimux->total_data += GST_BUFFER_SIZE (header);
1753
1754   gst_buffer_set_caps (header, GST_PAD_CAPS (avimux->srcpad));
1755   res = gst_pad_push (avimux->srcpad, header);
1756
1757   avimux->idx_offset = avimux->total_data;
1758
1759   return res;
1760 }
1761
1762 static GstFlowReturn
1763 gst_avi_mux_stop_file (GstAviMux * avimux)
1764 {
1765   GstFlowReturn res = GST_FLOW_OK;
1766   GstEvent *event;
1767   GstBuffer *header;
1768   GSList *node;
1769
1770   /* if bigfile, rewrite header, else write indexes */
1771   /* don't bail out at once if error, still try to re-write header */
1772   if (avimux->video_pads > 0) {
1773     if (avimux->is_bigfile) {
1774       res = gst_avi_mux_bigfile (avimux, TRUE);
1775     } else {
1776       res = gst_avi_mux_write_index (avimux);
1777     }
1778   }
1779
1780   /* we do our best to make it interleaved at least ... */
1781   if (avimux->audio_pads > 0 && avimux->video_pads > 0)
1782     avimux->avi_hdr.flags |= GST_RIFF_AVIH_ISINTERLEAVED;
1783
1784   /* set rate and everything having to do with that */
1785   avimux->avi_hdr.max_bps = 0;
1786   node = avimux->sinkpads;
1787   while (node) {
1788     GstAviPad *avipad = (GstAviPad *) node->data;
1789
1790     node = node->next;
1791
1792     if (!avipad->is_video) {
1793       GstAviAudioPad *audpad = (GstAviAudioPad *) avipad;
1794
1795       /* calculate bps if needed */
1796       if (!audpad->auds.av_bps) {
1797         if (audpad->audio_time) {
1798           audpad->auds.av_bps =
1799               (GST_SECOND * audpad->audio_size) / audpad->audio_time;
1800           /* round bps to nearest multiple of 8;
1801            * which is much more likely to be the (cbr) bitrate in use;
1802            * which in turn results in better timestamp calculation on playback */
1803           audpad->auds.av_bps = GST_ROUND_UP_8 (audpad->auds.av_bps - 4);
1804         } else {
1805           GST_ELEMENT_WARNING (avimux, STREAM, MUX,
1806               (_("No or invalid input audio, AVI stream will be corrupt.")),
1807               (NULL));
1808           audpad->auds.av_bps = 0;
1809         }
1810       }
1811       gst_avi_mux_audsink_set_fields (avimux, audpad);
1812       avimux->avi_hdr.max_bps += audpad->auds.av_bps;
1813       avipad->hdr.length = gst_util_uint64_scale (audpad->audio_time,
1814           avipad->hdr.rate, avipad->hdr.scale * GST_SECOND);
1815     } else {
1816       GstAviVideoPad *vidpad = (GstAviVideoPad *) avipad;
1817
1818       avimux->avi_hdr.max_bps += ((vidpad->vids.bit_cnt + 7) / 8) *
1819           (1000000. / avimux->avi_hdr.us_frame) * vidpad->vids.image_size;
1820       avipad->hdr.length = avimux->total_frames;
1821     }
1822   }
1823
1824   /* statistics/total_frames/... */
1825   avimux->avi_hdr.tot_frames = avimux->num_frames;
1826
1827   /* seek and rewrite the header */
1828   header = gst_avi_mux_riff_get_avi_header (avimux);
1829   event = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES,
1830       0, GST_CLOCK_TIME_NONE, 0);
1831   gst_pad_push_event (avimux->srcpad, event);
1832
1833   gst_buffer_set_caps (header, GST_PAD_CAPS (avimux->srcpad));
1834   /* the first error survives */
1835   if (res == GST_FLOW_OK)
1836     res = gst_pad_push (avimux->srcpad, header);
1837   else
1838     gst_pad_push (avimux->srcpad, header);
1839
1840   event = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES,
1841       avimux->total_data, GST_CLOCK_TIME_NONE, avimux->total_data);
1842   gst_pad_push_event (avimux->srcpad, event);
1843
1844   avimux->write_header = TRUE;
1845
1846   return res;
1847 }
1848
1849 static GstFlowReturn
1850 gst_avi_mux_restart_file (GstAviMux * avimux)
1851 {
1852   GstFlowReturn res;
1853
1854   if ((res = gst_avi_mux_stop_file (avimux)) != GST_FLOW_OK)
1855     return res;
1856
1857   gst_pad_push_event (avimux->srcpad, gst_event_new_eos ());
1858
1859   return gst_avi_mux_start_file (avimux);
1860 }
1861
1862 /* handle events (search) */
1863 static gboolean
1864 gst_avi_mux_handle_event (GstPad * pad, GstEvent * event)
1865 {
1866   GstAviMux *avimux;
1867   gboolean ret;
1868
1869   avimux = GST_AVI_MUX (gst_pad_get_parent (pad));
1870
1871   switch (GST_EVENT_TYPE (event)) {
1872     case GST_EVENT_TAG:{
1873       GstTagList *list;
1874       GstTagSetter *setter = GST_TAG_SETTER (avimux);
1875       const GstTagMergeMode mode = gst_tag_setter_get_tag_merge_mode (setter);
1876
1877       gst_event_parse_tag (event, &list);
1878       gst_tag_setter_merge_tags (setter, list, mode);
1879       break;
1880     }
1881     default:
1882       break;
1883   }
1884
1885   /* now GstCollectPads can take care of the rest, e.g. EOS */
1886   ret = avimux->collect_event (pad, event);
1887
1888   gst_object_unref (avimux);
1889
1890   return ret;
1891 }
1892
1893 /* send extra 'padding' data */
1894 static GstFlowReturn
1895 gst_avi_mux_send_pad_data (GstAviMux * avimux, gulong num_bytes)
1896 {
1897   GstBuffer *buffer;
1898
1899   buffer = gst_buffer_new_and_alloc (num_bytes);
1900   memset (GST_BUFFER_DATA (buffer), 0, num_bytes);
1901   gst_buffer_set_caps (buffer, GST_PAD_CAPS (avimux->srcpad));
1902   return gst_pad_push (avimux->srcpad, buffer);
1903 }
1904
1905 /* do buffer */
1906 static GstFlowReturn
1907 gst_avi_mux_do_buffer (GstAviMux * avimux, GstAviPad * avipad)
1908 {
1909   GstFlowReturn res;
1910   GstBuffer *data, *header;
1911   gulong total_size, pad_bytes = 0;
1912   guint flags;
1913
1914   data = gst_collect_pads_pop (avimux->collect, avipad->collect);
1915   /* arrange downstream running time */
1916   data = gst_buffer_make_metadata_writable (data);
1917   GST_BUFFER_TIMESTAMP (data) =
1918       gst_segment_to_running_time (&avipad->collect->segment,
1919       GST_FORMAT_TIME, GST_BUFFER_TIMESTAMP (data));
1920
1921   /* Prepend a special buffer to the first one for some formats */
1922   if (avipad->is_video) {
1923     GstAviVideoPad *vidpad = (GstAviVideoPad *) avipad;
1924
1925     if (vidpad->prepend_buffer) {
1926       GstBuffer *newdata = gst_buffer_merge (vidpad->prepend_buffer, data);
1927       gst_buffer_copy_metadata (newdata, data, GST_BUFFER_COPY_TIMESTAMPS);
1928       gst_buffer_unref (data);
1929       gst_buffer_unref (vidpad->prepend_buffer);
1930
1931       data = newdata;
1932       vidpad->prepend_buffer = NULL;
1933     }
1934   }
1935
1936   if (avimux->restart) {
1937     if ((res = gst_avi_mux_restart_file (avimux)) != GST_FLOW_OK)
1938       return res;
1939   }
1940
1941   /* need to restart or start a next avix chunk ? */
1942   if ((avimux->is_bigfile ? avimux->datax_size : avimux->data_size) +
1943       GST_BUFFER_SIZE (data) > GST_AVI_MAX_SIZE) {
1944     if (avimux->enable_large_avi) {
1945       if ((res = gst_avi_mux_bigfile (avimux, FALSE)) != GST_FLOW_OK)
1946         return res;
1947     } else {
1948       if ((res = gst_avi_mux_restart_file (avimux)) != GST_FLOW_OK)
1949         return res;
1950     }
1951   }
1952
1953   /* get header and record some stats */
1954   if (GST_BUFFER_SIZE (data) & 1) {
1955     pad_bytes = 2 - (GST_BUFFER_SIZE (data) & 1);
1956   }
1957   header = gst_avi_mux_riff_get_header (avipad, GST_BUFFER_SIZE (data));
1958   total_size = GST_BUFFER_SIZE (header) + GST_BUFFER_SIZE (data) + pad_bytes;
1959
1960   if (avimux->is_bigfile) {
1961     avimux->datax_size += total_size;
1962   } else {
1963     avimux->data_size += total_size;
1964   }
1965
1966   if (G_UNLIKELY (avipad->hook))
1967     avipad->hook (avimux, avipad, data);
1968
1969   /* the suggested buffer size is the max frame size */
1970   if (avipad->hdr.bufsize < GST_BUFFER_SIZE (data))
1971     avipad->hdr.bufsize = GST_BUFFER_SIZE (data);
1972
1973   if (avipad->is_video) {
1974     avimux->total_frames++;
1975
1976     if (avimux->is_bigfile) {
1977       avimux->numx_frames++;
1978     } else {
1979       avimux->num_frames++;
1980     }
1981
1982     flags = 0x02;
1983     if (!GST_BUFFER_FLAG_IS_SET (data, GST_BUFFER_FLAG_DELTA_UNIT))
1984       flags |= 0x10;
1985   } else {
1986     GstAviAudioPad *audpad = (GstAviAudioPad *) avipad;
1987
1988     flags = 0;
1989     audpad->audio_size += GST_BUFFER_SIZE (data);
1990     audpad->audio_time += GST_BUFFER_DURATION (data);
1991   }
1992
1993   gst_avi_mux_add_index (avimux, avipad, flags, GST_BUFFER_SIZE (data));
1994
1995   /* prepare buffers for sending */
1996   gst_buffer_set_caps (header, GST_PAD_CAPS (avimux->srcpad));
1997   data = gst_buffer_make_metadata_writable (data);
1998   gst_buffer_set_caps (data, GST_PAD_CAPS (avimux->srcpad));
1999
2000   GST_LOG_OBJECT (avimux, "pushing buffers: head, data");
2001
2002   if ((res = gst_pad_push (avimux->srcpad, header)) != GST_FLOW_OK)
2003     return res;
2004   if ((res = gst_pad_push (avimux->srcpad, data)) != GST_FLOW_OK)
2005     return res;
2006
2007   if (pad_bytes) {
2008     if ((res = gst_avi_mux_send_pad_data (avimux, pad_bytes)) != GST_FLOW_OK)
2009       return res;
2010   }
2011
2012   /* if any push above fails, we're in trouble with file consistency anyway */
2013   avimux->total_data += total_size;
2014   avimux->idx_offset += total_size;
2015
2016   return res;
2017 }
2018
2019 /* pick the oldest buffer from the pads and push it */
2020 static GstFlowReturn
2021 gst_avi_mux_do_one_buffer (GstAviMux * avimux)
2022 {
2023   GstAviPad *avipad, *best_pad;
2024   GSList *node;
2025   GstBuffer *buffer;
2026   GstClockTime time, best_time, delay;
2027
2028   node = avimux->sinkpads;
2029   best_pad = NULL;
2030   best_time = GST_CLOCK_TIME_NONE;
2031   for (; node; node = node->next) {
2032     avipad = (GstAviPad *) node->data;
2033
2034     if (!avipad->collect)
2035       continue;
2036
2037     if (!avipad->hdr.fcc_handler)
2038       goto not_negotiated;
2039
2040     buffer = gst_collect_pads_peek (avimux->collect, avipad->collect);
2041     if (!buffer)
2042       continue;
2043     time = GST_BUFFER_TIMESTAMP (buffer);
2044     gst_buffer_unref (buffer);
2045
2046     /* invalid should pass */
2047     if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (time))) {
2048       time = gst_segment_to_running_time (&avipad->collect->segment,
2049           GST_FORMAT_TIME, time);
2050       if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time))) {
2051         GST_DEBUG_OBJECT (avimux, "clipping buffer on pad %s outside segment",
2052             GST_PAD_NAME (avipad->collect->pad));
2053         buffer = gst_collect_pads_pop (avimux->collect, avipad->collect);
2054         gst_buffer_unref (buffer);
2055         return GST_FLOW_OK;
2056       }
2057     }
2058
2059     delay = avipad->is_video ? GST_SECOND / 2 : 0;
2060
2061     /* invalid timestamp buffers pass first,
2062      * these are probably initialization buffers */
2063     if (best_pad == NULL || !GST_CLOCK_TIME_IS_VALID (time)
2064         || (GST_CLOCK_TIME_IS_VALID (best_time) && time + delay < best_time)) {
2065       best_pad = avipad;
2066       best_time = time + delay;
2067     }
2068   }
2069
2070   if (best_pad) {
2071     GST_LOG_OBJECT (avimux, "selected pad %s with time %" GST_TIME_FORMAT,
2072         GST_PAD_NAME (best_pad->collect->pad), GST_TIME_ARGS (best_time));
2073
2074     return gst_avi_mux_do_buffer (avimux, best_pad);
2075   } else {
2076     /* simply finish off the file and send EOS */
2077     gst_avi_mux_stop_file (avimux);
2078     gst_pad_push_event (avimux->srcpad, gst_event_new_eos ());
2079     return GST_FLOW_UNEXPECTED;
2080   }
2081
2082   /* ERRORS */
2083 not_negotiated:
2084   {
2085     GST_ELEMENT_ERROR (avimux, CORE, NEGOTIATION, (NULL),
2086         ("pad %s not negotiated", GST_PAD_NAME (avipad->collect->pad)));
2087     return GST_FLOW_NOT_NEGOTIATED;
2088   }
2089 }
2090
2091 static GstFlowReturn
2092 gst_avi_mux_collect_pads (GstCollectPads * pads, GstAviMux * avimux)
2093 {
2094   GstFlowReturn res;
2095
2096   if (G_UNLIKELY (avimux->write_header)) {
2097     if ((res = gst_avi_mux_start_file (avimux)) != GST_FLOW_OK)
2098       return res;
2099   }
2100
2101   return gst_avi_mux_do_one_buffer (avimux);
2102 }
2103
2104
2105 static void
2106 gst_avi_mux_get_property (GObject * object,
2107     guint prop_id, GValue * value, GParamSpec * pspec)
2108 {
2109   GstAviMux *avimux;
2110
2111   avimux = GST_AVI_MUX (object);
2112
2113   switch (prop_id) {
2114     case ARG_BIGFILE:
2115       g_value_set_boolean (value, avimux->enable_large_avi);
2116       break;
2117     default:
2118       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2119       break;
2120   }
2121 }
2122
2123 static void
2124 gst_avi_mux_set_property (GObject * object,
2125     guint prop_id, const GValue * value, GParamSpec * pspec)
2126 {
2127   GstAviMux *avimux;
2128
2129   avimux = GST_AVI_MUX (object);
2130
2131   switch (prop_id) {
2132     case ARG_BIGFILE:
2133       avimux->enable_large_avi = g_value_get_boolean (value);
2134       break;
2135     default:
2136       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2137       break;
2138   }
2139 }
2140
2141 static GstStateChangeReturn
2142 gst_avi_mux_change_state (GstElement * element, GstStateChange transition)
2143 {
2144   GstAviMux *avimux;
2145   GstStateChangeReturn ret;
2146
2147   avimux = GST_AVI_MUX (element);
2148
2149   switch (transition) {
2150     case GST_STATE_CHANGE_READY_TO_PAUSED:
2151       gst_collect_pads_start (avimux->collect);
2152       break;
2153     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2154       break;
2155     case GST_STATE_CHANGE_PAUSED_TO_READY:
2156       gst_collect_pads_stop (avimux->collect);
2157       break;
2158     default:
2159       break;
2160   }
2161
2162   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2163   if (ret == GST_STATE_CHANGE_FAILURE)
2164     goto done;
2165
2166   switch (transition) {
2167     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2168       break;
2169     case GST_STATE_CHANGE_PAUSED_TO_READY:
2170       gst_avi_mux_reset (avimux);
2171       break;
2172     case GST_STATE_CHANGE_READY_TO_NULL:
2173       break;
2174     default:
2175       break;
2176   }
2177
2178 done:
2179   return ret;
2180 }