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