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