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