8b409d1cb9540acdc5f8b943db44895fba32b31d
[vlc.git] / modules / stream_out / transcode.c
1 /*****************************************************************************
2  * transcode.c: transcoding stream output module
3  *****************************************************************************
4  * Copyright (C) 2003-2004 VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gildas Bazin <gbazin@netcourrier.com>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <stdlib.h>
29 #include <string.h>
30
31 #include <vlc/vlc.h>
32 #include <vlc/input.h>
33 #include <vlc/sout.h>
34 #include <vlc/vout.h>
35 #include <vlc/decoder.h>
36
37 /* ffmpeg header */
38 #ifdef HAVE_FFMPEG_AVCODEC_H
39 #   include <ffmpeg/avcodec.h>
40 #else
41 #   include <avcodec.h>
42 #endif
43
44 #if LIBAVCODEC_BUILD < 4704
45 #   define AV_NOPTS_VALUE 0
46 #endif
47
48 /*****************************************************************************
49  * Exported prototypes
50  *****************************************************************************/
51 static int      Open    ( vlc_object_t * );
52 static void     Close   ( vlc_object_t * );
53
54 static sout_stream_id_t *Add ( sout_stream_t *, es_format_t * );
55 static int               Del ( sout_stream_t *, sout_stream_id_t * );
56 static int               Send( sout_stream_t *, sout_stream_id_t *, sout_buffer_t* );
57
58 static int  transcode_audio_ffmpeg_new    ( sout_stream_t *, sout_stream_id_t * );
59 static void transcode_audio_ffmpeg_close  ( sout_stream_t *, sout_stream_id_t * );
60 static int  transcode_audio_ffmpeg_process( sout_stream_t *, sout_stream_id_t *, sout_buffer_t *, sout_buffer_t ** );
61
62 static int  transcode_video_ffmpeg_new    ( sout_stream_t *, sout_stream_id_t * );
63 static void transcode_video_ffmpeg_close  ( sout_stream_t *, sout_stream_id_t * );
64 static int  transcode_video_ffmpeg_process( sout_stream_t *, sout_stream_id_t *, sout_buffer_t *, sout_buffer_t ** );
65
66 static int  transcode_video_ffmpeg_getframebuf( struct AVCodecContext *, AVFrame *);
67
68 static int  EncoderThread( struct sout_stream_sys_t * p_sys );
69
70 static int pi_channels_maps[6] =
71 {
72     0,
73     AOUT_CHAN_CENTER,   AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
74     AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
75     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
76      | AOUT_CHAN_REARRIGHT,
77     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
78      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
79 };
80
81 /*****************************************************************************
82  * Module descriptor
83  *****************************************************************************/
84 vlc_module_begin();
85     set_description( _("Transcode stream output") );
86     set_capability( "sout stream", 50 );
87     add_shortcut( "transcode" );
88     set_callbacks( Open, Close );
89 vlc_module_end();
90
91 #define PICTURE_RING_SIZE 64
92
93 struct sout_stream_sys_t
94 {
95     VLC_COMMON_MEMBERS
96
97     sout_stream_t * p_out;
98     sout_stream_id_t * id_video;
99     sout_buffer_t * p_buffers;
100     vlc_mutex_t     lock_out;
101     vlc_cond_t      cond;
102     picture_t *     pp_pics[PICTURE_RING_SIZE];
103     int             i_first_pic, i_last_pic;
104
105     vlc_fourcc_t    i_acodec;   /* codec audio (0 if not transcode) */
106     int             i_sample_rate;
107     int             i_channels;
108     int             i_abitrate;
109
110     vlc_fourcc_t    i_vcodec;   /*    "   video  " "   "      " */
111     int             i_vbitrate;
112     int             i_vtolerance;
113     double          f_scale;
114     int             i_width;
115     int             i_height;
116     int             i_b_frames;
117     int             i_key_int;
118     int             i_qmin;
119     int             i_qmax;
120     vlc_bool_t      i_hq;
121     vlc_bool_t      b_deinterlace;
122     vlc_bool_t      b_interlace;
123     vlc_bool_t      b_strict_rc;
124     vlc_bool_t      b_pre_me;
125     vlc_bool_t      b_hurry_up;
126     int             i_rc_buffer_size;
127     float           f_rc_buffer_aggressivity;
128     float           f_i_quant_factor;
129     int             i_noise_reduction;
130     vlc_bool_t      b_mpeg4_matrix;
131     int             i_threads;
132     vlc_bool_t      b_trellis;
133
134     int             i_crop_top;
135     int             i_crop_bottom;
136     int             i_crop_right;
137     int             i_crop_left;
138
139     mtime_t         i_input_dts;
140     mtime_t         i_input_pts;
141     vlc_bool_t      b_input_has_b_frames;
142
143     mtime_t         i_output_pts;
144 };
145
146 /*****************************************************************************
147  * Open:
148  *****************************************************************************/
149 static int Open( vlc_object_t *p_this )
150 {
151     sout_stream_t     *p_stream = (sout_stream_t*)p_this;
152     sout_stream_sys_t *p_sys;
153     char *codec;
154
155     p_sys = vlc_object_create( p_this, sizeof( sout_stream_sys_t ) );
156     p_sys->p_out = sout_stream_new( p_stream->p_sout, p_stream->psz_next );
157
158     p_sys->f_scale      = 1;
159     p_sys->i_vtolerance = -1;
160     p_sys->i_key_int    = -1;
161     p_sys->i_qmin       = 2;
162     p_sys->i_qmax       = 31;
163     p_sys->f_i_quant_factor = 0.0;
164 #if LIBAVCODEC_BUILD >= 4673
165     p_sys->i_hq         = FF_MB_DECISION_SIMPLE;
166 #else
167     p_sys->i_hq         = VLC_FALSE;
168 #endif
169     p_sys->i_rc_buffer_size = 224*1024*8 * 3/2;
170     p_sys->f_rc_buffer_aggressivity = 0.1;
171     p_sys->i_threads = 0;
172     p_sys->b_trellis = 0;
173     p_sys->b_input_has_b_frames = VLC_FALSE;
174     p_sys->i_output_pts = 0;
175
176     if( ( codec = sout_cfg_find_value( p_stream->p_cfg, "acodec" ) ) )
177     {
178         char fcc[4] = "    ";
179         char *val;
180
181         memcpy( fcc, codec, __MIN( strlen( codec ), 4 ) );
182
183         p_sys->i_acodec = VLC_FOURCC( fcc[0], fcc[1], fcc[2], fcc[3] );
184
185         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "samplerate" ) ) )
186         {
187             p_sys->i_sample_rate = atoi( val );
188         }
189         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "channels" ) ) )
190         {
191             p_sys->i_channels = atoi( val );
192         }
193         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "ab" ) ) )
194         {
195             p_sys->i_abitrate = atoi( val );
196             if( p_sys->i_abitrate < 4000 )
197             {
198                 p_sys->i_abitrate *= 1000;
199             }
200         }
201
202         msg_Dbg( p_stream, "codec audio=%4.4s %dHz %d channels %dKb/s", fcc,
203                  p_sys->i_sample_rate, p_sys->i_channels,
204                  p_sys->i_abitrate / 1000 );
205     }
206
207     if( ( codec = sout_cfg_find_value( p_stream->p_cfg, "vcodec" ) ) )
208     {
209         char fcc[4] = "    ";
210         char *val;
211
212         memcpy( fcc, codec, __MIN( strlen( codec ), 4 ) );
213
214         p_sys->i_vcodec = VLC_FOURCC( fcc[0], fcc[1], fcc[2], fcc[3] );
215
216         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "scale" ) ) )
217         {
218             p_sys->f_scale = atof( val );
219         }
220         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "width" ) ) )
221         {
222             p_sys->i_width = atoi( val );
223         }
224         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "height" ) ) )
225         {
226             p_sys->i_height = atoi( val );
227         }
228         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "vb" ) ) )
229         {
230             p_sys->i_vbitrate = atoi( val );
231             if( p_sys->i_vbitrate < 16000 )
232             {
233                 p_sys->i_vbitrate *= 1000;
234             }
235         }
236         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "vt" ) ) )
237         {
238             p_sys->i_vtolerance = atoi( val );
239         }
240         if( sout_cfg_find( p_stream->p_cfg, "deinterlace" ) )
241         {
242             p_sys->b_deinterlace = VLC_TRUE;
243         }
244         if( sout_cfg_find( p_stream->p_cfg, "interlace" ) )
245         {
246             p_sys->b_interlace = VLC_TRUE;
247         }
248         if( sout_cfg_find( p_stream->p_cfg, "strict_rc" ) )
249         {
250             p_sys->b_strict_rc = VLC_TRUE;
251         }
252         if( sout_cfg_find( p_stream->p_cfg, "pre_me" ) )
253         {
254             p_sys->b_pre_me = VLC_TRUE;
255         }
256         if( sout_cfg_find( p_stream->p_cfg, "hurry_up" ) )
257         {
258             p_sys->b_hurry_up = VLC_TRUE;
259             /* hurry up mode needs noise reduction, even small */
260             p_sys->i_noise_reduction = 1;
261         }
262         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "rc_buffer_size" ) ) )
263         {
264             p_sys->i_rc_buffer_size = atoi( val );
265         }
266         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "rc_buffer_aggressivity" ) ) )
267         {
268             p_sys->f_rc_buffer_aggressivity = atof( val );
269         }
270         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "i_quant_factor" ) ) )
271         {
272             p_sys->f_i_quant_factor = atof( val );
273         }
274         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "noise_reduction" ) ) )
275         {
276             p_sys->i_noise_reduction = atoi( val );
277         }
278         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "mpeg4_matrix" ) ) )
279         {
280             p_sys->b_mpeg4_matrix = VLC_TRUE;
281         }
282         /* crop */
283         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "croptop" ) ) )
284         {
285             p_sys->i_crop_top = atoi( val );
286         }
287         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "cropbottom" ) ) )
288         {
289             p_sys->i_crop_bottom = atoi( val );
290         }
291         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "cropleft" ) ) )
292         {
293             p_sys->i_crop_left = atoi( val );
294         }
295         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "cropright" ) ) )
296         {
297             p_sys->i_crop_right = atoi( val );
298         }
299         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "keyint" ) ) )
300         {
301             p_sys->i_key_int    = atoi( val );
302         }
303         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "bframes" ) ) )
304         {
305             p_sys->i_b_frames   = atoi( val );
306         }
307 #if LIBAVCODEC_BUILD >= 4673
308         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "hq" ) ) )
309         {
310             if( !strcmp( val, "rd" ) )
311             {
312                 p_sys->i_hq = FF_MB_DECISION_RD;
313             }
314             else if( !strcmp( val, "bits" ) )
315             {
316                 p_sys->i_hq = FF_MB_DECISION_BITS;
317             }
318             else if( !strcmp( val, "simple" ) )
319             {
320                 p_sys->i_hq = FF_MB_DECISION_SIMPLE;
321             }
322             else
323             {
324                 p_sys->i_hq = FF_MB_DECISION_RD;
325             }
326         }
327 #else
328         if( sout_cfg_find( p_stream->p_cfg, "hq" ) )
329         {
330             p_sys->i_hq = VLC_TRUE;
331         }
332 #endif
333         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "qmin" ) ) )
334         {
335             p_sys->i_qmin   = atoi( val );
336         }
337         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "qmax" ) ) )
338         {
339             p_sys->i_qmax   = atoi( val );
340         }
341         if( ( val = sout_cfg_find_value( p_stream->p_cfg, "threads" ) ) )
342         {
343             p_sys->i_threads = atoi( val );
344         }
345         if( sout_cfg_find( p_stream->p_cfg, "trellis" ) )
346         {
347             p_sys->b_trellis = VLC_TRUE;
348         }
349
350         msg_Dbg( p_stream, "codec video=%4.4s %dx%d scaling: %f %dkb/s",
351                  fcc, p_sys->i_width, p_sys->i_height, p_sys->f_scale,
352                  p_sys->i_vbitrate / 1000 );
353     }
354
355     if( !p_sys->p_out )
356     {
357         msg_Err( p_stream, "cannot create chain" );
358         free( p_sys );
359         return VLC_EGENERIC;
360     }
361
362     p_stream->pf_add    = Add;
363     p_stream->pf_del    = Del;
364     p_stream->pf_send   = Send;
365     p_stream->p_sys     = p_sys;
366
367     avcodec_init();
368     avcodec_register_all();
369
370     /* ffmpeg needs some padding at the end of each buffer */
371     p_stream->p_sout->i_padding += FF_INPUT_BUFFER_PADDING_SIZE;
372
373     return VLC_SUCCESS;
374 }
375
376 /*****************************************************************************
377  * Close:
378  *****************************************************************************/
379 static void Close( vlc_object_t * p_this )
380 {
381     sout_stream_t       *p_stream = (sout_stream_t*)p_this;
382     sout_stream_sys_t   *p_sys = p_stream->p_sys;
383
384     sout_stream_delete( p_sys->p_out );
385     vlc_object_destroy( p_sys );
386 }
387
388 struct sout_stream_id_t
389 {
390     vlc_fourcc_t  b_transcode;
391     es_format_t f_src;        /* only if transcoding */
392     es_format_t f_dst;        /*  "   "      " */
393     unsigned int  i_inter_pixfmt; /* intermediary format when transcoding */
394
395     /* id of the out stream */
396     void *id;
397
398     /* Encoder */
399     encoder_t       *p_encoder;
400     vlc_fourcc_t    b_enc_inited;
401
402     /* ffmpeg part */
403     AVCodec         *ff_dec;
404     AVCodecContext  *ff_dec_c;
405
406     mtime_t         i_dts;
407     mtime_t         i_length;
408
409     int             i_buffer;
410     int             i_buffer_pos;
411     uint8_t         *p_buffer;
412
413     AVFrame         *p_ff_pic;
414     AVFrame         *p_ff_pic_tmp0; /* to do deinterlace */
415     AVFrame         *p_ff_pic_tmp1; /* to do pix conversion */
416     AVFrame         *p_ff_pic_tmp2; /* to do resample */
417
418     ImgReSampleContext *p_vresample;
419 };
420
421
422 static sout_stream_id_t * Add( sout_stream_t *p_stream, es_format_t *p_fmt )
423 {
424     sout_stream_sys_t   *p_sys = p_stream->p_sys;
425     sout_stream_id_t    *id;
426
427     id = malloc( sizeof( sout_stream_id_t ) );
428     id->i_dts = 0;
429     id->id = NULL;
430     id->p_encoder = NULL;
431
432     if( p_fmt->i_cat == AUDIO_ES && p_sys->i_acodec != 0 )
433     {
434         msg_Dbg( p_stream,
435                  "creating audio transcoding from fcc=`%4.4s' to fcc=`%4.4s'",
436                  (char*)&p_fmt->i_codec,
437                  (char*)&p_sys->i_acodec );
438
439         /* src format */
440         memcpy( &id->f_src, p_fmt, sizeof( es_format_t ) );
441
442         /* create dst format */
443         es_format_Init( &id->f_dst, AUDIO_ES, p_sys->i_acodec );
444         id->f_dst.i_id    = id->f_src.i_id;
445         id->f_dst.i_group = id->f_src.i_group;
446         if( id->f_src.psz_language ) id->f_dst.psz_language = strdup( id->f_src.psz_language );
447         id->f_dst.audio.i_rate = p_sys->i_sample_rate  > 0 ? p_sys->i_sample_rate : id->f_src.audio.i_rate;
448         id->f_dst.audio.i_channels    = p_sys->i_channels > 0 ? p_sys->i_channels : id->f_src.audio.i_channels;
449         id->f_dst.i_bitrate     = p_sys->i_abitrate > 0 ? p_sys->i_abitrate : 64000;
450         id->f_dst.audio.i_blockalign = 0;
451         id->f_dst.i_extra  = 0;
452         id->f_dst.p_extra  = NULL;
453
454         /* build decoder -> filter -> encoder */
455         if( transcode_audio_ffmpeg_new( p_stream, id ) )
456         {
457             msg_Err( p_stream, "cannot create audio chain" );
458             free( id );
459             return NULL;
460         }
461
462         /* open output stream */
463         id->id = p_sys->p_out->pf_add( p_sys->p_out, &id->f_dst );
464         id->b_transcode = VLC_TRUE;
465
466         if( id->id == NULL )
467         {
468             free( id );
469             return NULL;
470         }
471     }
472     else if( p_fmt->i_cat == VIDEO_ES && p_sys->i_vcodec != 0 )
473     {
474         msg_Dbg( p_stream,
475                  "creating video transcoding from fcc=`%4.4s' to fcc=`%4.4s'",
476                  (char*)&p_fmt->i_codec,
477                  (char*)&p_sys->i_vcodec );
478
479         memcpy( &id->f_src, p_fmt, sizeof( es_format_t ) );
480
481         /* create dst format */
482         es_format_Init( &id->f_dst, VIDEO_ES, p_sys->i_vcodec );
483         id->f_dst.i_id    = id->f_src.i_id;
484         id->f_dst.i_group = id->f_src.i_group;
485         if( id->f_src.psz_language ) id->f_dst.psz_language = strdup( id->f_src.psz_language );
486         id->f_dst.video.i_width = p_sys->i_width;
487         id->f_dst.video.i_height= p_sys->i_height;
488         id->f_dst.i_bitrate     = p_sys->i_vbitrate > 0 ? p_sys->i_vbitrate : 800*1000;
489         id->f_dst.i_extra       = 0;
490         id->f_dst.p_extra       = NULL;
491
492         /* build decoder -> filter -> encoder */
493         if( transcode_video_ffmpeg_new( p_stream, id ) )
494         {
495             msg_Err( p_stream, "cannot create video chain" );
496             free( id );
497             return NULL;
498         }
499 #if 0
500         /* open output stream */
501         id->id = p_sys->p_out->pf_add( p_sys->p_out, &id->f_dst );
502 #endif
503         id->b_transcode = VLC_TRUE;
504     }
505     else
506     {
507         msg_Dbg( p_stream, "not transcoding a stream (fcc=`%4.4s')", (char*)&p_fmt->i_codec );
508         id->id = p_sys->p_out->pf_add( p_sys->p_out, p_fmt );
509         id->b_transcode = VLC_FALSE;
510
511         if( id->id == NULL )
512         {
513             free( id );
514             return NULL;
515         }
516     }
517
518     return id;
519 }
520
521 static int     Del      ( sout_stream_t *p_stream, sout_stream_id_t *id )
522 {
523     sout_stream_sys_t   *p_sys = p_stream->p_sys;
524
525     if( id->b_transcode )
526     {
527         if( id->f_src.i_cat == AUDIO_ES )
528         {
529             transcode_audio_ffmpeg_close( p_stream, id );
530         }
531         else if( id->f_src.i_cat == VIDEO_ES )
532         {
533             transcode_video_ffmpeg_close( p_stream, id );
534         }
535     }
536
537     if( id->id ) p_sys->p_out->pf_del( p_sys->p_out, id->id );
538     free( id );
539
540     return VLC_SUCCESS;
541 }
542
543 static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
544                  sout_buffer_t *p_buffer )
545 {
546     sout_stream_sys_t   *p_sys = p_stream->p_sys;
547
548     if( id->b_transcode )
549     {
550         sout_buffer_t *p_buffer_out;
551         if( id->f_src.i_cat == AUDIO_ES )
552         {
553             transcode_audio_ffmpeg_process( p_stream, id, p_buffer,
554                                             &p_buffer_out );
555         }
556         else if( id->f_src.i_cat == VIDEO_ES )
557         {
558             if( transcode_video_ffmpeg_process( p_stream, id, p_buffer,
559                 &p_buffer_out ) != VLC_SUCCESS )
560             {
561                 sout_BufferDelete( p_stream->p_sout, p_buffer );
562                 return VLC_EGENERIC;
563             }
564         }
565         sout_BufferDelete( p_stream->p_sout, p_buffer );
566
567         if( p_buffer_out )
568         {
569             return p_sys->p_out->pf_send( p_sys->p_out, id->id, p_buffer_out );
570         }
571         return VLC_SUCCESS;
572     }
573     else if( id->id != NULL )
574     {
575         return p_sys->p_out->pf_send( p_sys->p_out, id->id, p_buffer );
576     }
577     else
578     {
579         sout_BufferDelete( p_stream->p_sout, p_buffer );
580         return VLC_EGENERIC;
581     }
582 }
583
584 /****************************************************************************
585  * ffmpeg decoder reencocdr part
586  ****************************************************************************/
587
588 static struct
589 {
590     vlc_fourcc_t i_fcc;
591     int          i_ff_codec;
592 } fourcc_to_ff_code[] =
593 {
594     /* audio */
595     { VLC_FOURCC( 'm', 'p', 'g', 'a' ), CODEC_ID_MP2 },
596     { VLC_FOURCC( 'm', 'p', '3', ' ' ), CODEC_ID_MP3LAME },
597     { VLC_FOURCC( 'm', 'p', '4', 'a' ), CODEC_ID_AAC },
598     { VLC_FOURCC( 'a', '5', '2', ' ' ), CODEC_ID_AC3 },
599     { VLC_FOURCC( 'a', 'c', '3', ' ' ), CODEC_ID_AC3 },
600     { VLC_FOURCC( 'w', 'm', 'a', '1' ), CODEC_ID_WMAV1 },
601     { VLC_FOURCC( 'w', 'm', 'a', '2' ), CODEC_ID_WMAV2 },
602     { VLC_FOURCC( 'v', 'o', 'r', 'b' ), CODEC_ID_VORBIS },
603     { VLC_FOURCC( 'a', 'l', 'a', 'w' ), CODEC_ID_PCM_ALAW },
604
605     /* video */
606     { VLC_FOURCC( 'm', 'p', 'g', 'v' ), CODEC_ID_MPEG1VIDEO },
607     { VLC_FOURCC( 'm', 'p', '1', 'v' ), CODEC_ID_MPEG1VIDEO },
608 #if LIBAVCODEC_BUILD >= 4676
609     { VLC_FOURCC( 'm', 'p', '2', 'v' ), CODEC_ID_MPEG2VIDEO },
610 #endif
611     { VLC_FOURCC( 'm', 'p', '4', 'v'),  CODEC_ID_MPEG4 },
612     { VLC_FOURCC( 'D', 'I', 'V', '1' ), CODEC_ID_MSMPEG4V1 },
613     { VLC_FOURCC( 'D', 'I', 'V', '2' ), CODEC_ID_MSMPEG4V2 },
614     { VLC_FOURCC( 'D', 'I', 'V', '3' ), CODEC_ID_MSMPEG4V3 },
615     { VLC_FOURCC( 'H', '2', '6', '3' ), CODEC_ID_H263 },
616     { VLC_FOURCC( 'I', '2', '6', '3' ), CODEC_ID_H263I },
617     { VLC_FOURCC( 'h', 'u', 'f', 'f' ), CODEC_ID_HUFFYUV },
618     { VLC_FOURCC( 'W', 'M', 'V', '1' ), CODEC_ID_WMV1 },
619     { VLC_FOURCC( 'W', 'M', 'V', '2' ), CODEC_ID_WMV2 },
620     { VLC_FOURCC( 'M', 'J', 'P', 'G' ), CODEC_ID_MJPEG },
621     { VLC_FOURCC( 'm', 'j', 'p', 'b' ), CODEC_ID_MJPEGB },
622     { VLC_FOURCC( 'd', 'v', 's', 'l' ), CODEC_ID_DVVIDEO },
623     { VLC_FOURCC( 'S', 'V', 'Q', '1' ), CODEC_ID_SVQ1 },
624 #if LIBAVCODEC_BUILD >= 4666
625     { VLC_FOURCC( 'S', 'V', 'Q', '3' ), CODEC_ID_SVQ3 },
626 #endif
627
628     /* raw video code, only used for 'encoding' */
629     { VLC_FOURCC( 'I', '4', '2', '0' ), CODEC_ID_RAWVIDEO },
630     { VLC_FOURCC( 'I', '4', '2', '2' ), CODEC_ID_RAWVIDEO },
631     { VLC_FOURCC( 'I', '4', '4', '4' ), CODEC_ID_RAWVIDEO },
632     { VLC_FOURCC( 'R', 'V', '1', '5' ), CODEC_ID_RAWVIDEO },
633     { VLC_FOURCC( 'R', 'V', '1', '6' ), CODEC_ID_RAWVIDEO },
634     { VLC_FOURCC( 'R', 'V', '2', '4' ), CODEC_ID_RAWVIDEO },
635     { VLC_FOURCC( 'R', 'V', '3', '2' ), CODEC_ID_RAWVIDEO },
636     { VLC_FOURCC( 'Y', 'U', 'Y', '2' ), CODEC_ID_RAWVIDEO },
637     { VLC_FOURCC( 'Y', 'V', '1', '2' ), CODEC_ID_RAWVIDEO },
638     { VLC_FOURCC( 'I', 'Y', 'U', 'V' ), CODEC_ID_RAWVIDEO },
639
640     { VLC_FOURCC(   0,   0,   0,   0 ), 0 }
641 };
642
643 static inline int get_ff_codec( vlc_fourcc_t i_fcc )
644 {
645     int i;
646
647     for( i = 0; fourcc_to_ff_code[i].i_fcc != 0; i++ )
648     {
649         if( fourcc_to_ff_code[i].i_fcc == i_fcc )
650         {
651             return fourcc_to_ff_code[i].i_ff_codec;
652         }
653     }
654
655     return 0;
656 }
657
658 static inline int get_ff_chroma( vlc_fourcc_t i_chroma )
659 {
660     switch( i_chroma )
661     {
662         case VLC_FOURCC( 'Y', 'V', '1', '2' ):
663         case VLC_FOURCC( 'I', 'Y', 'U', 'V' ):
664         case VLC_FOURCC( 'I', '4', '2', '0' ):
665             return PIX_FMT_YUV420P;
666         case VLC_FOURCC( 'I', '4', '2', '2' ):
667             return PIX_FMT_YUV422P;
668         case VLC_FOURCC( 'I', '4', '4', '4' ):
669             return PIX_FMT_YUV444P;
670         case VLC_FOURCC( 'R', 'V', '1', '5' ):
671             return PIX_FMT_RGB555;
672         case VLC_FOURCC( 'R', 'V', '1', '6' ):
673             return PIX_FMT_RGB565;
674         case VLC_FOURCC( 'R', 'V', '2', '4' ):
675             return PIX_FMT_BGR24;
676         case VLC_FOURCC( 'R', 'V', '3', '2' ):
677             return PIX_FMT_RGBA32;
678         case VLC_FOURCC( 'G', 'R', 'E', 'Y' ):
679             return PIX_FMT_GRAY8;
680         case VLC_FOURCC( 'Y', 'U', 'Y', '2' ):
681             return PIX_FMT_YUV422;
682         default:
683             return 0;
684     }
685 }
686
687 static inline vlc_fourcc_t get_vlc_chroma( int i_pix_fmt )
688 {
689     switch( i_pix_fmt )
690     {
691     case PIX_FMT_YUV420P:
692         return VLC_FOURCC('I','4','2','0');
693     case PIX_FMT_YUV422P:
694         return VLC_FOURCC('I','4','2','2');
695     case PIX_FMT_YUV444P:
696         return VLC_FOURCC('I','4','4','4');
697
698     case PIX_FMT_YUV422:
699         return VLC_FOURCC('Y','U','Y','2');
700
701     case PIX_FMT_RGB555:
702         return VLC_FOURCC('R','V','1','5');
703     case PIX_FMT_RGB565:
704         return VLC_FOURCC('R','V','1','6');
705     case PIX_FMT_RGB24:
706         return VLC_FOURCC('R','V','2','4');
707     case PIX_FMT_RGBA32:
708         return VLC_FOURCC('R','V','3','2');
709     case PIX_FMT_GRAY8:
710         return VLC_FOURCC('G','R','E','Y');
711
712     case PIX_FMT_YUV410P:
713     case PIX_FMT_YUV411P:
714     case PIX_FMT_BGR24:
715     default:
716         return 0;
717     }
718 }
719
720 static int transcode_audio_ffmpeg_new( sout_stream_t *p_stream,
721                                        sout_stream_id_t *id )
722 {
723     int i_ff_codec;
724
725     if( id->f_src.i_codec == VLC_FOURCC('s','1','6','l') ||
726         id->f_src.i_codec == VLC_FOURCC('s','1','6','b') ||
727         id->f_src.i_codec == VLC_FOURCC('s','8',' ',' ') ||
728         id->f_src.i_codec == VLC_FOURCC('u','8',' ',' ') )
729     {
730         id->ff_dec = NULL;
731
732         id->ff_dec_c = avcodec_alloc_context();
733         id->ff_dec_c->sample_rate = id->f_src.audio.i_rate;
734         id->ff_dec_c->channels    = id->f_src.audio.i_channels;
735         id->ff_dec_c->block_align = id->f_src.audio.i_blockalign;
736         id->ff_dec_c->bit_rate    = id->f_src.i_bitrate;
737     }
738     else
739     {
740         /* find decoder */
741         i_ff_codec = get_ff_codec( id->f_src.i_codec );
742         if( i_ff_codec == 0 )
743         {
744             msg_Err( p_stream, "cannot find decoder id" );
745             return VLC_EGENERIC;
746         }
747
748         id->ff_dec = avcodec_find_decoder( i_ff_codec );
749         if( !id->ff_dec )
750         {
751             msg_Err( p_stream, "cannot find decoder (avcodec)" );
752             return VLC_EGENERIC;
753         }
754
755         id->ff_dec_c = avcodec_alloc_context();
756         id->ff_dec_c->sample_rate = id->f_src.audio.i_rate;
757         id->ff_dec_c->channels    = id->f_src.audio.i_channels;
758         id->ff_dec_c->block_align = id->f_src.audio.i_blockalign;
759         id->ff_dec_c->bit_rate    = id->f_src.i_bitrate;
760
761         id->ff_dec_c->extradata_size = id->f_src.i_extra;
762         id->ff_dec_c->extradata      = id->f_src.p_extra;
763         if( avcodec_open( id->ff_dec_c, id->ff_dec ) )
764         {
765             msg_Err( p_stream, "cannot open decoder" );
766             return VLC_EGENERIC;
767         }
768     }
769
770     id->i_buffer     = 2 * AVCODEC_MAX_AUDIO_FRAME_SIZE;
771     id->i_buffer_pos = 0;
772     id->p_buffer     = malloc( id->i_buffer );
773
774     /* Sanity check for audio channels */
775     id->f_dst.audio.i_channels = __MIN( id->f_dst.audio.i_channels, id->f_src.audio.i_channels );
776
777     /* find encoder */
778     id->p_encoder = vlc_object_create( p_stream, VLC_OBJECT_ENCODER );
779
780     /* Initialization of encoder format structures */
781     es_format_Init( &id->p_encoder->fmt_in, AUDIO_ES, AOUT_FMT_S16_NE );
782     id->p_encoder->fmt_in.audio.i_format = AOUT_FMT_S16_NE;
783     id->p_encoder->fmt_in.audio.i_rate = id->f_dst.audio.i_rate;
784     id->p_encoder->fmt_in.audio.i_physical_channels =
785         id->p_encoder->fmt_in.audio.i_original_channels =
786             pi_channels_maps[id->f_dst.audio.i_channels];
787     id->p_encoder->fmt_in.audio.i_channels = id->f_dst.audio.i_channels;
788
789     id->p_encoder->fmt_out = id->p_encoder->fmt_in;
790     id->p_encoder->fmt_out.i_codec = id->f_dst.i_codec;
791     id->p_encoder->fmt_out.i_bitrate = id->f_dst.i_bitrate;
792
793     id->p_encoder->p_module =
794         module_Need( id->p_encoder, "encoder", NULL, 0 );
795     if( !id->p_encoder->p_module )
796     {
797         vlc_object_destroy( id->p_encoder );
798         msg_Err( p_stream, "cannot open encoder" );
799         return VLC_EGENERIC;
800     }
801
802     id->b_enc_inited = VLC_FALSE;
803
804     id->f_dst.audio.i_channels = id->p_encoder->fmt_in.audio.i_channels;
805     id->f_dst.audio.i_rate     = id->p_encoder->fmt_in.audio.i_rate;
806     id->f_dst.i_extra = id->p_encoder->fmt_out.i_extra;
807     id->f_dst.p_extra = id->p_encoder->fmt_out.p_extra;
808
809     /* Hack for mp3 transcoding support */
810     if( id->f_dst.i_codec == VLC_FOURCC( 'm','p','3',' ' ) )
811     {
812         id->f_dst.i_codec = VLC_FOURCC( 'm','p','g','a' );
813     }
814
815     return VLC_SUCCESS;
816 }
817
818 static void transcode_audio_ffmpeg_close( sout_stream_t *p_stream,
819                                           sout_stream_id_t *id )
820 {
821     if( id->ff_dec )
822     {
823         avcodec_close( id->ff_dec_c );
824         free( id->ff_dec_c );
825     }
826
827     module_Unneed( id->p_encoder, id->p_encoder->p_module );
828     vlc_object_destroy( id->p_encoder );
829
830     free( id->p_buffer );
831 }
832
833 static int transcode_audio_ffmpeg_process( sout_stream_t *p_stream,
834                                            sout_stream_id_t *id,
835                                            sout_buffer_t *in,
836                                            sout_buffer_t **out )
837 {
838     aout_buffer_t aout_buf;
839     block_t *p_block;
840     int i_buffer = in->i_size;
841     char *p_buffer = in->p_buffer;
842     id->i_dts = in->i_dts;
843     *out = NULL;
844
845     while( i_buffer )
846     {
847         id->i_buffer_pos = 0;
848
849         /* decode as much data as possible */
850         if( id->ff_dec )
851         {
852             int i_used;
853
854             i_used = avcodec_decode_audio( id->ff_dec_c,
855                          (int16_t*)id->p_buffer, &id->i_buffer_pos,
856                          p_buffer, i_buffer );
857
858 #if 0
859             msg_Warn( p_stream, "avcodec_decode_audio: %d used on %d",
860                       i_used, i_buffer );
861 #endif
862             if( i_used < 0 )
863             {
864                 msg_Warn( p_stream, "error audio decoding");
865                 break;
866             }
867
868             i_buffer -= i_used;
869             p_buffer += i_used;
870
871             if ( id->i_buffer_pos < 0 )
872             {
873                 msg_Warn( p_stream, "weird error audio decoding");
874                 break;
875             }
876         }
877         else
878         {
879             int16_t *sout = (int16_t*)id->p_buffer;
880
881             if( id->f_src.i_codec == VLC_FOURCC( 's', '8', ' ', ' ' ) ||
882                 id->f_src.i_codec == VLC_FOURCC( 'u', '8', ' ', ' ' ) )
883             {
884                 int8_t *sin = (int8_t*)p_buffer;
885                 int i_used = __MIN( id->i_buffer/2, i_buffer );
886                 int i_samples = i_used;
887
888                 if( id->f_src.i_codec == VLC_FOURCC( 's', '8', ' ', ' ' ) )
889                     while( i_samples > 0 )
890                     {
891                         *sout++ = ( *sin++ ) << 8;
892                         i_samples--;
893                     }
894                 else
895                     while( i_samples > 0 )
896                     {
897                         *sout++ = ( *sin++ - 128 ) << 8;
898                         i_samples--;
899                     }
900
901                 i_buffer -= i_used;
902                 p_buffer += i_used;
903                 id->i_buffer_pos = i_used * 2;
904             }
905             else if( id->f_src.i_codec == VLC_FOURCC( 's', '1', '6', 'l' ) ||
906                      id->f_src.i_codec == VLC_FOURCC( 's', '1', '6', 'b' ) )
907             {
908                 int16_t *sin = (int16_t*)p_buffer;
909                 int i_used = __MIN( id->i_buffer, i_buffer );
910                 int i_samples = i_used / 2;
911
912                 /* first copy */
913                 memcpy( sout, sin, i_used );
914
915 #ifdef WORDS_BIGENDIAN
916                 if( id->f_src.i_codec == VLC_FOURCC( 's', '1', '6', 'l' ) )
917 #else
918                 if( id->f_src.i_codec == VLC_FOURCC( 's', '1', '6', 'b' ) )
919 #endif
920                 {
921                     uint8_t *dat = (uint8_t*)sout;
922
923                     while( i_samples > 0 )
924                     {
925                         uint8_t tmp;
926                         tmp    = dat[0];
927                         dat[0] = dat[1];
928                         dat[1] = tmp;
929
930                         dat += 2;
931
932                         i_samples--;
933                     }
934                 }
935
936                 i_buffer -= i_used;
937                 p_buffer += i_used;
938                 id->i_buffer_pos = i_used;
939             }
940         }
941
942         if( id->i_buffer_pos == 0 ) continue;
943
944         /* Encode as much data as possible */
945         if( !id->b_enc_inited && id->p_encoder->pf_header )
946         {
947             p_block = id->p_encoder->pf_header( id->p_encoder );
948             while( p_block )
949             {
950                 sout_buffer_t *p_out;
951                 block_t *p_prev_block = p_block;
952
953                 p_out = sout_BufferNew( p_stream->p_sout, p_block->i_buffer );
954                 memcpy( p_out->p_buffer, p_block->p_buffer, p_block->i_buffer);
955                 p_out->i_dts = p_out->i_pts = in->i_dts;
956                 p_out->i_length = 0;
957                 sout_BufferChain( out, p_out );
958
959                 p_block = p_block->p_next;
960                 block_Release( p_prev_block );
961             }
962
963             id->b_enc_inited = VLC_TRUE;
964         }
965
966         aout_buf.p_buffer = id->p_buffer;
967         aout_buf.i_nb_bytes = id->i_buffer_pos;
968         aout_buf.i_nb_samples = id->i_buffer_pos / 2 / id->f_src.audio.i_channels;
969         aout_buf.start_date = id->i_dts;
970         aout_buf.end_date = id->i_dts;
971
972         id->i_dts += ( I64C(1000000) * id->i_buffer_pos / 2 /
973             id->f_src.audio.i_channels / id->f_src.audio.i_rate );
974
975         if( id->p_encoder->fmt_in.audio.i_channels == 1 &&
976             id->f_src.audio.i_channels > 1 )
977         {
978             int16_t *p_sample = (int16_t *)aout_buf.p_buffer;
979             int i_src_c = id->f_src.audio.i_channels;
980             unsigned int i;
981
982             for( i = 0; i < aout_buf.i_nb_samples; i++ )
983             {
984                 int j, c = 0;
985
986                 for( j = 1; j < i_src_c; j++ )
987                 {
988                     c += p_sample[i_src_c * i + j];
989                 }
990                 p_sample[i] = c / (i_src_c-1);
991             }
992             aout_buf.i_nb_bytes = i * 2;
993         }
994         else if( id->p_encoder->fmt_in.audio.i_channels == 2 &&
995                  id->f_src.audio.i_channels > 2 )
996         {
997             int i_src_c = id->f_src.audio.i_channels;
998             unsigned int i;
999
1000             static const float mixf_l[4][6] = /* [i_src_c - 3][channel index] */
1001             {
1002                 { 0.00, 1.00, 0.00, 0.00, 0.00, 0.00 }, /* 3 channels */
1003                 { 0.00, 0.50, 0.50, 0.00, 0.00, 0.00 }, /* 4 channels */
1004                 { 0.00, 0.50, 0.00, 0.50, 0.00, 0.00 }, /* 5 channels */
1005                 { 0.00, 0.34, 0.33, 0.00, 0.33, 0.00 }, /* 6 channels */
1006             };
1007             static const float mixf_r[4][6] = /* [i_src_c - 3][channel index] */
1008             {
1009                 { 0.00, 1.00, 0.00, 0.00, 0.00, 0.00 }, /* 3 channels */
1010                 { 0.00, 0.00, 0.50, 0.50, 0.00, 0.00 }, /* 4 channels */
1011                 { 0.00, 0.00, 0.50, 0.00, 0.50, 0.00 }, /* 5 channels */
1012                 { 0.00, 0.00, 0.33, 0.34, 0.00, 0.33 }, /* 6 channels */
1013             };
1014
1015
1016             for( i = 0; i < aout_buf.i_nb_samples; i++ )
1017             {
1018                 int16_t *p_src = (int16_t *)aout_buf.p_buffer + i_src_c * i;
1019                 int16_t *p_dst = (int16_t *)aout_buf.p_buffer + 2 * i;
1020
1021                 int j;
1022                 float l = 0.0, r = 0.0;
1023                 for( j = 0; j < i_src_c; j++ )
1024                 {
1025                     l += mixf_l[i_src_c-3][j] * p_src[j];
1026                     r += mixf_r[i_src_c-3][j] * p_src[j];
1027                 }
1028
1029                 p_dst[0] = (int)( l + 0.5 );
1030                 p_dst[1] = (int)( r + 0.5 );
1031             }
1032             aout_buf.i_nb_bytes = i * 2 * 2;
1033         }
1034         else if( id->f_src.audio.i_channels !=
1035                  id->p_encoder->fmt_in.audio.i_channels )
1036         {
1037             unsigned int i;
1038             int j;
1039
1040             /* This is for liba52 which is what ffmpeg uses to decode ac3 */
1041             static const int translation[7][6] =
1042             {{ 0, 0, 0, 0, 0, 0 },      /* 0 channels (rarely used) */
1043              { 0, 0, 0, 0, 0, 0 },       /* 1 ch */
1044              { 0, 1, 0, 0, 0, 0 },       /* 2 */
1045              { 1, 2, 0, 0, 0, 0 },       /* 3 */
1046              { 1, 3, 2, 0, 0, 0 },       /* 4 */
1047              { 1, 3, 4, 2, 0, 0 },       /* 5 */
1048              { 1, 3, 4, 5, 2, 0 }};      /* 6 */
1049
1050             /* dumb downmixing */
1051             for( i = 0; i < aout_buf.i_nb_samples; i++ )
1052             {
1053                 uint16_t *p_buffer = (uint16_t *)aout_buf.p_buffer;
1054                 for( j = 0 ; j < id->p_encoder->fmt_in.audio.i_channels; j++ )
1055                 {
1056                     p_buffer[i*id->p_encoder->fmt_in.audio.i_channels+j] =
1057                         p_buffer[i*id->f_src.audio.i_channels+
1058                                  translation[id->f_src.audio.i_channels][j]];
1059                 }
1060             }
1061             aout_buf.i_nb_bytes = i*id->p_encoder->fmt_in.audio.i_channels * 2;
1062         }
1063
1064         p_block = id->p_encoder->pf_encode_audio( id->p_encoder, &aout_buf );
1065         while( p_block )
1066         {
1067             sout_buffer_t *p_out;
1068             block_t *p_prev_block = p_block;
1069
1070             p_out = sout_BufferNew( p_stream->p_sout, p_block->i_buffer );
1071             memcpy( p_out->p_buffer, p_block->p_buffer, p_block->i_buffer);
1072             p_out->i_dts = p_block->i_dts;
1073             p_out->i_pts = p_block->i_pts;
1074             p_out->i_length = p_block->i_length;
1075             sout_BufferChain( out, p_out );
1076
1077             p_block = p_block->p_next;
1078             block_Release( p_prev_block );
1079         }
1080     }
1081
1082     return VLC_SUCCESS;
1083 }
1084
1085
1086 /*
1087  * video
1088  */
1089 static int transcode_video_ffmpeg_new( sout_stream_t *p_stream,
1090                                        sout_stream_id_t *id )
1091 {
1092     sout_stream_sys_t   *p_sys = p_stream->p_sys;
1093
1094     int i_ff_codec;
1095
1096     /* Open decoder */
1097     if( id->f_src.i_codec == VLC_FOURCC( 'I', '4', '2', '0' ) ||
1098         id->f_src.i_codec == VLC_FOURCC( 'I', '4', '2', '2' ) ||
1099         id->f_src.i_codec == VLC_FOURCC( 'I', '4', '4', '4' ) ||
1100         id->f_src.i_codec == VLC_FOURCC( 'Y', 'V', '1', '2' ) ||
1101         id->f_src.i_codec == VLC_FOURCC( 'Y', 'U', 'Y', '2' ) ||
1102         id->f_src.i_codec == VLC_FOURCC( 'I', 'Y', 'U', 'V' ) ||
1103         id->f_src.i_codec == VLC_FOURCC( 'R', 'V', '1', '5' ) ||
1104         id->f_src.i_codec == VLC_FOURCC( 'R', 'V', '1', '6' ) ||
1105         id->f_src.i_codec == VLC_FOURCC( 'R', 'V', '2', '4' ) ||
1106         id->f_src.i_codec == VLC_FOURCC( 'R', 'V', '3', '2' ) ||
1107         id->f_src.i_codec == VLC_FOURCC( 'G', 'R', 'E', 'Y' ) )
1108     {
1109         id->ff_dec              = NULL;
1110         id->ff_dec_c            = avcodec_alloc_context();
1111         id->ff_dec_c->width     = id->f_src.video.i_width;
1112         id->ff_dec_c->height    = id->f_src.video.i_height;
1113         id->ff_dec_c->pix_fmt   = get_ff_chroma( id->f_src.i_codec );
1114
1115 #if LIBAVCODEC_BUILD >= 4687
1116         if( id->ff_dec_c->width )
1117         id->ff_dec_c->sample_aspect_ratio =
1118             av_d2q( id->f_src.video.i_aspect / (double)VOUT_ASPECT_FACTOR *
1119                     id->ff_dec_c->height / id->ff_dec_c->width, 255 );
1120 #else
1121         id->ff_dec_c->aspect_ratio =
1122             id->f_src.video.i_aspect / (float)VOUT_ASPECT_FACTOR;
1123 #endif
1124     }
1125     else
1126     {
1127         /* find decoder */
1128         i_ff_codec = get_ff_codec( id->f_src.i_codec );
1129         if( i_ff_codec == 0 )
1130         {
1131             msg_Err( p_stream, "cannot find decoder" );
1132             return VLC_EGENERIC;
1133         }
1134
1135         id->ff_dec = avcodec_find_decoder( i_ff_codec );
1136         if( !id->ff_dec )
1137         {
1138             msg_Err( p_stream, "cannot find decoder" );
1139             return VLC_EGENERIC;
1140         }
1141
1142         id->ff_dec_c = avcodec_alloc_context();
1143         id->ff_dec_c->width         = id->f_src.video.i_width;
1144         id->ff_dec_c->height        = id->f_src.video.i_height;
1145         id->ff_dec_c->bits_per_sample=id->f_src.video.i_bits_per_pixel;
1146         /* id->ff_dec_c->bit_rate      = id->f_src.i_bitrate; */
1147
1148         if( id->f_src.i_extra > 0 )
1149         {
1150             if( i_ff_codec == CODEC_ID_SVQ3 )
1151             {
1152                 int i_size = id->f_src.i_extra;
1153                 uint8_t *p;
1154
1155                 id->ff_dec_c->extradata_size = i_size + 12;
1156                 p = id->ff_dec_c->extradata  = malloc( i_size + 12 );
1157
1158                 memcpy( &p[0],  "SVQ3", 4 );
1159                 memset( &p[4], 0, 8 );
1160                 memcpy( &p[12], id->f_src.p_extra, i_size );
1161
1162                 /* Now remove all atoms before the SMI one */
1163                 if( id->ff_dec_c->extradata_size > 0x5a && strncmp( &p[0x56], "SMI ", 4 ) )
1164                 {
1165                     uint8_t *psz = &p[0x52];
1166
1167                     while( psz < &p[id->ff_dec_c->extradata_size - 8] )
1168                     {
1169                         int i_size = GetDWBE( psz );
1170                         if( i_size <= 1 )
1171                         {
1172                             /* FIXME handle 1 as long size */
1173                             break;
1174                         }
1175                         if( !strncmp( &psz[4], "SMI ", 4 ) )
1176                         {
1177                             memmove( &p[0x52], psz, &p[id->ff_dec_c->extradata_size] - psz );
1178                             break;
1179                         }
1180                         psz += i_size;
1181                     }
1182                 }
1183             }
1184             else
1185             {
1186                 id->ff_dec_c->extradata_size= id->f_src.i_extra;
1187                 id->ff_dec_c->extradata = malloc( id->f_src.i_extra + FF_INPUT_BUFFER_PADDING_SIZE );
1188
1189                 memcpy( id->ff_dec_c->extradata, id->f_src.p_extra, id->f_src.i_extra );
1190                 memset( (uint8_t*)id->ff_dec_c->extradata + id->f_src.i_extra, 0, FF_INPUT_BUFFER_PADDING_SIZE );
1191             }
1192         }
1193         id->ff_dec_c->workaround_bugs = FF_BUG_AUTODETECT;
1194         id->ff_dec_c->error_resilience= -1;
1195         id->ff_dec_c->get_buffer    = transcode_video_ffmpeg_getframebuf;
1196         id->ff_dec_c->opaque        = p_sys;
1197
1198         if( avcodec_open( id->ff_dec_c, id->ff_dec ) < 0 )
1199         {
1200             msg_Err( p_stream, "cannot open decoder" );
1201             return VLC_EGENERIC;
1202         }
1203 #if 0
1204         if( i_ff_codec == CODEC_ID_MPEG4 && id->ff_dec_c->extradata_size > 0 )
1205         {
1206             int b_gotpicture;
1207             AVFrame frame;
1208             uint8_t *p_vol = malloc( id->ff_dec_c->extradata_size +
1209                                      FF_INPUT_BUFFER_PADDING_SIZE );
1210
1211             memcpy( p_vol, id->ff_dec_c->extradata,
1212                     id->ff_dec_c->extradata_size );
1213             memset( p_vol + id->ff_dec_c->extradata_size, 0,
1214                     FF_INPUT_BUFFER_PADDING_SIZE );
1215
1216             avcodec_decode_video( id->ff_dec_c, &frame, &b_gotpicture,
1217                                   id->ff_dec_c->extradata,
1218                                   id->ff_dec_c->extradata_size );
1219             free( p_vol );
1220         }
1221 #endif
1222     }
1223
1224     /* Open encoder */
1225     id->p_encoder = vlc_object_create( p_stream, VLC_OBJECT_ENCODER );
1226
1227     /* Initialization of encoder format structures */
1228     es_format_Init( &id->p_encoder->fmt_in,
1229                     id->f_src.i_cat, get_vlc_chroma(id->ff_dec_c->pix_fmt) );
1230
1231     /* The dimensions will be set properly later on.
1232      * Just put sensible values so we can test if there is an encoder. */
1233     id->p_encoder->fmt_in.video.i_width = 16;
1234     id->p_encoder->fmt_in.video.i_height = 16;
1235
1236     id->p_encoder->fmt_in.video.i_frame_rate = 25; /* FIXME as it break mpeg */
1237     id->p_encoder->fmt_in.video.i_frame_rate_base= 1;
1238     if( id->ff_dec )
1239     {
1240         id->p_encoder->fmt_in.video.i_frame_rate = id->ff_dec_c->frame_rate;
1241 #if LIBAVCODEC_BUILD >= 4662
1242         id->p_encoder->fmt_in.video.i_frame_rate_base =
1243             id->ff_dec_c->frame_rate_base;
1244 #endif
1245
1246 #if LIBAVCODEC_BUILD >= 4687
1247         if( id->ff_dec_c->height )
1248         id->p_encoder->fmt_in.video.i_aspect = VOUT_ASPECT_FACTOR *
1249             ( av_q2d(id->ff_dec_c->sample_aspect_ratio) *
1250               id->ff_dec_c->width / id->ff_dec_c->height );
1251 #else
1252         id->p_encoder->fmt_in.video.i_aspect = VOUT_ASPECT_FACTOR *
1253             id->ff_dec_c->aspect_ratio;
1254 #endif
1255     }
1256
1257     /* Check whether a particular aspect ratio was requested */
1258     if( id->f_src.video.i_aspect )
1259     {
1260         id->p_encoder->fmt_in.video.i_aspect = id->f_src.video.i_aspect;
1261         id->f_dst.video.i_aspect = id->f_src.video.i_aspect;
1262     }
1263
1264     id->p_encoder->fmt_out = id->p_encoder->fmt_in;
1265     id->p_encoder->fmt_out.i_codec = id->f_dst.i_codec;
1266     id->p_encoder->fmt_out.i_bitrate = id->f_dst.i_bitrate;
1267
1268     id->p_encoder->i_vtolerance = p_sys->i_vtolerance;
1269     id->p_encoder->i_key_int = p_sys->i_key_int;
1270     id->p_encoder->i_b_frames = p_sys->i_b_frames;
1271     id->p_encoder->i_qmin = p_sys->i_qmin;
1272     id->p_encoder->i_qmax = p_sys->i_qmax;
1273     id->p_encoder->i_hq = p_sys->i_hq;
1274     id->p_encoder->b_strict_rc = p_sys->b_strict_rc;
1275     id->p_encoder->b_pre_me = p_sys->b_pre_me;
1276     id->p_encoder->b_hurry_up = p_sys->b_hurry_up;
1277     id->p_encoder->b_interlace = p_sys->b_interlace;
1278     id->p_encoder->i_rc_buffer_size = p_sys->i_rc_buffer_size;
1279     id->p_encoder->f_rc_buffer_aggressivity = p_sys->f_rc_buffer_aggressivity;
1280     id->p_encoder->f_i_quant_factor = p_sys->f_i_quant_factor;
1281     id->p_encoder->i_noise_reduction = p_sys->i_noise_reduction;
1282     id->p_encoder->b_mpeg4_matrix = p_sys->b_mpeg4_matrix;
1283     id->p_encoder->i_threads = p_sys->i_threads;
1284     id->p_encoder->b_trellis = p_sys->b_trellis;
1285
1286     id->p_ff_pic         = avcodec_alloc_frame();
1287     id->p_ff_pic_tmp0    = NULL;
1288     id->p_ff_pic_tmp1    = NULL;
1289     id->p_ff_pic_tmp2    = NULL;
1290     id->p_vresample      = NULL;
1291
1292     id->p_encoder->p_module =
1293         module_Need( id->p_encoder, "encoder", NULL, 0 );
1294
1295     if( !id->p_encoder->p_module )
1296     {
1297         vlc_object_destroy( id->p_encoder );
1298         msg_Err( p_stream, "cannot find encoder" );
1299         return VLC_EGENERIC;
1300     }
1301
1302     /* Close the encoder.
1303      * We'll open it only when we have the first frame */
1304     module_Unneed( id->p_encoder, id->p_encoder->p_module );
1305     id->p_encoder->p_module = NULL;
1306
1307     id->b_enc_inited = VLC_FALSE;
1308
1309     if ( p_sys->i_threads >= 1 )
1310     {
1311         p_sys->id_video = id;
1312         vlc_mutex_init( p_stream, &p_sys->lock_out );
1313         vlc_cond_init( p_stream, &p_sys->cond );
1314         memset( p_sys->pp_pics, 0, sizeof(p_sys->pp_pics) );
1315         p_sys->i_first_pic = 0;
1316         p_sys->i_last_pic = 0;
1317         p_sys->p_buffers = NULL;
1318         p_sys->b_die = p_sys->b_error = 0;
1319         if( vlc_thread_create( p_sys, "encoder", EncoderThread,
1320                                VLC_THREAD_PRIORITY_VIDEO, VLC_FALSE ) )
1321         {
1322             vlc_object_destroy( id->p_encoder );
1323             msg_Err( p_stream, "cannot spawn encoder thread" );
1324             return VLC_EGENERIC;
1325         }
1326     }
1327
1328     return VLC_SUCCESS;
1329 }
1330
1331 static void transcode_video_ffmpeg_close ( sout_stream_t *p_stream,
1332                                            sout_stream_id_t *id )
1333 {
1334     if ( p_stream->p_sys->i_threads >= 1 )
1335     {
1336        vlc_mutex_lock( &p_stream->p_sys->lock_out );
1337        p_stream->p_sys->b_die = 1;
1338        vlc_cond_signal( &p_stream->p_sys->cond );
1339        vlc_mutex_unlock( &p_stream->p_sys->lock_out );
1340        vlc_thread_join( p_stream->p_sys );
1341        vlc_mutex_destroy( &p_stream->p_sys->lock_out );
1342        vlc_cond_destroy( &p_stream->p_sys->cond );
1343     }
1344
1345     /* Close decoder */
1346     if( id->ff_dec )
1347     {
1348         avcodec_close( id->ff_dec_c );
1349         free( id->ff_dec_c );
1350     }
1351
1352     /* Close encoder */
1353     if( id->p_encoder->p_module )
1354         module_Unneed( id->p_encoder, id->p_encoder->p_module );
1355     vlc_object_destroy( id->p_encoder );
1356
1357     /* Misc cleanup */
1358     if( id->p_ff_pic)
1359     {
1360         free( id->p_ff_pic );
1361     }
1362
1363     if( id->p_ff_pic_tmp0 )
1364     {
1365         free( id->p_ff_pic_tmp0->data[0] );
1366         free( id->p_ff_pic_tmp0 );
1367     }
1368     if( id->p_ff_pic_tmp1)
1369     {
1370         free( id->p_ff_pic_tmp1->data[0] );
1371         free( id->p_ff_pic_tmp1 );
1372     }
1373     if( id->p_ff_pic_tmp2)
1374     {
1375         free( id->p_ff_pic_tmp2->data[0] );
1376         free( id->p_ff_pic_tmp2 );
1377     }
1378     if( id->p_vresample )
1379     {
1380         img_resample_close( id->p_vresample );
1381     }
1382 }
1383
1384 static int transcode_video_ffmpeg_process( sout_stream_t *p_stream,
1385                sout_stream_id_t *id, sout_buffer_t *in, sout_buffer_t **out )
1386 {
1387     sout_stream_sys_t   *p_sys = p_stream->p_sys;
1388     int     i_used;
1389     int     b_gotpicture;
1390     AVFrame *frame;
1391
1392     int     i_data;
1393     uint8_t *p_data;
1394
1395     *out = NULL;
1396
1397     i_data = in->i_size;
1398     p_data = in->p_buffer;
1399
1400     for( ;; )
1401     {
1402         block_t *p_block;
1403         picture_t * p_pic;
1404         int i_plane;
1405
1406         /* decode frame */
1407         frame = id->p_ff_pic;
1408         p_sys->i_input_pts = in->i_pts;
1409         p_sys->i_input_dts = in->i_dts;
1410         if( id->ff_dec )
1411         {
1412             i_used = avcodec_decode_video( id->ff_dec_c, frame,
1413                                            &b_gotpicture,
1414                                            p_data, i_data );
1415         }
1416         else
1417         {
1418             /* raw video */
1419             avpicture_fill( (AVPicture*)frame, p_data,
1420                             id->ff_dec_c->pix_fmt,
1421                             id->ff_dec_c->width, id->ff_dec_c->height );
1422             i_used = i_data;
1423             b_gotpicture = 1;
1424
1425             /* Set PTS */
1426             frame->pts = p_sys->i_input_pts ? p_sys->i_input_pts :
1427                          AV_NOPTS_VALUE;
1428
1429             frame->pict_type = FF_I_TYPE;
1430         }
1431
1432         if( i_used < 0 )
1433         {
1434             msg_Warn( p_stream, "error");
1435             return VLC_EGENERIC;
1436         }
1437         i_data -= i_used;
1438         p_data += i_used;
1439
1440         if( !b_gotpicture )
1441         {
1442             return VLC_SUCCESS;
1443         }
1444
1445         /* Get the pts of the decoded frame if any, otherwise keep the
1446          * interpolated one */
1447         if( frame->pts != AV_NOPTS_VALUE )
1448         {
1449             p_sys->i_output_pts = frame->pts;
1450         }
1451
1452         /* Sanity check (seems to be needed for some streams ) */
1453         if( frame->pict_type == FF_B_TYPE )
1454         {
1455             p_sys->b_input_has_b_frames = VLC_TRUE;
1456         }
1457
1458         if( !id->b_enc_inited )
1459         {
1460             /* Hack because of the copy packetizer which can fail to detect the
1461              * proper size (which forces us to wait until the 1st frame
1462              * is decoded) */
1463             int i_width = id->ff_dec_c->width - p_sys->i_crop_left -
1464                           p_sys->i_crop_right;
1465             int i_height = id->ff_dec_c->height - p_sys->i_crop_top -
1466                            p_sys->i_crop_bottom;
1467
1468             if( id->f_dst.video.i_width <= 0 && id->f_dst.video.i_height <= 0
1469                 && p_sys->f_scale )
1470             {
1471                 /* Apply the scaling */
1472                 id->f_dst.video.i_width = i_width * p_sys->f_scale;
1473                 id->f_dst.video.i_height = i_height * p_sys->f_scale;
1474             }
1475             else if( id->f_dst.video.i_width > 0 &&
1476                      id->f_dst.video.i_height <= 0 )
1477             {
1478                 id->f_dst.video.i_height =
1479                     id->f_dst.video.i_width / (double)i_width * i_height;
1480             }
1481             else if( id->f_dst.video.i_width <= 0 &&
1482                      id->f_dst.video.i_height > 0 )
1483             {
1484                 id->f_dst.video.i_width =
1485                     id->f_dst.video.i_height / (double)i_height * i_width;
1486             }
1487
1488             id->p_encoder->fmt_in.video.i_width =
1489               id->p_encoder->fmt_out.video.i_width =
1490                 id->f_dst.video.i_width;
1491             id->p_encoder->fmt_in.video.i_height =
1492               id->p_encoder->fmt_out.video.i_height =
1493                 id->f_dst.video.i_height;
1494
1495             id->p_encoder->fmt_out.i_extra = 0;
1496             id->p_encoder->fmt_out.p_extra = NULL;
1497
1498             id->p_encoder->p_module =
1499                 module_Need( id->p_encoder, "encoder", NULL, 0 );
1500             if( !id->p_encoder->p_module )
1501             {
1502                 vlc_object_destroy( id->p_encoder );
1503                 msg_Err( p_stream, "cannot find encoder" );
1504                 id->b_transcode = VLC_FALSE;
1505                 return VLC_EGENERIC;
1506             }
1507
1508             id->f_dst.i_extra = id->p_encoder->fmt_out.i_extra;
1509             id->f_dst.p_extra = id->p_encoder->fmt_out.p_extra;
1510
1511             /* Hack for mp2v/mp1v transcoding support */
1512             if( id->f_dst.i_codec == VLC_FOURCC( 'm','p','1','v' ) ||
1513                 id->f_dst.i_codec == VLC_FOURCC( 'm','p','2','v' ) )
1514             {
1515                 id->f_dst.i_codec = VLC_FOURCC( 'm','p','g','v' );
1516             }
1517
1518             if( !( id->id =
1519                      p_stream->p_sys->p_out->pf_add( p_stream->p_sys->p_out,
1520                                                      &id->f_dst ) ) )
1521             {
1522                 msg_Err( p_stream, "cannot add this stream" );
1523                 transcode_video_ffmpeg_close( p_stream, id );
1524                 id->b_transcode = VLC_FALSE;
1525                 return VLC_EGENERIC;
1526             }
1527
1528             if( id->p_encoder->pf_header )
1529             {
1530                 p_block = id->p_encoder->pf_header( id->p_encoder );
1531                 while( p_block )
1532                 {
1533                     sout_buffer_t *p_out;
1534                     block_t *p_prev_block = p_block;
1535
1536                     p_out = sout_BufferNew( p_stream->p_sout,
1537                                             p_block->i_buffer );
1538                     memcpy( p_out->p_buffer, p_block->p_buffer,
1539                             p_block->i_buffer);
1540                     p_out->i_dts = p_out->i_pts = in->i_dts;
1541                     p_out->i_length = 0;
1542                     sout_BufferChain( out, p_out );
1543
1544                     p_block = p_block->p_next;
1545                     block_Release( p_prev_block );
1546                 }
1547             }
1548
1549             id->i_inter_pixfmt =
1550                 get_ff_chroma( id->p_encoder->fmt_in.i_codec );
1551
1552             id->b_enc_inited = VLC_TRUE;
1553         }
1554
1555         /* deinterlace */
1556         if( p_stream->p_sys->b_deinterlace )
1557         {
1558             if( id->p_ff_pic_tmp0 == NULL )
1559             {
1560                 int     i_size;
1561                 uint8_t *buf;
1562                 id->p_ff_pic_tmp0 = avcodec_alloc_frame();
1563                 i_size = avpicture_get_size( id->ff_dec_c->pix_fmt,
1564                                              id->ff_dec_c->width, id->ff_dec_c->height );
1565
1566                 buf = malloc( i_size );
1567
1568                 avpicture_fill( (AVPicture*)id->p_ff_pic_tmp0, buf,
1569                                 id->i_inter_pixfmt,
1570                                 id->ff_dec_c->width, id->ff_dec_c->height );
1571             }
1572
1573             avpicture_deinterlace( (AVPicture*)id->p_ff_pic_tmp0, (AVPicture*)frame,
1574                                    id->ff_dec_c->pix_fmt,
1575                                    id->ff_dec_c->width, id->ff_dec_c->height );
1576
1577 #if LIBAVCODEC_BUILD >= 4685
1578             id->p_ff_pic_tmp0->interlaced_frame = 0;
1579 #endif
1580             id->p_ff_pic_tmp0->repeat_pict = frame->repeat_pict;
1581             frame = id->p_ff_pic_tmp0;
1582         }
1583
1584         /* convert pix format */
1585         if( id->ff_dec_c->pix_fmt != id->i_inter_pixfmt )
1586         {
1587             if( id->p_ff_pic_tmp1 == NULL )
1588             {
1589                 int     i_size;
1590                 uint8_t *buf;
1591                 id->p_ff_pic_tmp1 = avcodec_alloc_frame();
1592                 i_size = avpicture_get_size( id->i_inter_pixfmt,
1593                                              id->ff_dec_c->width,
1594                                              id->ff_dec_c->height );
1595
1596                 buf = malloc( i_size );
1597
1598                 avpicture_fill( (AVPicture*)id->p_ff_pic_tmp1, buf,
1599                                 id->i_inter_pixfmt,
1600                                 id->ff_dec_c->width, id->ff_dec_c->height );
1601             }
1602
1603             img_convert( (AVPicture*)id->p_ff_pic_tmp1, id->i_inter_pixfmt,
1604                          (AVPicture*)frame, id->ff_dec_c->pix_fmt,
1605                          id->ff_dec_c->width, id->ff_dec_c->height );
1606
1607             id->p_ff_pic_tmp1->repeat_pict = frame->repeat_pict;
1608 #if LIBAVCODEC_BUILD >= 4685
1609             id->p_ff_pic_tmp1->interlaced_frame = frame->interlaced_frame;
1610             id->p_ff_pic_tmp1->top_field_first = frame->top_field_first;
1611 #endif
1612             frame = id->p_ff_pic_tmp1;
1613         }
1614
1615         /* convert size and crop */
1616         if( id->ff_dec_c->width  != id->f_dst.video.i_width ||
1617             id->ff_dec_c->height != id->f_dst.video.i_height ||
1618             p_sys->i_crop_top > 0 || p_sys->i_crop_bottom > 0 ||
1619             p_sys->i_crop_left > 0 || p_sys->i_crop_right > 0 )
1620         {
1621             if( id->p_ff_pic_tmp2 == NULL )
1622             {
1623                 int     i_size;
1624                 uint8_t *buf;
1625                 id->p_ff_pic_tmp2 = avcodec_alloc_frame();
1626                 i_size = avpicture_get_size( id->i_inter_pixfmt,
1627                                              id->f_dst.video.i_width,
1628                                              id->f_dst.video.i_height );
1629
1630                 buf = malloc( i_size );
1631
1632                 avpicture_fill( (AVPicture*)id->p_ff_pic_tmp2, buf,
1633                                 id->i_inter_pixfmt,
1634                                 id->f_dst.video.i_width, id->f_dst.video.i_height );
1635
1636                 id->p_vresample =
1637                     img_resample_full_init( id->f_dst.video.i_width,
1638                                             id->f_dst.video.i_height,
1639                                             id->ff_dec_c->width, id->ff_dec_c->height,
1640                                             p_stream->p_sys->i_crop_top,
1641                                             p_stream->p_sys->i_crop_bottom,
1642                                             p_stream->p_sys->i_crop_left,
1643                                             p_stream->p_sys->i_crop_right );
1644             }
1645
1646             img_resample( id->p_vresample, (AVPicture*)id->p_ff_pic_tmp2,
1647                           (AVPicture*)frame );
1648
1649             id->p_ff_pic_tmp2->repeat_pict = frame->repeat_pict;
1650 #if LIBAVCODEC_BUILD >= 4685
1651             id->p_ff_pic_tmp2->interlaced_frame = frame->interlaced_frame;
1652             id->p_ff_pic_tmp2->top_field_first = frame->top_field_first;
1653 #endif
1654             frame = id->p_ff_pic_tmp2;
1655         }
1656
1657         /* Encoding */
1658         p_pic = malloc(sizeof(picture_t));
1659         vout_InitPicture( VLC_OBJECT(p_stream), p_pic,
1660                           id->p_encoder->fmt_in.i_codec,
1661                           id->f_dst.video.i_width, id->f_dst.video.i_height,
1662                           id->f_dst.video.i_width * VOUT_ASPECT_FACTOR /
1663                           id->f_dst.video.i_height );
1664
1665         for( i_plane = 0; i_plane < p_pic->i_planes; i_plane++ )
1666         {
1667             p_pic->p[i_plane].i_pitch = frame->linesize[i_plane];
1668             if ( p_sys->i_threads >= 1 )
1669             {
1670                 p_pic->p[i_plane].p_pixels = malloc(p_pic->p[i_plane].i_lines *
1671                                                     p_pic->p[i_plane].i_pitch);
1672                 p_stream->p_vlc->pf_memcpy( p_pic->p[i_plane].p_pixels,
1673                     frame->data[i_plane], p_pic->p[i_plane].i_lines *
1674                      p_pic->p[i_plane].i_pitch );
1675             }
1676             else
1677             {
1678                 p_pic->p[i_plane].p_pixels = frame->data[i_plane];
1679             }
1680         }
1681
1682         /* Set the pts of the frame being encoded */
1683         p_pic->date = p_sys->i_output_pts;
1684
1685         p_pic->i_nb_fields = frame->repeat_pict;
1686 #if LIBAVCODEC_BUILD >= 4685
1687         p_pic->b_progressive = !frame->interlaced_frame;
1688         p_pic->b_top_field_first = frame->top_field_first;
1689 #endif
1690
1691         /* Interpolate the next PTS
1692          * (needed by the mpeg video packetizer which can send pts <= 0 ) */
1693         if( id->ff_dec_c && id->ff_dec_c->frame_rate > 0 )
1694         {
1695             p_sys->i_output_pts += I64C(1000000) * (2 + frame->repeat_pict) *
1696               id->ff_dec_c->frame_rate_base / (2 * id->ff_dec_c->frame_rate);
1697         }
1698
1699         if ( p_sys->i_threads >= 1 )
1700         {
1701             vlc_mutex_lock( &p_sys->lock_out );
1702             p_sys->pp_pics[p_sys->i_last_pic++] = p_pic;
1703             p_sys->i_last_pic %= PICTURE_RING_SIZE;
1704             *out = p_sys->p_buffers;
1705             p_sys->p_buffers = NULL;
1706             vlc_cond_signal( &p_sys->cond );
1707             vlc_mutex_unlock( &p_sys->lock_out );
1708         }
1709         else
1710         {
1711             block_t *p_block;
1712             p_block = id->p_encoder->pf_encode_video( id->p_encoder, p_pic );
1713             while( p_block )
1714             {
1715                 sout_buffer_t *p_out;
1716                 block_t *p_prev_block = p_block;
1717
1718                 p_out = sout_BufferNew( p_stream->p_sout, p_block->i_buffer );
1719                 memcpy( p_out->p_buffer, p_block->p_buffer, p_block->i_buffer);
1720                 p_out->i_dts = p_block->i_dts;
1721                 p_out->i_pts = p_block->i_pts;
1722                 p_out->i_length = p_block->i_length;
1723                 p_out->i_flags =
1724                         (p_block->i_flags << SOUT_BUFFER_FLAGS_BLOCK_SHIFT)
1725                           & SOUT_BUFFER_FLAGS_BLOCK_MASK;
1726                 sout_BufferChain( out, p_out );
1727
1728                 p_block = p_block->p_next;
1729                 block_Release( p_prev_block );
1730             }
1731             free( p_pic );
1732         }
1733
1734         if( i_data <= 0 )
1735         {
1736             return VLC_SUCCESS;
1737         }
1738     }
1739
1740     return VLC_SUCCESS;
1741 }
1742
1743 static int EncoderThread( sout_stream_sys_t * p_sys )
1744 {
1745     sout_stream_t * p_stream = p_sys->p_out;
1746     sout_stream_id_t * id = p_sys->id_video;
1747     picture_t * p_pic;
1748     int i_plane;
1749     sout_buffer_t * p_buffer;
1750
1751     while ( !p_sys->b_die && !p_sys->b_error )
1752     {
1753         block_t *p_block;
1754
1755         vlc_mutex_lock( &p_sys->lock_out );
1756         while ( p_sys->i_last_pic == p_sys->i_first_pic )
1757         {
1758             vlc_cond_wait( &p_sys->cond, &p_sys->lock_out );
1759             if ( p_sys->b_die || p_sys->b_error )
1760                 break;
1761         }
1762         if ( p_sys->b_die || p_sys->b_error )
1763         {
1764             vlc_mutex_unlock( &p_sys->lock_out );
1765             break;
1766         }
1767
1768         p_pic = p_sys->pp_pics[p_sys->i_first_pic++];
1769         p_sys->i_first_pic %= PICTURE_RING_SIZE;
1770         vlc_mutex_unlock( &p_sys->lock_out );
1771
1772         p_block = id->p_encoder->pf_encode_video( id->p_encoder, p_pic );
1773         vlc_mutex_lock( &p_sys->lock_out );
1774         while( p_block )
1775         {
1776             sout_buffer_t *p_out;
1777             block_t *p_prev_block = p_block;
1778
1779             p_out = sout_BufferNew( p_stream->p_sout, p_block->i_buffer );
1780             memcpy( p_out->p_buffer, p_block->p_buffer, p_block->i_buffer);
1781             p_out->i_dts = p_block->i_dts;
1782             p_out->i_pts = p_block->i_pts;
1783             p_out->i_length = p_block->i_length;
1784             p_out->i_flags =
1785                 (p_block->i_flags << SOUT_BUFFER_FLAGS_BLOCK_SHIFT)
1786                   & SOUT_BUFFER_FLAGS_BLOCK_MASK;
1787             sout_BufferChain( &p_sys->p_buffers, p_out );
1788
1789             p_block = p_block->p_next;
1790             block_Release( p_prev_block );
1791         }
1792         vlc_mutex_unlock( &p_sys->lock_out );
1793
1794         for( i_plane = 0; i_plane < p_pic->i_planes; i_plane++ )
1795         {
1796             free( p_pic->p[i_plane].p_pixels );
1797         }
1798         free( p_pic );
1799     }
1800
1801     while ( p_sys->i_last_pic != p_sys->i_first_pic )
1802     {
1803         p_pic = p_sys->pp_pics[p_sys->i_first_pic++];
1804         p_sys->i_first_pic %= PICTURE_RING_SIZE;
1805
1806         for( i_plane = 0; i_plane < p_pic->i_planes; i_plane++ )
1807         {
1808             free( p_pic->p[i_plane].p_pixels );
1809         }
1810         free( p_pic );
1811     }
1812
1813     p_buffer = p_sys->p_buffers;
1814     while ( p_buffer != NULL )
1815     {
1816         sout_buffer_t * p_next = p_buffer->p_next;
1817         sout_BufferDelete( p_stream->p_sout, p_buffer );
1818         p_buffer = p_next;
1819     }
1820
1821     return 0;
1822 }
1823
1824 /*****************************************************************************
1825  * transcode_video_ffmpeg_getframebuf:
1826  *
1827  * Callback used by ffmpeg to get a frame buffer.
1828  * We use it to get the right PTS for each decoded picture.
1829  *****************************************************************************/
1830 static int transcode_video_ffmpeg_getframebuf(struct AVCodecContext *p_context,
1831                                               AVFrame *p_frame)
1832 {
1833     sout_stream_sys_t *p_sys = (sout_stream_sys_t *)p_context->opaque;
1834
1835     /* Set PTS */
1836     if( p_sys->i_input_pts )
1837     {
1838         p_frame->pts = p_sys->i_input_pts;
1839     }
1840     else if( p_sys->i_input_dts )
1841     {
1842         /* Some demuxers/packetizers only set the dts so let's try to find a
1843          * useful timestamp from this */
1844         if( !p_context->has_b_frames || !p_sys->b_input_has_b_frames ||
1845             !p_frame->reference || !p_sys->i_output_pts )
1846         {
1847             p_frame->pts = p_sys->i_input_dts;
1848         }
1849         else p_frame->pts = AV_NOPTS_VALUE;
1850     }
1851     else p_frame->pts = AV_NOPTS_VALUE;
1852
1853     if( p_sys->i_output_pts ) /* make sure 1st frame has a pts > 0 */
1854     {
1855         p_sys->i_input_pts = 0;
1856         p_sys->i_input_dts = 0;
1857     }
1858
1859     return avcodec_default_get_buffer( p_context, p_frame );
1860 }