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