]> git.sesse.net Git - vlc/blob - modules/mux/avi.c
mux: avi: fix leak on format failure
[vlc] / modules / mux / avi.c
1 /*****************************************************************************
2  * avi.c
3  *****************************************************************************
4  * Copyright (C) 2001-2009 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 /* TODO: add OpenDML write support */
28
29
30 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
33
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
36 #include <vlc_sout.h>
37 #include <vlc_block.h>
38 #include <vlc_codecs.h>
39 #include <vlc_bits.h>
40
41 /*****************************************************************************
42  * Module descriptor
43  *****************************************************************************/
44 static int  Open   ( vlc_object_t * );
45 static void Close  ( vlc_object_t * );
46
47 #define SOUT_CFG_PREFIX "sout-avi-"
48
49 #define CFG_ARTIST_TEXT     N_("Artist")
50 #define CFG_DATE_TEXT       N_("Date")
51 #define CFG_GENRE_TEXT      N_("Genre")
52 #define CFG_COPYRIGHT_TEXT  N_("Copyright")
53 #define CFG_COMMENT_TEXT    N_("Comment")
54 #define CFG_NAME_TEXT       N_("Name")
55 #define CFG_SUBJECT_TEXT    N_("Subject")
56 #define CFG_ENCODER_TEXT    N_("Encoder")
57 #define CFG_KEYWORDS_TEXT   N_("Keywords")
58
59 vlc_module_begin ()
60     set_description( N_("AVI muxer") )
61     set_category( CAT_SOUT )
62     set_subcategory( SUBCAT_SOUT_MUX )
63     set_capability( "sout mux", 5 )
64     add_shortcut( "avi" )
65
66     add_string( SOUT_CFG_PREFIX "artist", NULL,    CFG_ARTIST_TEXT, NULL, true )
67     add_string( SOUT_CFG_PREFIX "date",   NULL,    CFG_DATE_TEXT, NULL, true )
68     add_string( SOUT_CFG_PREFIX "genre",  NULL,    CFG_GENRE_TEXT, NULL, true )
69     add_string( SOUT_CFG_PREFIX "copyright", NULL, CFG_COPYRIGHT_TEXT, NULL, true )
70     add_string( SOUT_CFG_PREFIX "comment", NULL,   CFG_COMMENT_TEXT, NULL, true )
71     add_string( SOUT_CFG_PREFIX "name", NULL,      CFG_NAME_TEXT, NULL, true )
72     add_string( SOUT_CFG_PREFIX "subject", NULL,   CFG_SUBJECT_TEXT, NULL, true )
73     add_string( SOUT_CFG_PREFIX "encoder",
74                 "VLC Media Player - " VERSION_MESSAGE,
75                                                    CFG_ENCODER_TEXT, NULL, true )
76     add_string( SOUT_CFG_PREFIX "keywords", NULL,  CFG_KEYWORDS_TEXT, NULL, true )
77
78     set_callbacks( Open, Close )
79 vlc_module_end ()
80
81
82 /*****************************************************************************
83  * Local prototypes
84  *****************************************************************************/
85 static int Control( sout_mux_t *, int, va_list );
86 static int AddStream( sout_mux_t *, sout_input_t * );
87 static void DelStream( sout_mux_t *, sout_input_t * );
88 static int Mux      ( sout_mux_t * );
89
90 typedef struct avi_stream_s
91 {
92     int i_cat;
93
94     char fcc[4];
95
96     mtime_t i_duration;       // in µs
97
98     int     i_frames;        // total frame count
99     int64_t i_totalsize;    // total stream size
100
101     float   f_fps;
102     int     i_bitrate;
103
104     VLC_BITMAPINFOHEADER    *p_bih;
105     WAVEFORMATEX            *p_wf;
106
107 } avi_stream_t;
108
109 typedef struct avi_idx1_entry_s
110 {
111     char     fcc[4];
112     uint32_t i_flags;
113     uint32_t i_pos;
114     uint32_t i_length;
115
116 } avi_idx1_entry_t;
117
118 typedef struct avi_idx1_s
119 {
120     unsigned int i_entry_count;
121     unsigned int i_entry_max;
122
123     avi_idx1_entry_t *entry;
124 } avi_idx1_t;
125
126 struct sout_mux_sys_t
127 {
128     bool b_write_header;
129
130     int i_streams;
131     int i_stream_video;
132
133     off_t i_movi_size;
134     avi_stream_t stream[100];
135
136     avi_idx1_t idx1;
137     off_t i_idx1_size;
138
139 };
140
141 #define HDR_BASE_SIZE 512 /* single video&audio ~ 400 bytes header */
142
143 /* Flags in avih */
144 #define AVIF_HASINDEX       0x00000010  // Index at end of file?
145 #define AVIF_ISINTERLEAVED  0x00000100
146 #define AVIF_TRUSTCKTYPE    0x00000800  // Use CKType to find key frames?
147
148 /* Flags for index */
149 #define AVIIF_KEYFRAME      0x00000010L /* this frame is a key frame.*/
150
151
152 static block_t *avi_HeaderCreateRIFF( sout_mux_t * );
153 static block_t *avi_HeaderCreateidx1( sout_mux_t * );
154
155 static void SetFCC( uint8_t *p, char *fcc )
156 {
157     memcpy( p, fcc, 4 );
158 }
159
160 /*****************************************************************************
161  * Open:
162  *****************************************************************************/
163 static int Open( vlc_object_t *p_this )
164 {
165     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
166     sout_mux_sys_t  *p_sys;
167
168     msg_Dbg( p_mux, "AVI muxer opened" );
169
170     p_sys = malloc( sizeof( sout_mux_sys_t ) );
171     if( !p_sys )
172         return VLC_ENOMEM;
173     p_sys->i_streams = 0;
174     p_sys->i_stream_video = -1;
175     p_sys->i_movi_size = 0;
176
177     p_sys->idx1.i_entry_count = 0;
178     p_sys->idx1.i_entry_max = 10000;
179     p_sys->idx1.entry = calloc( p_sys->idx1.i_entry_max,
180                                 sizeof( avi_idx1_entry_t ) );
181     if( !p_sys->idx1.entry )
182     {
183         free( p_sys );
184         return VLC_ENOMEM;
185     }
186     p_sys->b_write_header = true;
187
188
189     p_mux->pf_control   = Control;
190     p_mux->pf_addstream = AddStream;
191     p_mux->pf_delstream = DelStream;
192     p_mux->pf_mux       = Mux;
193     p_mux->p_sys        = p_sys;
194
195     return VLC_SUCCESS;
196 }
197
198 /*****************************************************************************
199  * Close:
200  *****************************************************************************/
201 static void Close( vlc_object_t * p_this )
202 {
203     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
204     sout_mux_sys_t  *p_sys = p_mux->p_sys;
205
206     block_t       *p_hdr, *p_idx1;
207     int                 i_stream;
208
209     msg_Dbg( p_mux, "AVI muxer closed" );
210
211     /* first create idx1 chunk (write at the end of the stream */
212     p_idx1 = avi_HeaderCreateidx1( p_mux );
213     p_sys->i_idx1_size = p_idx1->i_buffer;
214     sout_AccessOutWrite( p_mux->p_access, p_idx1 );
215
216     /* calculate some value for headers creations */
217     for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
218     {
219         avi_stream_t *p_stream;
220
221         p_stream = &p_sys->stream[i_stream];
222
223         p_stream->f_fps = 25;
224         if( p_stream->i_duration > 0 )
225         {
226             p_stream->f_fps = (float)p_stream->i_frames /
227                               ( (float)p_stream->i_duration /
228                                 (float)1000000 );
229         }
230         p_stream->i_bitrate = 128 * 1024;
231         if( p_stream->i_duration > 0 )
232         {
233             p_stream->i_bitrate =
234                 8 * (uint64_t)1000000 *
235                     (uint64_t)p_stream->i_totalsize /
236                     (uint64_t)p_stream->i_duration;
237         }
238         msg_Info( p_mux, "stream[%d] duration:%"PRId64" totalsize:%"PRId64
239                   " frames:%d fps:%f KiB/s:%d",
240                   i_stream,
241                   (int64_t)p_stream->i_duration / (int64_t)1000000,
242                   p_stream->i_totalsize,
243                   p_stream->i_frames,
244                   p_stream->f_fps, p_stream->i_bitrate/1024 );
245     }
246
247     p_hdr = avi_HeaderCreateRIFF( p_mux );
248     sout_AccessOutSeek( p_mux->p_access, 0 );
249     sout_AccessOutWrite( p_mux->p_access, p_hdr );
250
251     for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
252     {
253         avi_stream_t *p_stream;
254         p_stream = &p_sys->stream[i_stream];
255         free( p_stream->p_bih );
256         free( p_stream->p_wf );
257     }
258     free( p_sys->idx1.entry );
259     free( p_sys );
260 }
261
262 static int Control( sout_mux_t *p_mux, int i_query, va_list args )
263 {
264     VLC_UNUSED(p_mux);
265     bool *pb_bool;
266     char **ppsz;
267
268    switch( i_query )
269    {
270        case MUX_CAN_ADD_STREAM_WHILE_MUXING:
271            pb_bool = (bool*)va_arg( args, bool * );
272            *pb_bool = false;
273            return VLC_SUCCESS;
274
275        case MUX_GET_ADD_STREAM_WAIT:
276            pb_bool = (bool*)va_arg( args, bool * );
277            *pb_bool = true;
278            return VLC_SUCCESS;
279
280        case MUX_GET_MIME:
281            ppsz = (char**)va_arg( args, char ** );
282            *ppsz = strdup( "video/avi" );
283            return VLC_SUCCESS;
284
285         default:
286             return VLC_EGENERIC;
287    }
288 }
289
290 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
291 {
292     sout_mux_sys_t  *p_sys = p_mux->p_sys;
293     avi_stream_t    *p_stream;
294
295     if( p_sys->i_streams >= 100 )
296     {
297         msg_Err( p_mux, "too many streams" );
298         return VLC_EGENERIC;
299     }
300
301     msg_Dbg( p_mux, "adding input" );
302     p_input->p_sys = malloc( sizeof( int ) );
303     if( !p_input->p_sys )
304         return VLC_ENOMEM;
305
306     *((int*)p_input->p_sys) = p_sys->i_streams;
307     p_stream = &p_sys->stream[p_sys->i_streams];
308
309     switch( p_input->p_fmt->i_cat )
310     {
311         case AUDIO_ES:
312             p_stream->i_cat = AUDIO_ES;
313             p_stream->fcc[0] = '0' + p_sys->i_streams / 10;
314             p_stream->fcc[1] = '0' + p_sys->i_streams % 10;
315             p_stream->fcc[2] = 'w';
316             p_stream->fcc[3] = 'b';
317
318             p_stream->p_bih = NULL;
319
320             WAVEFORMATEX *p_wf  = malloc( sizeof( WAVEFORMATEX ) +
321                                   p_input->p_fmt->i_extra );
322             if( !p_wf )
323             {
324                 free( p_input->p_sys );
325                 p_input->p_sys = NULL;
326                 return VLC_ENOMEM;
327             }
328
329             p_wf->cbSize = p_input->p_fmt->i_extra;
330             if( p_wf->cbSize > 0 )
331             {
332                 memcpy( &p_wf[1],
333                         p_input->p_fmt->p_extra,
334                         p_input->p_fmt->i_extra );
335             }
336             p_wf->nChannels      = p_input->p_fmt->audio.i_channels;
337             p_wf->nSamplesPerSec = p_input->p_fmt->audio.i_rate;
338             p_wf->nBlockAlign    = p_input->p_fmt->audio.i_blockalign;
339             p_wf->nAvgBytesPerSec= p_input->p_fmt->i_bitrate / 8;
340             p_wf->wBitsPerSample = 0;
341
342             switch( p_input->p_fmt->i_codec )
343             {
344                 case VLC_CODEC_A52:
345                     p_wf->wFormatTag = WAVE_FORMAT_A52;
346                     p_wf->nBlockAlign= 1;
347                     break;
348                 case VLC_CODEC_MP3:
349                     p_wf->wFormatTag = WAVE_FORMAT_MPEGLAYER3;
350                     p_wf->nBlockAlign= 1;
351                     break;
352                 case VLC_CODEC_WMA1:
353                     p_wf->wFormatTag = WAVE_FORMAT_WMA1;
354                     break;
355                 case VLC_CODEC_WMA2:
356                     p_wf->wFormatTag = WAVE_FORMAT_WMA2;
357                     break;
358                 case VLC_CODEC_WMAP:
359                     p_wf->wFormatTag = WAVE_FORMAT_WMAP;
360                     break;
361                 case VLC_CODEC_WMAL:
362                     p_wf->wFormatTag = WAVE_FORMAT_WMAL;
363                     break;
364                     /* raw codec */
365                 case VLC_CODEC_U8:
366                     p_wf->wFormatTag = WAVE_FORMAT_PCM;
367                     p_wf->nBlockAlign= p_wf->nChannels;
368                     p_wf->wBitsPerSample = 8;
369                     p_wf->nAvgBytesPerSec = (p_wf->wBitsPerSample/8) *
370                                       p_wf->nSamplesPerSec * p_wf->nChannels;
371                     break;
372                 case VLC_CODEC_S16L:
373                     p_wf->wFormatTag = WAVE_FORMAT_PCM;
374                     p_wf->nBlockAlign= 2 * p_wf->nChannels;
375                     p_wf->wBitsPerSample = 16;
376                     p_wf->nAvgBytesPerSec = (p_wf->wBitsPerSample/8) *
377                                       p_wf->nSamplesPerSec * p_wf->nChannels;
378                     break;
379                 case VLC_CODEC_S24L:
380                     p_wf->wFormatTag = WAVE_FORMAT_PCM;
381                     p_wf->nBlockAlign= 3 * p_wf->nChannels;
382                     p_wf->wBitsPerSample = 24;
383                     p_wf->nAvgBytesPerSec = (p_wf->wBitsPerSample/8) *
384                                       p_wf->nSamplesPerSec * p_wf->nChannels;
385                     break;
386                 case VLC_CODEC_S32L:
387                     p_wf->wFormatTag = WAVE_FORMAT_PCM;
388                     p_wf->nBlockAlign= 4 * p_wf->nChannels;
389                     p_wf->wBitsPerSample = 32;
390                     p_wf->nAvgBytesPerSec = (p_wf->wBitsPerSample/8) *
391                                       p_wf->nSamplesPerSec * p_wf->nChannels;
392                     break;
393                 default:
394                     free( p_wf );
395                     free( p_input->p_sys );
396                     p_input->p_sys = NULL;
397                     return VLC_EGENERIC;
398             }
399             p_stream->p_wf = p_wf;
400             break;
401         case VIDEO_ES:
402             p_stream->i_cat = VIDEO_ES;
403             p_stream->fcc[0] = '0' + p_sys->i_streams / 10;
404             p_stream->fcc[1] = '0' + p_sys->i_streams % 10;
405             p_stream->fcc[2] = 'd';
406             p_stream->fcc[3] = 'c';
407             if( p_sys->i_stream_video < 0 )
408             {
409                 p_sys->i_stream_video = p_sys->i_streams;
410             }
411             p_stream->p_wf  = NULL;
412             VLC_BITMAPINFOHEADER *p_bih = malloc( sizeof( VLC_BITMAPINFOHEADER ) +
413                                                  p_input->p_fmt->i_extra );
414             if( !p_bih )
415             {
416                 free( p_input->p_sys );
417                 p_input->p_sys = NULL;
418                 return VLC_ENOMEM;
419             }
420
421             p_bih->biSize  = sizeof( VLC_BITMAPINFOHEADER ) +
422                              p_input->p_fmt->i_extra;
423             if( p_input->p_fmt->i_extra > 0 )
424             {
425                 memcpy( &p_bih[1],
426                         p_input->p_fmt->p_extra,
427                         p_input->p_fmt->i_extra );
428             }
429             p_bih->biWidth = p_input->p_fmt->video.i_width;
430             p_bih->biHeight= p_input->p_fmt->video.i_height;
431             p_bih->biPlanes= 1;
432             p_bih->biBitCount       = 24;
433             p_bih->biSizeImage      = 0;
434             p_bih->biXPelsPerMeter  = 0;
435             p_bih->biYPelsPerMeter  = 0;
436             p_bih->biClrUsed        = 0;
437             p_bih->biClrImportant   = 0;
438             switch( p_input->p_fmt->i_codec )
439             {
440                 case VLC_CODEC_MP4V:
441                     p_bih->biCompression = VLC_FOURCC( 'X', 'V', 'I', 'D' );
442                     break;
443                 default:
444                     p_bih->biCompression = p_input->p_fmt->i_original_fourcc ?: p_input->p_fmt->i_codec;
445                     break;
446             }
447             p_stream->p_bih = p_bih;
448             break;
449         default:
450             free( p_input->p_sys );
451             p_input->p_sys = NULL;
452             return( VLC_EGENERIC );
453     }
454     p_stream->i_totalsize = 0;
455     p_stream->i_frames    = 0;
456     p_stream->i_duration  = 0;
457
458     /* fixed later */
459     p_stream->f_fps = 25;
460     p_stream->i_bitrate = 128 * 1024;
461
462     p_sys->i_streams++;
463     return( VLC_SUCCESS );
464 }
465
466 static void DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
467 {
468     msg_Dbg( p_mux, "removing input" );
469
470     free( p_input->p_sys );
471 }
472
473 static int Mux      ( sout_mux_t *p_mux )
474 {
475     sout_mux_sys_t  *p_sys = p_mux->p_sys;
476     avi_stream_t    *p_stream;
477     int i_stream, i;
478
479     if( p_sys->b_write_header )
480     {
481         block_t *p_hdr;
482
483         msg_Dbg( p_mux, "writing header" );
484
485         p_hdr = avi_HeaderCreateRIFF( p_mux );
486         sout_AccessOutWrite( p_mux->p_access, p_hdr );
487
488         p_sys->b_write_header = false;
489     }
490
491     for( i = 0; i < p_mux->i_nb_inputs; i++ )
492     {
493         int i_count;
494         block_fifo_t *p_fifo;
495
496         i_stream = *((int*)p_mux->pp_inputs[i]->p_sys );
497         p_stream = &p_sys->stream[i_stream];
498
499         p_fifo = p_mux->pp_inputs[i]->p_fifo;
500         i_count = block_FifoCount(  p_fifo );
501         while( i_count > 1 )
502         {
503             avi_idx1_entry_t *p_idx;
504             block_t *p_data;
505
506             p_data = block_FifoGet( p_fifo );
507             if( block_FifoCount( p_fifo ) > 0 )
508             {
509                 block_t *p_next = block_FifoShow( p_fifo );
510                 p_data->i_length = p_next->i_dts - p_data->i_dts;
511             }
512
513
514             if( p_stream->i_frames == 0 &&p_stream->i_cat == VIDEO_ES )
515             {
516                /* Add header present at the end of BITMAP info header
517                   to first frame in case of XVID */
518                if( p_stream->p_bih->biCompression
519                                == VLC_FOURCC( 'X', 'V', 'I', 'D' ) )
520                {
521                    int i_header_length =
522                        p_stream->p_bih->biSize - sizeof(VLC_BITMAPINFOHEADER);
523                    p_data = block_Realloc( p_data,
524                                    i_header_length, p_data->i_buffer );
525                    if( !p_data)
526                        return VLC_ENOMEM;
527                    memcpy(p_data->p_buffer,&p_stream->p_bih[1], i_header_length);
528                }
529             }
530
531             p_stream->i_frames++;
532             if( p_data->i_length < 0 )
533             {
534                 msg_Warn( p_mux, "argg length < 0 l" );
535                 block_Release( p_data );
536                 i_count--;
537                 continue;
538             }
539             p_stream->i_duration  += p_data->i_length;
540             p_stream->i_totalsize += p_data->i_buffer;
541
542             /* add idx1 entry for this frame */
543             p_idx = &p_sys->idx1.entry[p_sys->idx1.i_entry_count];
544             memcpy( p_idx->fcc, p_stream->fcc, 4 );
545             p_idx->i_flags = 0;
546             if( ( p_data->i_flags & BLOCK_FLAG_TYPE_MASK ) == 0 || ( p_data->i_flags & BLOCK_FLAG_TYPE_I ) )
547                 p_idx->i_flags = AVIIF_KEYFRAME;
548             p_idx->i_pos   = p_sys->i_movi_size + 4;
549             p_idx->i_length= p_data->i_buffer;
550             p_sys->idx1.i_entry_count++;
551             if( p_sys->idx1.i_entry_count >= p_sys->idx1.i_entry_max )
552             {
553                 p_sys->idx1.i_entry_max += 10000;
554                 p_sys->idx1.entry = xrealloc( p_sys->idx1.entry,
555                        p_sys->idx1.i_entry_max * sizeof( avi_idx1_entry_t ) );
556             }
557
558             p_data = block_Realloc( p_data, 8, p_data->i_buffer );
559             if( p_data )
560             {
561                 SetFCC( p_data->p_buffer, p_stream->fcc );
562                 SetDWLE( p_data->p_buffer + 4, p_data->i_buffer - 8 );
563
564                 if( p_data->i_buffer & 0x01 )
565                 {
566                     p_data = block_Realloc( p_data, 0, p_data->i_buffer + 1 );
567                     p_data->p_buffer[ p_data->i_buffer - 1 ] = '\0';
568                 }
569
570                 p_sys->i_movi_size += p_data->i_buffer;
571                 sout_AccessOutWrite( p_mux->p_access, p_data );
572             }
573
574             i_count--;
575         }
576
577     }
578     return( 0 );
579 }
580
581 /****************************************************************************
582  ****************************************************************************
583  **
584  ** avi header generation
585  **
586  ****************************************************************************
587  ****************************************************************************/
588 #define AVI_BOX_ENTER( fcc ) \
589     int i_datasize_offset; \
590     bo_add_fourcc( p_bo, fcc ); \
591     i_datasize_offset = p_bo->b->i_buffer; \
592     bo_add_32le( p_bo, 0 )
593
594 #define AVI_BOX_ENTER_LIST( fcc ) \
595     AVI_BOX_ENTER( "LIST" ); \
596     bo_add_fourcc( p_bo, fcc )
597
598 #define AVI_BOX_EXIT( i_err ) \
599     if( p_bo->b->i_buffer&0x01 ) bo_add_8( p_bo, 0 ); \
600     bo_set_32le( p_bo, i_datasize_offset, p_bo->b->i_buffer - i_datasize_offset - 4 ); \
601     return( i_err );
602
603 static int avi_HeaderAdd_avih( sout_mux_t *p_mux,
604                                bo_t *p_bo )
605 {
606     sout_mux_sys_t  *p_sys = p_mux->p_sys;
607     avi_stream_t    *p_video = NULL;
608     int         i_stream;
609     uint32_t    i_microsecperframe;
610     int         i_maxbytespersec;
611     int         i_totalframes;
612     AVI_BOX_ENTER( "avih" );
613
614     if( p_sys->i_stream_video >= 0 )
615     {
616         p_video = &p_sys->stream[p_sys->i_stream_video];
617         if( p_video->i_frames <= 0 )
618         {
619         //    p_video = NULL;
620         }
621     }
622
623     if( p_video )
624     {
625         i_microsecperframe =
626             (uint32_t)( (float)1000000 /
627                         (float)p_sys->stream[p_sys->i_stream_video].f_fps );
628         i_totalframes = p_sys->stream[p_sys->i_stream_video].i_frames;
629     }
630     else
631     {
632         msg_Warn( p_mux, "avi file without video track isn't a good idea..." );
633         i_microsecperframe = 0;
634         i_totalframes = 0;
635     }
636
637     for( i_stream = 0,i_maxbytespersec = 0; i_stream < p_sys->i_streams; i_stream++ )
638     {
639         if( p_sys->stream[i_stream].i_duration > 0 )
640         {
641             i_maxbytespersec +=
642                 p_sys->stream[i_stream].i_totalsize /
643                 p_sys->stream[i_stream].i_duration;
644         }
645     }
646
647     bo_add_32le( p_bo, i_microsecperframe );
648     bo_add_32le( p_bo, i_maxbytespersec );
649     bo_add_32le( p_bo, 0 );                   /* padding */
650     bo_add_32le( p_bo, AVIF_TRUSTCKTYPE |
651                        AVIF_HASINDEX |
652                        AVIF_ISINTERLEAVED );  /* flags */
653     bo_add_32le( p_bo, i_totalframes );
654     bo_add_32le( p_bo, 0 );                   /* initial frame */
655     bo_add_32le( p_bo, p_sys->i_streams );    /* streams count */
656     bo_add_32le( p_bo, 1024 * 1024 );         /* suggested buffer size */
657     if( p_video )
658     {
659         bo_add_32le( p_bo, p_video->p_bih->biWidth );
660         bo_add_32le( p_bo, p_video->p_bih->biHeight );
661     }
662     else
663     {
664         bo_add_32le( p_bo, 0 );
665         bo_add_32le( p_bo, 0 );
666     }
667     bo_add_32le( p_bo, 0 );                   /* ???? */
668     bo_add_32le( p_bo, 0 );                   /* ???? */
669     bo_add_32le( p_bo, 0 );                   /* ???? */
670     bo_add_32le( p_bo, 0 );                   /* ???? */
671
672     AVI_BOX_EXIT( 0 );
673 }
674 static int avi_HeaderAdd_strh( bo_t *p_bo, avi_stream_t *p_stream )
675 {
676     AVI_BOX_ENTER( "strh" );
677
678     switch( p_stream->i_cat )
679     {
680         case VIDEO_ES:
681             {
682                 bo_add_fourcc( p_bo, "vids" );
683                 bo_add_32be( p_bo, p_stream->p_bih->biCompression );
684                 bo_add_32le( p_bo, 0 );   /* flags */
685                 bo_add_16le(  p_bo, 0 );   /* priority */
686                 bo_add_16le(  p_bo, 0 );   /* langage */
687                 bo_add_32le( p_bo, 0 );   /* initial frame */
688                 bo_add_32le( p_bo, 1000 );/* scale */
689                 bo_add_32le( p_bo, (uint32_t)( 1000 * p_stream->f_fps ));
690                 bo_add_32le( p_bo, 0 );   /* start */
691                 bo_add_32le( p_bo, p_stream->i_frames );
692                 bo_add_32le( p_bo, 1024 * 1024 );
693                 bo_add_32le( p_bo, -1 );  /* quality */
694                 bo_add_32le( p_bo, 0 );   /* samplesize */
695                 bo_add_16le(  p_bo, 0 );   /* ??? */
696                 bo_add_16le(  p_bo, 0 );   /* ??? */
697                 bo_add_16le(  p_bo, p_stream->p_bih->biWidth );
698                 bo_add_16le(  p_bo, p_stream->p_bih->biHeight );
699             }
700             break;
701         case AUDIO_ES:
702             {
703                 int i_rate, i_scale, i_samplesize;
704
705                 i_samplesize = p_stream->p_wf->nBlockAlign;
706                 if( i_samplesize > 1 )
707                 {
708                     i_scale = i_samplesize;
709                     i_rate = /*i_scale **/ p_stream->i_bitrate / 8;
710                 }
711                 else
712                 {
713                     i_samplesize = 1;
714                     i_scale = 1000;
715                     i_rate = 1000 * p_stream->i_bitrate / 8;
716                 }
717                 bo_add_fourcc( p_bo, "auds" );
718                 bo_add_32le( p_bo, 0 );   /* tag */
719                 bo_add_32le( p_bo, 0 );   /* flags */
720                 bo_add_16le(  p_bo, 0 );   /* priority */
721                 bo_add_16le(  p_bo, 0 );   /* langage */
722                 bo_add_32le( p_bo, 0 );   /* initial frame */
723                 bo_add_32le( p_bo, i_scale );/* scale */
724                 bo_add_32le( p_bo, i_rate );
725                 bo_add_32le( p_bo, 0 );   /* start */
726                 bo_add_32le( p_bo, p_stream->i_frames );
727                 bo_add_32le( p_bo, 10 * 1024 );
728                 bo_add_32le( p_bo, -1 );  /* quality */
729                 bo_add_32le( p_bo, i_samplesize );
730                 bo_add_16le(  p_bo, 0 );   /* ??? */
731                 bo_add_16le(  p_bo, 0 );   /* ??? */
732                 bo_add_16le(  p_bo, 0 );
733                 bo_add_16le(  p_bo, 0 );
734             }
735             break;
736     }
737
738     AVI_BOX_EXIT( 0 );
739 }
740
741 static int avi_HeaderAdd_strf( bo_t *p_bo, avi_stream_t *p_stream )
742 {
743     AVI_BOX_ENTER( "strf" );
744
745     switch( p_stream->i_cat )
746     {
747         case AUDIO_ES:
748             bo_add_16le( p_bo, p_stream->p_wf->wFormatTag );
749             bo_add_16le( p_bo, p_stream->p_wf->nChannels );
750             bo_add_32le( p_bo, p_stream->p_wf->nSamplesPerSec );
751             bo_add_32le( p_bo, p_stream->p_wf->nAvgBytesPerSec );
752             bo_add_16le( p_bo, p_stream->p_wf->nBlockAlign );
753             bo_add_16le( p_bo, p_stream->p_wf->wBitsPerSample );
754             bo_add_16le( p_bo, p_stream->p_wf->cbSize );
755             bo_add_mem( p_bo, p_stream->p_wf->cbSize, (uint8_t*)&p_stream->p_wf[1] );
756             break;
757         case VIDEO_ES:
758             bo_add_32le( p_bo, p_stream->p_bih->biSize );
759             bo_add_32le( p_bo, p_stream->p_bih->biWidth );
760             bo_add_32le( p_bo, p_stream->p_bih->biHeight );
761             bo_add_16le( p_bo, p_stream->p_bih->biPlanes );
762             bo_add_16le( p_bo, p_stream->p_bih->biBitCount );
763             if( VLC_FOURCC( 0, 0, 0, 1 ) == 0x00000001 )
764             {
765                 bo_add_32be( p_bo, p_stream->p_bih->biCompression );
766             }
767             else
768             {
769                 bo_add_32le( p_bo, p_stream->p_bih->biCompression );
770             }
771             bo_add_32le( p_bo, p_stream->p_bih->biSizeImage );
772             bo_add_32le( p_bo, p_stream->p_bih->biXPelsPerMeter );
773             bo_add_32le( p_bo, p_stream->p_bih->biYPelsPerMeter );
774             bo_add_32le( p_bo, p_stream->p_bih->biClrUsed );
775             bo_add_32le( p_bo, p_stream->p_bih->biClrImportant );
776             bo_add_mem( p_bo,
777                         p_stream->p_bih->biSize - sizeof( VLC_BITMAPINFOHEADER ),
778                         (uint8_t*)&p_stream->p_bih[1] );
779             break;
780     }
781
782     AVI_BOX_EXIT( 0 );
783 }
784
785 static int avi_HeaderAdd_strl( bo_t *p_bo, avi_stream_t *p_stream )
786 {
787     AVI_BOX_ENTER_LIST( "strl" );
788
789     avi_HeaderAdd_strh( p_bo, p_stream );
790     avi_HeaderAdd_strf( p_bo, p_stream );
791
792     AVI_BOX_EXIT( 0 );
793 }
794
795 static int avi_HeaderAdd_meta( bo_t *p_bo, const char psz_meta[4],
796                                const char *psz_data )
797 {
798     if ( psz_data == NULL ) return 1;
799     const char *psz = psz_data;
800     AVI_BOX_ENTER( psz_meta );
801     while (*psz) bo_add_8( p_bo, *psz++ );
802     bo_add_8( p_bo, 0 );
803     AVI_BOX_EXIT( 0 );
804 }
805
806 static int avi_HeaderAdd_INFO( sout_mux_t *p_mux, bo_t *p_bo )
807 {
808     char *psz;
809
810 #define APPLY_META(var, fourcc) \
811     psz = var_InheritString( p_mux, SOUT_CFG_PREFIX var );\
812     if ( psz )\
813     {\
814         avi_HeaderAdd_meta( p_bo, fourcc, psz );\
815         free( psz );\
816     }
817
818     AVI_BOX_ENTER_LIST( "INFO" );
819
820     APPLY_META( "artist",   "IART")
821     APPLY_META( "comment",  "ICMT")
822     APPLY_META( "copyright","ICOP")
823     APPLY_META( "date",     "ICRD")
824     APPLY_META( "genre",    "IGNR")
825     APPLY_META( "name",     "INAM")
826     APPLY_META( "keywords", "IKEY")
827     APPLY_META( "subject",  "ISBJ")
828     APPLY_META( "encoder",  "ISFT")
829     /* Some are missing, but are they really useful ?? */
830
831 #undef APPLY_META
832
833     AVI_BOX_EXIT( 0 );
834 }
835
836 static block_t *avi_HeaderCreateRIFF( sout_mux_t *p_mux )
837 {
838     sout_mux_sys_t      *p_sys = p_mux->p_sys;
839     int                 i_stream;
840     int                 i_junk;
841     bo_t                bo;
842
843     struct
844     {
845         int i_riffsize;
846         int i_hdrllistsize;
847         int i_hdrldatastart;
848     } offsets;
849
850     bo_init( &bo, HDR_BASE_SIZE );
851
852     bo_add_fourcc( &bo, "RIFF" );
853     offsets.i_riffsize = bo.b->i_buffer;
854     bo_add_32le( &bo, 0xEFBEADDE );
855     bo_add_fourcc( &bo, "AVI " );
856
857     bo_add_fourcc( &bo, "LIST" );
858     /* HDRL List size should exclude following data in HDR buffer
859      *  -12 (RIFF, RIFF size, 'AVI ' tag),
860      *  - 8 (hdr1 LIST tag and its size)
861      *  - 12 (movi LIST tag, size, 'movi' listType )
862      */
863     offsets.i_hdrllistsize = bo.b->i_buffer;
864     bo_add_32le( &bo, 0xEFBEADDE );
865     bo_add_fourcc( &bo, "hdrl" );
866     offsets.i_hdrldatastart = bo.b->i_buffer;
867
868     avi_HeaderAdd_avih( p_mux, &bo );
869     for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
870     {
871         avi_HeaderAdd_strl( &bo, &p_sys->stream[i_stream] );
872     }
873
874     /* align on 16 bytes */
875     int i_align = ( ( bo.b->i_buffer + 12 + 0xE ) & ~ 0xF );
876     i_junk = i_align - bo.b->i_buffer;
877     bo_add_fourcc( &bo, "JUNK" );
878     bo_add_32le( &bo, i_junk );
879     for( int i=0; i< i_junk; i++ )
880     {
881         bo_add_8( &bo, 0 );
882     }
883
884     /* Now set hdrl size */
885     bo_set_32le( &bo, offsets.i_hdrllistsize,
886                  bo.b->i_buffer - offsets.i_hdrldatastart );
887
888     avi_HeaderAdd_INFO( p_mux, &bo );
889
890     bo_add_fourcc( &bo, "LIST" );
891     bo_add_32le( &bo, p_sys->i_movi_size + 4 );
892     bo_add_fourcc( &bo, "movi" );
893
894     /* Now set RIFF size */
895     bo_set_32le( &bo, offsets.i_riffsize, bo.b->i_buffer - 8
896                  + p_sys->i_movi_size + p_sys->i_idx1_size );
897
898     return( bo.b );
899 }
900
901 static block_t * avi_HeaderCreateidx1( sout_mux_t *p_mux )
902 {
903     sout_mux_sys_t      *p_sys = p_mux->p_sys;
904     uint32_t            i_idx1_size;
905     bo_t                bo;
906
907     i_idx1_size = 16 * p_sys->idx1.i_entry_count + 8;
908
909     bo_init( &bo, i_idx1_size );
910     memset( bo.b->p_buffer, 0, i_idx1_size);
911
912     bo_add_fourcc( &bo, "idx1" );
913     bo_add_32le( &bo, i_idx1_size - 8);
914
915     for( unsigned i = 0; i < p_sys->idx1.i_entry_count; i++ )
916     {
917         bo_add_fourcc( &bo, p_sys->idx1.entry[i].fcc );
918         bo_add_32le( &bo, p_sys->idx1.entry[i].i_flags );
919         bo_add_32le( &bo, p_sys->idx1.entry[i].i_pos );
920         bo_add_32le( &bo, p_sys->idx1.entry[i].i_length );
921     }
922
923     return( bo.b );
924 }