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