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