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