]> git.sesse.net Git - vlc/blob - modules/stream_out/transcode.c
* modules/stream_out/transcode.c: small cleanup + added an fps (to specify the output...
[vlc] / 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@videolan.org>
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 #include "vlc_filter.h"
37 #include "osd.h"
38
39 /* ffmpeg header */
40 #ifdef HAVE_FFMPEG_AVCODEC_H
41 #   include <ffmpeg/avcodec.h>
42 #else
43 #   include <avcodec.h>
44 #endif
45
46 #if LIBAVCODEC_BUILD < 4704
47 #   define AV_NOPTS_VALUE 0
48 #endif
49
50 /*****************************************************************************
51  * Module descriptor
52  *****************************************************************************/
53 #define VENC_TEXT N_("Video encoder")
54 #define VENC_LONGTEXT N_( \
55     "Allows you to specify the video encoder to use and its associated " \
56     "options." )
57 #define VCODEC_TEXT N_("Destination video codec")
58 #define VCODEC_LONGTEXT N_( \
59     "Allows you to specify the destination video codec used for the " \
60     "streaming output." )
61 #define VB_TEXT N_("Video bitrate")
62 #define VB_LONGTEXT N_( \
63     "Allows you to specify the video bitrate used for the streaming " \
64     "output." )
65 #define SCALE_TEXT N_("Video scaling")
66 #define SCALE_LONGTEXT N_( \
67     "Allows you to scale the video before encoding." )
68 #define FPS_TEXT N_("Video frame-rate")
69 #define FPS_LONGTEXT N_( \
70     "Allows you to specify an output frame rate for the video." )
71 #define DEINTERLACE_TEXT N_("Deinterlace video")
72 #define DEINTERLACE_LONGTEXT N_( \
73     "Allows you to deinterlace the video before encoding." )
74 #define WIDTH_TEXT N_("Video width")
75 #define WIDTH_LONGTEXT N_( \
76     "Allows you to specify the output video width." )
77 #define HEIGHT_TEXT N_("Video height")
78 #define HEIGHT_LONGTEXT N_( \
79     "Allows you to specify the output video height." )
80
81 #define CROPTOP_TEXT N_("Video crop top")
82 #define CROPTOP_LONGTEXT N_( \
83     "Allows you to specify the top coordinate for the video cropping." )
84 #define CROPLEFT_TEXT N_("Video crop left")
85 #define CROPLEFT_LONGTEXT N_( \
86     "Allows you to specify the left coordinate for the video cropping." )
87 #define CROPBOTTOM_TEXT N_("Video crop bottom")
88 #define CROPBOTTOM_LONGTEXT N_( \
89     "Allows you to specify the bottom coordinate for the video cropping." )
90 #define CROPRIGHT_TEXT N_("Video crop right")
91 #define CROPRIGHT_LONGTEXT N_( \
92     "Allows you to specify the right coordinate for the video cropping." )
93
94 #define AENC_TEXT N_("Audio encoder")
95 #define AENC_LONGTEXT N_( \
96     "Allows you to specify the audio encoder to use and its associated " \
97     "options." )
98 #define ACODEC_TEXT N_("Destination audio codec")
99 #define ACODEC_LONGTEXT N_( \
100     "Allows you to specify the destination audio codec used for the " \
101     "streaming output." )
102 #define AB_TEXT N_("Audio bitrate")
103 #define AB_LONGTEXT N_( \
104     "Allows you to specify the audio bitrate used for the streaming " \
105     "output." )
106 #define ARATE_TEXT N_("Audio sample rate")
107 #define ARATE_LONGTEXT N_( \
108     "Allows you to specify the audio sample rate used for the streaming " \
109     "output." )
110 #define ACHANS_TEXT N_("Audio channels")
111 #define ACHANS_LONGTEXT N_( \
112     "Allows you to specify the number of audio channels used for the " \
113     "streaming output." )
114
115 #define SENC_TEXT N_("Subtitles encoder")
116 #define SENC_LONGTEXT N_( \
117     "Allows you to specify the subtitles encoder to use and its associated " \
118     "options." )
119 #define SCODEC_TEXT N_("Destination subtitles codec")
120 #define SCODEC_LONGTEXT N_( \
121     "Allows you to specify the destination subtitles codec used for the " \
122     "streaming output." )
123
124 #define THREADS_TEXT N_("Number of threads")
125 #define THREADS_LONGTEXT N_( \
126     "Allows you to specify the number of threads used for the transcoding." )
127
128 #define ASYNC_TEXT N_("Synchronise on audio track")
129 #define ASYNC_LONGTEXT N_( \
130     "This option will drop/duplicate video frames to synchronise the video " \
131     "track on the audio track." )
132
133 static int  Open ( vlc_object_t * );
134 static void Close( vlc_object_t * );
135
136 #define SOUT_CFG_PREFIX "sout-transcode-"
137
138 vlc_module_begin();
139     set_description( _("Transcode stream output") );
140     set_capability( "sout stream", 50 );
141     add_shortcut( "transcode" );
142     set_callbacks( Open, Close );
143
144     add_string( SOUT_CFG_PREFIX "venc", NULL, NULL, VENC_TEXT,
145                 VENC_LONGTEXT, VLC_FALSE );
146     add_string( SOUT_CFG_PREFIX "vcodec", NULL, NULL, VCODEC_TEXT,
147                 VCODEC_LONGTEXT, VLC_FALSE );
148     add_integer( SOUT_CFG_PREFIX "vb", 800 * 1000, NULL, VB_TEXT,
149                  VB_LONGTEXT, VLC_FALSE );
150     add_float( SOUT_CFG_PREFIX "scale", 1, NULL, SCALE_TEXT,
151                SCALE_LONGTEXT, VLC_FALSE );
152     add_float( SOUT_CFG_PREFIX "fps", 0, NULL, FPS_TEXT,
153                FPS_LONGTEXT, VLC_FALSE );
154     add_bool( SOUT_CFG_PREFIX "deinterlace", 0, NULL, DEINTERLACE_TEXT,
155               DEINTERLACE_LONGTEXT, VLC_FALSE );
156     add_integer( SOUT_CFG_PREFIX "width", 0, NULL, WIDTH_TEXT,
157                  WIDTH_LONGTEXT, VLC_TRUE );
158     add_integer( SOUT_CFG_PREFIX "height", 0, NULL, HEIGHT_TEXT,
159                  HEIGHT_LONGTEXT, VLC_TRUE );
160
161     add_integer( SOUT_CFG_PREFIX "croptop", 0, NULL, CROPTOP_TEXT,
162                  CROPTOP_LONGTEXT, VLC_TRUE );
163     add_integer( SOUT_CFG_PREFIX "cropleft", 0, NULL, CROPLEFT_TEXT,
164                  CROPLEFT_LONGTEXT, VLC_TRUE );
165     add_integer( SOUT_CFG_PREFIX "cropbottom", 0, NULL, CROPBOTTOM_TEXT,
166                  CROPBOTTOM_LONGTEXT, VLC_TRUE );
167     add_integer( SOUT_CFG_PREFIX "cropright", 0, NULL, CROPRIGHT_TEXT,
168                  CROPRIGHT_LONGTEXT, VLC_TRUE );
169
170     add_string( SOUT_CFG_PREFIX "aenc", NULL, NULL, AENC_TEXT,
171                 AENC_LONGTEXT, VLC_FALSE );
172     add_string( SOUT_CFG_PREFIX "acodec", NULL, NULL, ACODEC_TEXT,
173                 ACODEC_LONGTEXT, VLC_FALSE );
174     add_integer( SOUT_CFG_PREFIX "ab", 64000, NULL, AB_TEXT,
175                  AB_LONGTEXT, VLC_FALSE );
176     add_integer( SOUT_CFG_PREFIX "channels", 0, NULL, ACHANS_TEXT,
177                  ACHANS_LONGTEXT, VLC_FALSE );
178     add_integer( SOUT_CFG_PREFIX "samplerate", 0, NULL, ARATE_TEXT,
179                  ARATE_LONGTEXT, VLC_TRUE );
180
181     add_string( SOUT_CFG_PREFIX "senc", NULL, NULL, SENC_TEXT,
182                 SENC_LONGTEXT, VLC_FALSE );
183     add_string( SOUT_CFG_PREFIX "scodec", NULL, NULL, SCODEC_TEXT,
184                 SCODEC_LONGTEXT, VLC_FALSE );
185     add_bool( SOUT_CFG_PREFIX "soverlay", 0, NULL, SCODEC_TEXT,
186                SCODEC_LONGTEXT, VLC_FALSE );
187
188     add_integer( SOUT_CFG_PREFIX "threads", 0, NULL, THREADS_TEXT,
189                  THREADS_LONGTEXT, VLC_TRUE );
190
191     add_bool( SOUT_CFG_PREFIX "audio-sync", 0, NULL, ASYNC_TEXT,
192               ASYNC_LONGTEXT, VLC_FALSE );
193 vlc_module_end();
194
195 static const char *ppsz_sout_options[] = {
196     "venc", "vcodec", "vb", "croptop", "cropbottom", "cropleft", "cropright",
197     "scale", "fps", "width", "height", "deinterlace", "threads",
198     "aenc", "acodec", "ab", "samplerate", "channels",
199     "senc", "scodec", "soverlay",
200     "audio-sync", NULL
201 };
202
203 /*****************************************************************************
204  * Exported prototypes
205  *****************************************************************************/
206 static sout_stream_id_t *Add ( sout_stream_t *, es_format_t * );
207 static int               Del ( sout_stream_t *, sout_stream_id_t * );
208 static int               Send( sout_stream_t *, sout_stream_id_t *, block_t* );
209
210 static int  transcode_audio_ffmpeg_new    ( sout_stream_t *, sout_stream_id_t * );
211 static void transcode_audio_ffmpeg_close  ( sout_stream_t *, sout_stream_id_t * );
212 static int  transcode_audio_ffmpeg_process( sout_stream_t *, sout_stream_id_t *, block_t *, block_t ** );
213
214 static int  transcode_video_ffmpeg_new    ( sout_stream_t *, sout_stream_id_t * );
215 static void transcode_video_ffmpeg_close  ( sout_stream_t *, sout_stream_id_t * );
216 static int  transcode_video_ffmpeg_process( sout_stream_t *, sout_stream_id_t *, block_t *, block_t ** );
217
218 static int  transcode_video_ffmpeg_getframebuf( struct AVCodecContext *, AVFrame *);
219
220 static int  transcode_spu_new    ( sout_stream_t *, sout_stream_id_t * );
221 static void transcode_spu_close  ( sout_stream_t *, sout_stream_id_t * );
222 static int  transcode_spu_process( sout_stream_t *, sout_stream_id_t *,
223                                    block_t *, block_t ** );
224 static subpicture_t *transcode_spu_get( sout_stream_t *, sout_stream_id_t *,
225                                         mtime_t );
226
227 static int  EncoderThread( struct sout_stream_sys_t * p_sys );
228
229 static int pi_channels_maps[6] =
230 {
231     0,
232     AOUT_CHAN_CENTER,   AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
233     AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
234     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
235      | AOUT_CHAN_REARRIGHT,
236     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
237      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
238 };
239
240 #define PICTURE_RING_SIZE 64
241 #define SUBPICTURE_RING_SIZE 20
242
243 struct sout_stream_sys_t
244 {
245     VLC_COMMON_MEMBERS
246
247     sout_stream_t * p_out;
248     sout_stream_id_t * id_video;
249     block_t * p_buffers;
250     vlc_mutex_t     lock_out;
251     vlc_cond_t      cond;
252     picture_t *     pp_pics[PICTURE_RING_SIZE];
253     int             i_first_pic, i_last_pic;
254
255     /* Audio */
256     vlc_fourcc_t    i_acodec;   /* codec audio (0 if not transcode) */
257     char            *psz_aenc;
258     sout_cfg_t      *p_audio_cfg;
259     int             i_sample_rate;
260     int             i_channels;
261     int             i_abitrate;
262
263     /* Video */
264     vlc_fourcc_t    i_vcodec;   /* codec video (0 if not transcode) */
265     char            *psz_venc;
266     sout_cfg_t      *p_video_cfg;
267     int             i_vbitrate;
268     double          f_scale;
269     double          f_fps;
270     int             i_width;
271     int             i_height;
272     vlc_bool_t      b_deinterlace;
273     int             i_threads;
274
275     int             i_crop_top;
276     int             i_crop_bottom;
277     int             i_crop_right;
278     int             i_crop_left;
279
280     mtime_t         i_input_dts;
281     mtime_t         i_input_pts;
282     vlc_bool_t      b_input_has_b_frames;
283
284     mtime_t         i_output_pts;
285
286     /* SPU */
287     vlc_fourcc_t    i_scodec;   /* codec spu (0 if not transcode) */
288     char            *psz_senc;
289     vlc_bool_t      b_soverlay;
290     sout_cfg_t      *p_spu_cfg;
291     subpicture_t    *pp_subpics[SUBPICTURE_RING_SIZE];
292
293     /* Filters */
294     filter_t        *p_filter_blend;
295
296     /* Sync */
297     vlc_bool_t      b_audio_sync;
298     mtime_t         i_master_drift;
299 };
300
301 /*****************************************************************************
302  * Open:
303  *****************************************************************************/
304 static int Open( vlc_object_t *p_this )
305 {
306     sout_stream_t     *p_stream = (sout_stream_t*)p_this;
307     sout_stream_sys_t *p_sys;
308     vlc_value_t       val;
309     int               i;
310
311     p_sys = vlc_object_create( p_this, sizeof( sout_stream_sys_t ) );
312
313     p_sys->p_out = sout_StreamNew( p_stream->p_sout, p_stream->psz_next );
314     if( !p_sys->p_out )
315     {
316         msg_Err( p_stream, "cannot create chain" );
317         free( p_sys );
318         return VLC_EGENERIC;
319     }
320
321     p_sys->b_input_has_b_frames = VLC_FALSE;
322     p_sys->i_output_pts = 0;
323     p_sys->i_master_drift = 0;
324
325     sout_CfgParse( p_stream, SOUT_CFG_PREFIX, ppsz_sout_options,
326                    p_stream->p_cfg );
327
328     /* Audio transcoding parameters */
329     var_Get( p_stream, SOUT_CFG_PREFIX "aenc", &val );
330     p_sys->psz_aenc = NULL;
331     p_sys->p_audio_cfg = NULL;
332     if( val.psz_string && *val.psz_string )
333     {
334         char *psz_next;
335         psz_next = sout_CfgCreate( &p_sys->psz_aenc, &p_sys->p_audio_cfg,
336                                    val.psz_string );
337         if( psz_next ) free( psz_next );
338     }
339     if( val.psz_string ) free( val.psz_string );
340
341     var_Get( p_stream, SOUT_CFG_PREFIX "acodec", &val );
342     p_sys->i_acodec = 0;
343     if( val.psz_string && *val.psz_string )
344     {
345         char fcc[4] = "    ";
346         memcpy( fcc, val.psz_string, __MIN( strlen( val.psz_string ), 4 ) );
347         p_sys->i_acodec = VLC_FOURCC( fcc[0], fcc[1], fcc[2], fcc[3] );
348     }
349     if( val.psz_string ) free( val.psz_string );
350
351     var_Get( p_stream, SOUT_CFG_PREFIX "ab", &val );
352     p_sys->i_abitrate = val.i_int;
353     if( p_sys->i_abitrate < 4000 ) p_sys->i_abitrate *= 1000;
354
355     var_Get( p_stream, SOUT_CFG_PREFIX "samplerate", &val );
356     p_sys->i_sample_rate = val.i_int;
357
358     var_Get( p_stream, SOUT_CFG_PREFIX "channels", &val );
359     p_sys->i_channels = val.i_int;
360
361     if( p_sys->i_acodec )
362     {
363         msg_Dbg( p_stream, "codec audio=%4.4s %dHz %d channels %dKb/s",
364                  (char *)&p_sys->i_acodec, p_sys->i_sample_rate,
365                  p_sys->i_channels, p_sys->i_abitrate / 1000 );
366     }
367
368     /* Video transcoding parameters */
369     var_Get( p_stream, SOUT_CFG_PREFIX "venc", &val );
370     p_sys->psz_venc = NULL;
371     p_sys->p_video_cfg = NULL;
372     if( val.psz_string && *val.psz_string )
373     {
374         char *psz_next;
375         psz_next = sout_CfgCreate( &p_sys->psz_venc, &p_sys->p_video_cfg,
376                                    val.psz_string );
377         if( psz_next ) free( psz_next );
378     }
379     if( val.psz_string ) free( val.psz_string );
380
381     var_Get( p_stream, SOUT_CFG_PREFIX "vcodec", &val );
382     p_sys->i_vcodec = 0;
383     if( val.psz_string && *val.psz_string )
384     {
385         char fcc[4] = "    ";
386         memcpy( fcc, val.psz_string, __MIN( strlen( val.psz_string ), 4 ) );
387         p_sys->i_vcodec = VLC_FOURCC( fcc[0], fcc[1], fcc[2], fcc[3] );
388     }
389     if( val.psz_string ) free( val.psz_string );
390
391     var_Get( p_stream, SOUT_CFG_PREFIX "vb", &val );
392     p_sys->i_vbitrate = val.i_int;
393     if( p_sys->i_vbitrate < 16000 ) p_sys->i_vbitrate *= 1000;
394
395     var_Get( p_stream, SOUT_CFG_PREFIX "scale", &val );
396     p_sys->f_scale = val.f_float;
397
398     var_Get( p_stream, SOUT_CFG_PREFIX "fps", &val );
399     p_sys->f_fps = val.f_float;
400
401     var_Get( p_stream, SOUT_CFG_PREFIX "width", &val );
402     p_sys->i_width = val.i_int;
403
404     var_Get( p_stream, SOUT_CFG_PREFIX "height", &val );
405     p_sys->i_height = val.i_int;
406
407     var_Get( p_stream, SOUT_CFG_PREFIX "deinterlace", &val );
408     p_sys->b_deinterlace = val.b_bool;
409
410     var_Get( p_stream, SOUT_CFG_PREFIX "croptop", &val );
411     p_sys->i_crop_top = val.i_int;
412     var_Get( p_stream, SOUT_CFG_PREFIX "cropbottom", &val );
413     p_sys->i_crop_bottom = val.i_int;
414     var_Get( p_stream, SOUT_CFG_PREFIX "cropleft", &val );
415     p_sys->i_crop_left = val.i_int;
416     var_Get( p_stream, SOUT_CFG_PREFIX "cropright", &val );
417     p_sys->i_crop_right = val.i_int;
418
419     var_Get( p_stream, SOUT_CFG_PREFIX "threads", &val );
420     p_sys->i_threads = val.i_int;
421
422     if( p_sys->i_vcodec )
423     {
424         msg_Dbg( p_stream, "codec video=%4.4s %dx%d scaling: %f %dkb/s",
425                  (char *)&p_sys->i_vcodec, p_sys->i_width, p_sys->i_height,
426                  p_sys->f_scale, p_sys->i_vbitrate / 1000 );
427     }
428
429     /* Subpictures transcoding parameters */
430     var_Get( p_stream, SOUT_CFG_PREFIX "senc", &val );
431     p_sys->psz_senc = NULL;
432     p_sys->p_spu_cfg = NULL;
433     if( val.psz_string && *val.psz_string )
434     {
435         char *psz_next;
436         psz_next = sout_CfgCreate( &p_sys->psz_senc, &p_sys->p_spu_cfg,
437                                    val.psz_string );
438         if( psz_next ) free( psz_next );
439     }
440     if( val.psz_string ) free( val.psz_string );
441
442     var_Get( p_stream, SOUT_CFG_PREFIX "scodec", &val );
443     p_sys->i_scodec = 0;
444     if( val.psz_string && *val.psz_string )
445     {
446         char fcc[4] = "    ";
447         memcpy( fcc, val.psz_string, __MIN( strlen( val.psz_string ), 4 ) );
448         p_sys->i_scodec = VLC_FOURCC( fcc[0], fcc[1], fcc[2], fcc[3] );
449     }
450     if( val.psz_string ) free( val.psz_string );
451
452     if( p_sys->i_scodec )
453     {
454         msg_Dbg( p_stream, "codec spu=%4.4s", (char *)&p_sys->i_acodec );
455     }
456
457     var_Get( p_stream, SOUT_CFG_PREFIX "soverlay", &val );
458     p_sys->b_soverlay = val.b_bool;
459     p_sys->p_filter_blend = 0;
460
461     for( i = 0; i < SUBPICTURE_RING_SIZE; i++ )
462     {
463         p_sys->pp_subpics[i] = 0;
464     }
465
466     var_Get( p_stream, SOUT_CFG_PREFIX "audio-sync", &val );
467     p_sys->b_audio_sync = val.b_bool;
468     if( p_sys->f_fps > 0 ) p_sys->b_audio_sync = VLC_TRUE;
469
470     p_stream->pf_add    = Add;
471     p_stream->pf_del    = Del;
472     p_stream->pf_send   = Send;
473     p_stream->p_sys     = p_sys;
474
475     avcodec_init();
476     avcodec_register_all();
477
478     return VLC_SUCCESS;
479 }
480
481 /*****************************************************************************
482  * Close:
483  *****************************************************************************/
484 static void Close( vlc_object_t * p_this )
485 {
486     sout_stream_t       *p_stream = (sout_stream_t*)p_this;
487     sout_stream_sys_t   *p_sys = p_stream->p_sys;
488
489     sout_StreamDelete( p_sys->p_out );
490
491     while( p_sys->p_audio_cfg != NULL )
492     {
493         sout_cfg_t *p_next = p_sys->p_audio_cfg->p_next;
494
495         if( p_sys->p_audio_cfg->psz_name )
496             free( p_sys->p_audio_cfg->psz_name );
497         if( p_sys->p_audio_cfg->psz_value )
498             free( p_sys->p_audio_cfg->psz_value );
499         free( p_sys->p_audio_cfg );
500
501         p_sys->p_audio_cfg = p_next;
502     }
503     if( p_sys->psz_aenc ) free( p_sys->psz_aenc );
504
505     while( p_sys->p_video_cfg != NULL )
506     {
507         sout_cfg_t *p_next = p_sys->p_video_cfg->p_next;
508
509         if( p_sys->p_video_cfg->psz_name )
510             free( p_sys->p_video_cfg->psz_name );
511         if( p_sys->p_video_cfg->psz_value )
512             free( p_sys->p_video_cfg->psz_value );
513         free( p_sys->p_video_cfg );
514
515         p_sys->p_video_cfg = p_next;
516     }
517     if( p_sys->psz_venc ) free( p_sys->psz_venc );
518
519     while( p_sys->p_spu_cfg != NULL )
520     {
521         sout_cfg_t *p_next = p_sys->p_spu_cfg->p_next;
522
523         if( p_sys->p_spu_cfg->psz_name )
524             free( p_sys->p_spu_cfg->psz_name );
525         if( p_sys->p_spu_cfg->psz_value )
526             free( p_sys->p_spu_cfg->psz_value );
527         free( p_sys->p_spu_cfg );
528
529         p_sys->p_spu_cfg = p_next;
530     }
531     if( p_sys->psz_senc ) free( p_sys->psz_senc );
532
533     if( p_sys->p_filter_blend )
534     {
535         if( p_sys->p_filter_blend->p_module )
536             module_Unneed( p_sys->p_filter_blend,
537                            p_sys->p_filter_blend->p_module );
538
539         vlc_object_detach( p_sys->p_filter_blend );
540         vlc_object_destroy( p_sys->p_filter_blend );
541     }
542
543     vlc_object_destroy( p_sys );
544 }
545
546 struct sout_stream_id_t
547 {
548     vlc_fourcc_t  b_transcode;
549     es_format_t f_src;        /* only if transcoding */
550     es_format_t f_dst;        /*  "   "      " */
551     unsigned int  i_inter_pixfmt; /* intermediary format when transcoding */
552
553     /* id of the out stream */
554     void *id;
555
556     /* Decoder */
557     decoder_t       *p_decoder;
558
559     /* Encoder */
560     encoder_t       *p_encoder;
561     vlc_fourcc_t    b_enc_inited;
562
563     /* ffmpeg part */
564     AVCodec         *ff_dec;
565     AVCodecContext  *ff_dec_c;
566
567     mtime_t         i_dts;
568     mtime_t         i_length;
569
570     int             i_buffer;
571     int             i_buffer_pos;
572     uint8_t         *p_buffer;
573
574     AVFrame         *p_ff_pic;
575     AVFrame         *p_ff_pic_tmp0; /* to do deinterlace */
576     AVFrame         *p_ff_pic_tmp1; /* to do pix conversion */
577     AVFrame         *p_ff_pic_tmp2; /* to do resample */
578     AVFrame         *p_ff_pic_tmp3; /* to do subpicture overlay */
579
580     ImgReSampleContext *p_vresample;
581
582     /* Sync */
583     date_t          interpolated_pts;
584 };
585
586
587 static sout_stream_id_t *Add( sout_stream_t *p_stream, es_format_t *p_fmt )
588 {
589     sout_stream_sys_t *p_sys = p_stream->p_sys;
590     sout_stream_id_t *id;
591
592     id = malloc( sizeof( sout_stream_id_t ) );
593     memset( id, 0, sizeof(sout_stream_id_t) );
594
595     id->id = NULL;
596     id->p_decoder = NULL;
597     id->p_encoder = NULL;
598
599     /* Get source format */
600     id->f_src = *p_fmt;
601
602     /* Create destination format */
603     es_format_Init( &id->f_dst, p_fmt->i_cat, 0 );
604     id->f_dst.i_id    = id->f_src.i_id;
605     id->f_dst.i_group = id->f_src.i_group;
606     if( id->f_src.psz_language )
607         id->f_dst.psz_language = strdup( id->f_src.psz_language );
608
609     if( p_fmt->i_cat == AUDIO_ES && (p_sys->i_acodec || p_sys->psz_aenc) )
610     {
611         msg_Dbg( p_stream,
612                  "creating audio transcoding from fcc=`%4.4s' to fcc=`%4.4s'",
613                  (char*)&p_fmt->i_codec, (char*)&p_sys->i_acodec );
614
615         /* Complete destination format */
616         id->f_dst.i_codec = p_sys->i_acodec;
617         id->f_dst.audio.i_rate = p_sys->i_sample_rate > 0 ?
618             p_sys->i_sample_rate : id->f_src.audio.i_rate;
619         id->f_dst.audio.i_channels = p_sys->i_channels > 0 ?
620             p_sys->i_channels : id->f_src.audio.i_channels;
621         id->f_dst.i_bitrate = p_sys->i_abitrate;
622         id->f_dst.audio.i_bitspersample = id->f_src.audio.i_bitspersample;
623
624         /* build decoder -> filter -> encoder */
625         if( transcode_audio_ffmpeg_new( p_stream, id ) )
626         {
627             msg_Err( p_stream, "cannot create audio chain" );
628             free( id );
629             return NULL;
630         }
631
632         /* open output stream */
633         id->id = p_sys->p_out->pf_add( p_sys->p_out, &id->f_dst );
634         id->b_transcode = VLC_TRUE;
635
636         if( id->id == NULL )
637         {
638             free( id );
639             return NULL;
640         }
641
642         date_Init( &id->interpolated_pts, p_fmt->audio.i_rate, 1 );
643     }
644     else if( p_fmt->i_cat == VIDEO_ES &&
645              (p_sys->i_vcodec != 0 || p_sys->psz_venc) )
646     {
647         msg_Dbg( p_stream,
648                  "creating video transcoding from fcc=`%4.4s' to fcc=`%4.4s'",
649                  (char*)&p_fmt->i_codec, (char*)&p_sys->i_vcodec );
650
651         /* Complete destination format */
652         id->f_dst.i_codec = p_sys->i_vcodec;
653         id->f_dst.video.i_width  = p_sys->i_width;
654         id->f_dst.video.i_height = p_sys->i_height;
655         id->f_dst.i_bitrate = p_sys->i_vbitrate;
656
657         /* build decoder -> filter -> encoder */
658         if( transcode_video_ffmpeg_new( p_stream, id ) )
659         {
660             msg_Err( p_stream, "cannot create video chain" );
661             free( id );
662             return NULL;
663         }
664 #if 0
665         /* open output stream */
666         id->id = p_sys->p_out->pf_add( p_sys->p_out, &id->f_dst );
667 #endif
668         id->b_transcode = VLC_TRUE;
669
670         if( id->f_dst.video.i_frame_rate && id->f_dst.video.i_frame_rate_base )
671         {
672             date_Init( &id->interpolated_pts, id->f_dst.video.i_frame_rate,
673                        id->f_dst.video.i_frame_rate_base );
674         }
675         else if( p_sys->b_audio_sync )
676         {
677             msg_Warn( p_stream, "no video frame rate available, disabling "
678                       "audio sync" );
679             p_sys->b_audio_sync = VLC_FALSE;
680         }
681     }
682     else if( p_fmt->i_cat == SPU_ES && (p_sys->i_scodec || p_sys->psz_senc) )
683     {
684         msg_Dbg( p_stream, "creating subtitles transcoding from fcc=`%4.4s' "
685                  "to fcc=`%4.4s'", (char*)&p_fmt->i_codec,
686                  (char*)&p_sys->i_scodec );
687
688         /* Complete destination format */
689         id->f_dst.i_codec = p_sys->i_scodec;
690
691         /* build decoder -> filter -> encoder */
692         if( transcode_spu_new( p_stream, id ) )
693         {
694             msg_Err( p_stream, "cannot create subtitles chain" );
695             free( id );
696             return NULL;
697         }
698
699         /* open output stream */
700         id->id = p_sys->p_out->pf_add( p_sys->p_out, &id->f_dst );
701         id->b_transcode = VLC_TRUE;
702
703         if( id->id == NULL )
704         {
705             free( id );
706             return NULL;
707         }
708     }
709     else if( p_fmt->i_cat == SPU_ES && p_sys->b_soverlay )
710     {
711         msg_Dbg( p_stream, "subtitles (fcc=`%4.4s') overlaying",
712                  (char*)&p_fmt->i_codec );
713
714         id->b_transcode = VLC_TRUE;
715
716         /* build decoder -> filter -> encoder */
717         if( transcode_spu_new( p_stream, id ) )
718         {
719             msg_Err( p_stream, "cannot create subtitles chain" );
720             free( id );
721             return NULL;
722         }
723     }
724     else
725     {
726         msg_Dbg( p_stream, "not transcoding a stream (fcc=`%4.4s')",
727                  (char*)&p_fmt->i_codec );
728         id->id = p_sys->p_out->pf_add( p_sys->p_out, p_fmt );
729         id->b_transcode = VLC_FALSE;
730
731         if( id->id == NULL )
732         {
733             free( id );
734             return NULL;
735         }
736     }
737
738     return id;
739 }
740
741 static int Del( sout_stream_t *p_stream, sout_stream_id_t *id )
742 {
743     sout_stream_sys_t   *p_sys = p_stream->p_sys;
744
745     if( id->b_transcode )
746     {
747         if( id->f_src.i_cat == AUDIO_ES )
748         {
749             transcode_audio_ffmpeg_close( p_stream, id );
750         }
751         else if( id->f_src.i_cat == VIDEO_ES )
752         {
753             transcode_video_ffmpeg_close( p_stream, id );
754         }
755         else if( id->f_src.i_cat == SPU_ES )
756         {
757             transcode_spu_close( p_stream, id );
758         }
759     }
760
761     if( id->id ) p_sys->p_out->pf_del( p_sys->p_out, id->id );
762     free( id );
763
764     return VLC_SUCCESS;
765 }
766
767 static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
768                  block_t *p_buffer )
769 {
770     sout_stream_sys_t *p_sys = p_stream->p_sys;
771
772     if( id->b_transcode )
773     {
774         block_t *p_buffer_out;
775
776         /* Be sure to have padding */
777         p_buffer = block_Realloc( p_buffer, 0, p_buffer->i_buffer + FF_INPUT_BUFFER_PADDING_SIZE );
778         if( p_buffer == NULL )
779         {
780             return VLC_EGENERIC;
781         }
782         p_buffer->i_buffer -= FF_INPUT_BUFFER_PADDING_SIZE;
783         memset( &p_buffer->p_buffer[p_buffer->i_buffer], 0, FF_INPUT_BUFFER_PADDING_SIZE );
784
785         if( id->f_src.i_cat == AUDIO_ES )
786         {
787             transcode_audio_ffmpeg_process( p_stream, id, p_buffer,
788                                             &p_buffer_out );
789             block_Release( p_buffer );
790         }
791         else if( id->f_src.i_cat == VIDEO_ES )
792         {
793             if( transcode_video_ffmpeg_process( p_stream, id, p_buffer,
794                 &p_buffer_out ) != VLC_SUCCESS )
795             {
796                 block_Release( p_buffer );
797                 return VLC_EGENERIC;
798             }
799             block_Release( p_buffer );
800         }
801         else if( id->f_src.i_cat == SPU_ES )
802         {
803             if( transcode_spu_process( p_stream, id, p_buffer,
804                 &p_buffer_out ) != VLC_SUCCESS )
805             {
806                 return VLC_EGENERIC;
807             }
808         }
809         else
810         {
811             block_Release( p_buffer );
812         }
813
814         if( p_buffer_out )
815         {
816             return p_sys->p_out->pf_send( p_sys->p_out, id->id, p_buffer_out );
817         }
818         return VLC_SUCCESS;
819     }
820     else if( id->id != NULL )
821     {
822         return p_sys->p_out->pf_send( p_sys->p_out, id->id, p_buffer );
823     }
824     else
825     {
826         block_Release( p_buffer );
827         return VLC_EGENERIC;
828     }
829 }
830
831 /****************************************************************************
832  * ffmpeg decoder reencoder part
833  ****************************************************************************/
834 static struct
835 {
836     vlc_fourcc_t i_fcc;
837     int          i_ff_codec;
838 } fourcc_to_ff_code[] =
839 {
840     /* audio */
841     { VLC_FOURCC( 'm', 'p', 'g', 'a' ), CODEC_ID_MP2 },
842     { VLC_FOURCC( 'm', 'p', '3', ' ' ), CODEC_ID_MP3LAME },
843     { VLC_FOURCC( 'm', 'p', '4', 'a' ), CODEC_ID_AAC },
844     { VLC_FOURCC( 'a', '5', '2', ' ' ), CODEC_ID_AC3 },
845     { VLC_FOURCC( 'a', 'c', '3', ' ' ), CODEC_ID_AC3 },
846     { VLC_FOURCC( 'w', 'm', 'a', '1' ), CODEC_ID_WMAV1 },
847     { VLC_FOURCC( 'w', 'm', 'a', '2' ), CODEC_ID_WMAV2 },
848     { VLC_FOURCC( 'v', 'o', 'r', 'b' ), CODEC_ID_VORBIS },
849     { VLC_FOURCC( 'a', 'l', 'a', 'w' ), CODEC_ID_PCM_ALAW },
850
851     /* video */
852     { VLC_FOURCC( 'm', 'p', 'g', 'v' ), CODEC_ID_MPEG1VIDEO },
853     { VLC_FOURCC( 'm', 'p', '1', 'v' ), CODEC_ID_MPEG1VIDEO },
854 #if LIBAVCODEC_BUILD >= 4676
855     { VLC_FOURCC( 'm', 'p', '2', 'v' ), CODEC_ID_MPEG2VIDEO },
856 #endif
857     { VLC_FOURCC( 'm', 'p', '4', 'v'),  CODEC_ID_MPEG4 },
858     { VLC_FOURCC( 'D', 'I', 'V', '1' ), CODEC_ID_MSMPEG4V1 },
859     { VLC_FOURCC( 'D', 'I', 'V', '2' ), CODEC_ID_MSMPEG4V2 },
860     { VLC_FOURCC( 'D', 'I', 'V', '3' ), CODEC_ID_MSMPEG4V3 },
861     { VLC_FOURCC( 'H', '2', '6', '3' ), CODEC_ID_H263 },
862     { VLC_FOURCC( 'I', '2', '6', '3' ), CODEC_ID_H263I },
863     { VLC_FOURCC( 'h', 'u', 'f', 'f' ), CODEC_ID_HUFFYUV },
864     { VLC_FOURCC( 'W', 'M', 'V', '1' ), CODEC_ID_WMV1 },
865     { VLC_FOURCC( 'W', 'M', 'V', '2' ), CODEC_ID_WMV2 },
866     { VLC_FOURCC( 'M', 'J', 'P', 'G' ), CODEC_ID_MJPEG },
867     { VLC_FOURCC( 'm', 'j', 'p', 'b' ), CODEC_ID_MJPEGB },
868     { VLC_FOURCC( 'd', 'v', 's', 'l' ), CODEC_ID_DVVIDEO },
869     { VLC_FOURCC( 'S', 'V', 'Q', '1' ), CODEC_ID_SVQ1 },
870 #if LIBAVCODEC_BUILD >= 4666
871     { VLC_FOURCC( 'S', 'V', 'Q', '3' ), CODEC_ID_SVQ3 },
872     { VLC_FOURCC( 'h', '2', '6', '4' ), CODEC_ID_H264 },
873 #endif
874 #if LIBAVCODEC_BUILD >= 4719
875     { VLC_FOURCC( 'S', 'N', 'O', 'W' ), CODEC_ID_SNOW },
876 #endif
877
878     /* raw video code, only used for 'encoding' */
879     { VLC_FOURCC( 'I', '4', '2', '0' ), CODEC_ID_RAWVIDEO },
880     { VLC_FOURCC( 'I', '4', '2', '2' ), CODEC_ID_RAWVIDEO },
881     { VLC_FOURCC( 'I', '4', '4', '4' ), CODEC_ID_RAWVIDEO },
882     { VLC_FOURCC( 'R', 'V', '1', '5' ), CODEC_ID_RAWVIDEO },
883     { VLC_FOURCC( 'R', 'V', '1', '6' ), CODEC_ID_RAWVIDEO },
884     { VLC_FOURCC( 'R', 'V', '2', '4' ), CODEC_ID_RAWVIDEO },
885     { VLC_FOURCC( 'R', 'V', '3', '2' ), CODEC_ID_RAWVIDEO },
886     { VLC_FOURCC( 'Y', 'U', 'Y', '2' ), CODEC_ID_RAWVIDEO },
887     { VLC_FOURCC( 'Y', 'V', '1', '2' ), CODEC_ID_RAWVIDEO },
888     { VLC_FOURCC( 'I', 'Y', 'U', 'V' ), CODEC_ID_RAWVIDEO },
889
890     { VLC_FOURCC(   0,   0,   0,   0 ), 0 }
891 };
892
893 static inline int get_ff_codec( vlc_fourcc_t i_fcc )
894 {
895     int i;
896
897     for( i = 0; fourcc_to_ff_code[i].i_fcc != 0; i++ )
898     {
899         if( fourcc_to_ff_code[i].i_fcc == i_fcc )
900         {
901             return fourcc_to_ff_code[i].i_ff_codec;
902         }
903     }
904
905     return 0;
906 }
907
908 static inline int get_ff_chroma( vlc_fourcc_t i_chroma )
909 {
910     switch( i_chroma )
911     {
912         case VLC_FOURCC( 'Y', 'V', '1', '2' ):
913         case VLC_FOURCC( 'I', 'Y', 'U', 'V' ):
914         case VLC_FOURCC( 'I', '4', '2', '0' ):
915             return PIX_FMT_YUV420P;
916         case VLC_FOURCC( 'I', '4', '2', '2' ):
917             return PIX_FMT_YUV422P;
918         case VLC_FOURCC( 'I', '4', '4', '4' ):
919             return PIX_FMT_YUV444P;
920         case VLC_FOURCC( 'R', 'V', '1', '5' ):
921             return PIX_FMT_RGB555;
922         case VLC_FOURCC( 'R', 'V', '1', '6' ):
923             return PIX_FMT_RGB565;
924         case VLC_FOURCC( 'R', 'V', '2', '4' ):
925             return PIX_FMT_BGR24;
926         case VLC_FOURCC( 'R', 'V', '3', '2' ):
927             return PIX_FMT_RGBA32;
928         case VLC_FOURCC( 'G', 'R', 'E', 'Y' ):
929             return PIX_FMT_GRAY8;
930         case VLC_FOURCC( 'Y', 'U', 'Y', '2' ):
931             return PIX_FMT_YUV422;
932         default:
933             return 0;
934     }
935 }
936
937 static inline vlc_fourcc_t get_vlc_chroma( int i_pix_fmt )
938 {
939     switch( i_pix_fmt )
940     {
941     case PIX_FMT_YUV420P:
942         return VLC_FOURCC('I','4','2','0');
943     case PIX_FMT_YUV422P:
944         return VLC_FOURCC('I','4','2','2');
945     case PIX_FMT_YUV444P:
946         return VLC_FOURCC('I','4','4','4');
947
948     case PIX_FMT_YUV422:
949         return VLC_FOURCC('Y','U','Y','2');
950
951     case PIX_FMT_RGB555:
952         return VLC_FOURCC('R','V','1','5');
953     case PIX_FMT_RGB565:
954         return VLC_FOURCC('R','V','1','6');
955     case PIX_FMT_RGB24:
956         return VLC_FOURCC('R','V','2','4');
957     case PIX_FMT_RGBA32:
958         return VLC_FOURCC('R','V','3','2');
959     case PIX_FMT_GRAY8:
960         return VLC_FOURCC('G','R','E','Y');
961
962     case PIX_FMT_YUV410P:
963     case PIX_FMT_YUV411P:
964     case PIX_FMT_BGR24:
965     default:
966         return 0;
967     }
968 }
969
970 static int transcode_audio_ffmpeg_new( sout_stream_t *p_stream,
971                                        sout_stream_id_t *id )
972 {
973     int i_ff_codec;
974
975     if( id->f_src.i_codec == VLC_FOURCC('s','1','6','l') ||
976         id->f_src.i_codec == VLC_FOURCC('s','1','6','b') ||
977         id->f_src.i_codec == VLC_FOURCC('s','8',' ',' ') ||
978         id->f_src.i_codec == VLC_FOURCC('u','8',' ',' ') )
979     {
980         id->ff_dec = NULL;
981
982         id->ff_dec_c = avcodec_alloc_context();
983         id->ff_dec_c->sample_rate = id->f_src.audio.i_rate;
984         id->ff_dec_c->channels    = id->f_src.audio.i_channels;
985         id->ff_dec_c->block_align = id->f_src.audio.i_blockalign;
986         id->ff_dec_c->bit_rate    = id->f_src.i_bitrate;
987     }
988     else
989     {
990         /* find decoder */
991         i_ff_codec = get_ff_codec( id->f_src.i_codec );
992         if( i_ff_codec == 0 )
993         {
994             msg_Err( p_stream, "cannot find decoder id" );
995             return VLC_EGENERIC;
996         }
997
998         id->ff_dec = avcodec_find_decoder( i_ff_codec );
999         if( !id->ff_dec )
1000         {
1001             msg_Err( p_stream, "cannot find decoder (avcodec)" );
1002             return VLC_EGENERIC;
1003         }
1004
1005         id->ff_dec_c = avcodec_alloc_context();
1006         id->ff_dec_c->sample_rate = id->f_src.audio.i_rate;
1007         id->ff_dec_c->channels    = id->f_src.audio.i_channels;
1008         id->ff_dec_c->block_align = id->f_src.audio.i_blockalign;
1009         id->ff_dec_c->bit_rate    = id->f_src.i_bitrate;
1010
1011         id->ff_dec_c->extradata_size = id->f_src.i_extra;
1012         id->ff_dec_c->extradata      = id->f_src.p_extra;
1013         if( avcodec_open( id->ff_dec_c, id->ff_dec ) )
1014         {
1015             msg_Err( p_stream, "cannot open decoder" );
1016             av_free( id->ff_dec_c );
1017             return VLC_EGENERIC;
1018         }
1019     }
1020
1021     id->i_buffer     = 2 * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1022     id->i_buffer_pos = 0;
1023     id->p_buffer     = malloc( id->i_buffer );
1024
1025     /* Sanity check for audio channels */
1026     id->f_dst.audio.i_channels =
1027         __MIN( id->f_dst.audio.i_channels, id->f_src.audio.i_channels );
1028
1029     /* find encoder */
1030     id->p_encoder = vlc_object_create( p_stream, VLC_OBJECT_ENCODER );
1031
1032     /* Initialization of encoder format structures */
1033     es_format_Init( &id->p_encoder->fmt_in, AUDIO_ES, AOUT_FMT_S16_NE );
1034     id->p_encoder->fmt_in.audio.i_format = AOUT_FMT_S16_NE;
1035     id->p_encoder->fmt_in.audio.i_rate = id->f_dst.audio.i_rate;
1036     id->p_encoder->fmt_in.audio.i_physical_channels =
1037         id->p_encoder->fmt_in.audio.i_original_channels =
1038             pi_channels_maps[id->f_dst.audio.i_channels];
1039     id->p_encoder->fmt_in.audio.i_channels = id->f_dst.audio.i_channels;
1040     id->p_encoder->fmt_in.audio.i_bitspersample = 16;
1041
1042     id->p_encoder->fmt_out = id->f_dst;
1043
1044     id->p_encoder->p_cfg = p_stream->p_sys->p_audio_cfg;
1045
1046     /* Attach object to parent so object variables inheritance works */
1047     vlc_object_attach( id->p_encoder, p_stream );
1048
1049     id->p_encoder->p_module =
1050         module_Need( id->p_encoder, "encoder",
1051                      p_stream->p_sys->psz_aenc, VLC_TRUE );
1052     if( !id->p_encoder->p_module )
1053     {
1054         vlc_object_detach( id->p_encoder );
1055         vlc_object_destroy( id->p_encoder );
1056         msg_Err( p_stream, "cannot open encoder" );
1057         av_free( id->ff_dec_c );
1058         return VLC_EGENERIC;
1059     }
1060
1061     id->b_enc_inited = VLC_FALSE;
1062
1063     id->f_dst = id->p_encoder->fmt_out;
1064
1065     /* Hack for mp3 transcoding support */
1066     if( id->f_dst.i_codec == VLC_FOURCC( 'm','p','3',' ' ) )
1067     {
1068         id->f_dst.i_codec = VLC_FOURCC( 'm','p','g','a' );
1069     }
1070
1071     return VLC_SUCCESS;
1072 }
1073
1074 static void transcode_audio_ffmpeg_close( sout_stream_t *p_stream,
1075                                           sout_stream_id_t *id )
1076 {
1077     if( id->ff_dec ) avcodec_close( id->ff_dec_c );
1078     av_free( id->ff_dec_c );
1079
1080     module_Unneed( id->p_encoder, id->p_encoder->p_module );
1081
1082     vlc_object_detach( id->p_encoder );
1083     vlc_object_destroy( id->p_encoder );
1084
1085     free( id->p_buffer );
1086 }
1087
1088 static int transcode_audio_ffmpeg_process( sout_stream_t *p_stream,
1089                                            sout_stream_id_t *id,
1090                                            block_t *in,
1091                                            block_t **out )
1092 {
1093     sout_stream_sys_t *p_sys = p_stream->p_sys;
1094     aout_buffer_t aout_buf;
1095     block_t *p_block;
1096     int i_buffer = in->i_buffer;
1097     char *p_buffer = in->p_buffer;
1098     id->i_dts = in->i_dts;
1099     *out = NULL;
1100
1101     while( i_buffer )
1102     {
1103         id->i_buffer_pos = 0;
1104
1105         /* decode as much data as possible */
1106         if( id->ff_dec )
1107         {
1108             int i_used;
1109
1110             i_used = avcodec_decode_audio( id->ff_dec_c,
1111                          (int16_t*)id->p_buffer, &id->i_buffer_pos,
1112                          p_buffer, i_buffer );
1113
1114 #if 0
1115             msg_Warn( p_stream, "avcodec_decode_audio: %d used on %d",
1116                       i_used, i_buffer );
1117 #endif
1118             if( i_used < 0 )
1119             {
1120                 msg_Warn( p_stream, "error audio decoding");
1121                 break;
1122             }
1123
1124             i_buffer -= i_used;
1125             p_buffer += i_used;
1126
1127             if ( id->i_buffer_pos < 0 )
1128             {
1129                 msg_Warn( p_stream, "weird error audio decoding");
1130                 break;
1131             }
1132         }
1133         else
1134         {
1135             int16_t *sout = (int16_t*)id->p_buffer;
1136
1137             if( id->f_src.i_codec == VLC_FOURCC( 's', '8', ' ', ' ' ) ||
1138                 id->f_src.i_codec == VLC_FOURCC( 'u', '8', ' ', ' ' ) )
1139             {
1140                 int8_t *sin = (int8_t*)p_buffer;
1141                 int i_used = __MIN( id->i_buffer/2, i_buffer );
1142                 int i_samples = i_used;
1143
1144                 if( id->f_src.i_codec == VLC_FOURCC( 's', '8', ' ', ' ' ) )
1145                     while( i_samples > 0 )
1146                     {
1147                         *sout++ = ( *sin++ ) << 8;
1148                         i_samples--;
1149                     }
1150                 else
1151                     while( i_samples > 0 )
1152                     {
1153                         *sout++ = ( *sin++ - 128 ) << 8;
1154                         i_samples--;
1155                     }
1156
1157                 i_buffer -= i_used;
1158                 p_buffer += i_used;
1159                 id->i_buffer_pos = i_used * 2;
1160             }
1161             else if( id->f_src.i_codec == VLC_FOURCC( 's', '1', '6', 'l' ) ||
1162                      id->f_src.i_codec == VLC_FOURCC( 's', '1', '6', 'b' ) )
1163             {
1164                 int16_t *sin = (int16_t*)p_buffer;
1165                 int i_used = __MIN( id->i_buffer, i_buffer );
1166                 int i_samples = i_used / 2;
1167
1168                 /* first copy */
1169                 memcpy( sout, sin, i_used );
1170
1171 #ifdef WORDS_BIGENDIAN
1172                 if( id->f_src.i_codec == VLC_FOURCC( 's', '1', '6', 'l' ) )
1173 #else
1174                 if( id->f_src.i_codec == VLC_FOURCC( 's', '1', '6', 'b' ) )
1175 #endif
1176                 {
1177                     uint8_t *dat = (uint8_t*)sout;
1178
1179                     while( i_samples > 0 )
1180                     {
1181                         uint8_t tmp;
1182                         tmp    = dat[0];
1183                         dat[0] = dat[1];
1184                         dat[1] = tmp;
1185
1186                         dat += 2;
1187
1188                         i_samples--;
1189                     }
1190                 }
1191
1192                 i_buffer -= i_used;
1193                 p_buffer += i_used;
1194                 id->i_buffer_pos = i_used;
1195             }
1196         }
1197
1198         if( id->i_buffer_pos == 0 ) continue;
1199
1200         /* Encode as much data as possible */
1201         if( !id->b_enc_inited && id->p_encoder->pf_header )
1202         {
1203             block_t *p_block_tmp;
1204
1205             p_block = id->p_encoder->pf_header( id->p_encoder );
1206             p_block_tmp = p_block;
1207             while( p_block_tmp )
1208             {
1209                 p_block_tmp->i_dts = p_block_tmp->i_pts = in->i_dts;
1210                 p_block_tmp = p_block_tmp->p_next;
1211             }
1212             block_ChainAppend( out, p_block );
1213
1214             id->b_enc_inited = VLC_TRUE;
1215         }
1216
1217         aout_buf.p_buffer = id->p_buffer;
1218         aout_buf.i_nb_bytes = id->i_buffer_pos;
1219         aout_buf.i_nb_samples = id->i_buffer_pos/2/id->f_src.audio.i_channels;
1220         aout_buf.start_date = id->i_dts;
1221         aout_buf.end_date = id->i_dts;
1222
1223         if( p_sys->b_audio_sync )
1224         {
1225             aout_buf.start_date = date_Get( &id->interpolated_pts ) + 1;
1226             p_sys->i_master_drift = id->i_dts - aout_buf.start_date;
1227             date_Increment( &id->interpolated_pts, aout_buf.i_nb_samples );
1228         }
1229
1230         id->i_dts += ( I64C(1000000) * id->i_buffer_pos / 2 /
1231             id->f_src.audio.i_channels / id->f_src.audio.i_rate );
1232
1233         if( id->p_encoder->fmt_in.audio.i_channels == 1 &&
1234             id->f_src.audio.i_channels > 1 )
1235         {
1236             int16_t *p_sample = (int16_t *)aout_buf.p_buffer;
1237             int i_src_c = id->f_src.audio.i_channels;
1238             unsigned int i;
1239
1240             for( i = 0; i < aout_buf.i_nb_samples; i++ )
1241             {
1242                 int j, c = 0;
1243
1244                 for( j = 1; j < i_src_c; j++ )
1245                 {
1246                     c += p_sample[i_src_c * i + j];
1247                 }
1248                 p_sample[i] = c / (i_src_c-1);
1249             }
1250             aout_buf.i_nb_bytes = i * 2;
1251         }
1252         else if( id->p_encoder->fmt_in.audio.i_channels == 2 &&
1253                  id->f_src.audio.i_channels > 2 )
1254         {
1255             int i_src_c = id->f_src.audio.i_channels;
1256             unsigned int i;
1257
1258             static const float mixf_l[4][6] = /* [i_src_c - 3][channel index] */
1259             {
1260                 { 0.00, 1.00, 0.00, 0.00, 0.00, 0.00 }, /* 3 channels */
1261                 { 0.00, 0.50, 0.50, 0.00, 0.00, 0.00 }, /* 4 channels */
1262                 { 0.00, 0.50, 0.00, 0.50, 0.00, 0.00 }, /* 5 channels */
1263                 { 0.00, 0.34, 0.33, 0.00, 0.33, 0.00 }, /* 6 channels */
1264             };
1265             static const float mixf_r[4][6] = /* [i_src_c - 3][channel index] */
1266             {
1267                 { 0.00, 1.00, 0.00, 0.00, 0.00, 0.00 }, /* 3 channels */
1268                 { 0.00, 0.00, 0.50, 0.50, 0.00, 0.00 }, /* 4 channels */
1269                 { 0.00, 0.00, 0.50, 0.00, 0.50, 0.00 }, /* 5 channels */
1270                 { 0.00, 0.00, 0.33, 0.34, 0.00, 0.33 }, /* 6 channels */
1271             };
1272
1273
1274             for( i = 0; i < aout_buf.i_nb_samples; i++ )
1275             {
1276                 int16_t *p_src = (int16_t *)aout_buf.p_buffer + i_src_c * i;
1277                 int16_t *p_dst = (int16_t *)aout_buf.p_buffer + 2 * i;
1278
1279                 int j;
1280                 float l = 0.0, r = 0.0;
1281                 for( j = 0; j < i_src_c; j++ )
1282                 {
1283                     l += mixf_l[i_src_c-3][j] * p_src[j];
1284                     r += mixf_r[i_src_c-3][j] * p_src[j];
1285                 }
1286
1287                 p_dst[0] = (int)( l + 0.5 );
1288                 p_dst[1] = (int)( r + 0.5 );
1289             }
1290             aout_buf.i_nb_bytes = i * 2 * 2;
1291         }
1292         else if( id->f_src.audio.i_channels !=
1293                  id->p_encoder->fmt_in.audio.i_channels )
1294         {
1295             unsigned int i;
1296             int j;
1297
1298             /* This is for liba52 which is what ffmpeg uses to decode ac3 */
1299             static const int translation[7][6] =
1300             {{ 0, 0, 0, 0, 0, 0 },      /* 0 channels (rarely used) */
1301              { 0, 0, 0, 0, 0, 0 },       /* 1 ch */
1302              { 0, 1, 0, 0, 0, 0 },       /* 2 */
1303              { 1, 2, 0, 0, 0, 0 },       /* 3 */
1304              { 1, 3, 2, 0, 0, 0 },       /* 4 */
1305              { 1, 3, 4, 2, 0, 0 },       /* 5 */
1306              { 1, 3, 4, 5, 2, 0 }};      /* 6 */
1307
1308             /* dumb downmixing */
1309             for( i = 0; i < aout_buf.i_nb_samples; i++ )
1310             {
1311                 uint16_t *p_buffer = (uint16_t *)aout_buf.p_buffer;
1312                 for( j = 0 ; j < id->p_encoder->fmt_in.audio.i_channels; j++ )
1313                 {
1314                     p_buffer[i*id->p_encoder->fmt_in.audio.i_channels+j] =
1315                         p_buffer[i*id->f_src.audio.i_channels+
1316                                  translation[id->f_src.audio.i_channels][j]];
1317                 }
1318             }
1319             aout_buf.i_nb_bytes = i*id->p_encoder->fmt_in.audio.i_channels * 2;
1320         }
1321
1322         p_block = id->p_encoder->pf_encode_audio( id->p_encoder, &aout_buf );
1323         block_ChainAppend( out, p_block );
1324     }
1325
1326     return VLC_SUCCESS;
1327 }
1328
1329
1330 /*
1331  * video
1332  */
1333 static int transcode_video_ffmpeg_new( sout_stream_t *p_stream,
1334                                        sout_stream_id_t *id )
1335 {
1336     sout_stream_sys_t *p_sys = p_stream->p_sys;
1337     int i_ff_codec;
1338
1339     /* Open decoder */
1340     if( id->f_src.i_codec == VLC_FOURCC( 'I', '4', '2', '0' ) ||
1341         id->f_src.i_codec == VLC_FOURCC( 'I', '4', '2', '2' ) ||
1342         id->f_src.i_codec == VLC_FOURCC( 'I', '4', '4', '4' ) ||
1343         id->f_src.i_codec == VLC_FOURCC( 'Y', 'V', '1', '2' ) ||
1344         id->f_src.i_codec == VLC_FOURCC( 'Y', 'U', 'Y', '2' ) ||
1345         id->f_src.i_codec == VLC_FOURCC( 'I', 'Y', 'U', 'V' ) ||
1346         id->f_src.i_codec == VLC_FOURCC( 'R', 'V', '1', '5' ) ||
1347         id->f_src.i_codec == VLC_FOURCC( 'R', 'V', '1', '6' ) ||
1348         id->f_src.i_codec == VLC_FOURCC( 'R', 'V', '2', '4' ) ||
1349         id->f_src.i_codec == VLC_FOURCC( 'R', 'V', '3', '2' ) ||
1350         id->f_src.i_codec == VLC_FOURCC( 'G', 'R', 'E', 'Y' ) )
1351     {
1352         id->ff_dec              = NULL;
1353         id->ff_dec_c            = avcodec_alloc_context();
1354         id->ff_dec_c->width     = id->f_src.video.i_width;
1355         id->ff_dec_c->height    = id->f_src.video.i_height;
1356         id->ff_dec_c->pix_fmt   = get_ff_chroma( id->f_src.i_codec );
1357
1358 #if LIBAVCODEC_BUILD >= 4687
1359         if( id->ff_dec_c->width )
1360         id->ff_dec_c->sample_aspect_ratio =
1361             av_d2q( id->f_src.video.i_aspect / (double)VOUT_ASPECT_FACTOR *
1362                     id->ff_dec_c->height / id->ff_dec_c->width, 255 );
1363 #else
1364         id->ff_dec_c->aspect_ratio =
1365             id->f_src.video.i_aspect / (float)VOUT_ASPECT_FACTOR;
1366 #endif
1367     }
1368     else
1369     {
1370         /* find decoder */
1371         i_ff_codec = get_ff_codec( id->f_src.i_codec );
1372         if( i_ff_codec == 0 )
1373         {
1374             msg_Err( p_stream, "cannot find decoder" );
1375             return VLC_EGENERIC;
1376         }
1377
1378         id->ff_dec = avcodec_find_decoder( i_ff_codec );
1379         if( !id->ff_dec )
1380         {
1381             msg_Err( p_stream, "cannot find decoder" );
1382             return VLC_EGENERIC;
1383         }
1384
1385         id->ff_dec_c = avcodec_alloc_context();
1386         id->ff_dec_c->width         = id->f_src.video.i_width;
1387         id->ff_dec_c->height        = id->f_src.video.i_height;
1388         id->ff_dec_c->bits_per_sample=id->f_src.video.i_bits_per_pixel;
1389         /* id->ff_dec_c->bit_rate      = id->f_src.i_bitrate; */
1390
1391         if( id->f_src.i_extra > 0 )
1392         {
1393             if( i_ff_codec == CODEC_ID_SVQ3 )
1394             {
1395                 int i_size = id->f_src.i_extra;
1396                 uint8_t *p;
1397
1398                 id->ff_dec_c->extradata_size = i_size + 12;
1399                 p = id->ff_dec_c->extradata  = malloc( i_size + 12 );
1400
1401                 memcpy( &p[0],  "SVQ3", 4 );
1402                 memset( &p[4], 0, 8 );
1403                 memcpy( &p[12], id->f_src.p_extra, i_size );
1404
1405                 /* Now remove all atoms before the SMI one */
1406                 if( id->ff_dec_c->extradata_size > 0x5a && strncmp( &p[0x56], "SMI ", 4 ) )
1407                 {
1408                     uint8_t *psz = &p[0x52];
1409
1410                     while( psz < &p[id->ff_dec_c->extradata_size - 8] )
1411                     {
1412                         int i_size = GetDWBE( psz );
1413                         if( i_size <= 1 )
1414                         {
1415                             /* FIXME handle 1 as long size */
1416                             break;
1417                         }
1418                         if( !strncmp( &psz[4], "SMI ", 4 ) )
1419                         {
1420                             memmove( &p[0x52], psz, &p[id->ff_dec_c->extradata_size] - psz );
1421                             break;
1422                         }
1423                         psz += i_size;
1424                     }
1425                 }
1426             }
1427             else
1428             {
1429                 id->ff_dec_c->extradata_size= id->f_src.i_extra;
1430                 id->ff_dec_c->extradata = malloc( id->f_src.i_extra + FF_INPUT_BUFFER_PADDING_SIZE );
1431
1432                 memcpy( id->ff_dec_c->extradata, id->f_src.p_extra, id->f_src.i_extra );
1433                 memset( (uint8_t*)id->ff_dec_c->extradata + id->f_src.i_extra, 0, FF_INPUT_BUFFER_PADDING_SIZE );
1434             }
1435         }
1436         id->ff_dec_c->workaround_bugs = FF_BUG_AUTODETECT;
1437         id->ff_dec_c->error_resilience= -1;
1438         id->ff_dec_c->get_buffer    = transcode_video_ffmpeg_getframebuf;
1439         id->ff_dec_c->opaque        = p_sys;
1440
1441         if( avcodec_open( id->ff_dec_c, id->ff_dec ) < 0 )
1442         {
1443             msg_Err( p_stream, "cannot open decoder" );
1444             av_free( id->ff_dec_c );
1445             return VLC_EGENERIC;
1446         }
1447     }
1448
1449     /* Open encoder */
1450     id->p_encoder = vlc_object_create( p_stream, VLC_OBJECT_ENCODER );
1451
1452     /* Initialization of encoder format structures */
1453     es_format_Init( &id->p_encoder->fmt_in,
1454                     id->f_src.i_cat, get_vlc_chroma(id->ff_dec_c->pix_fmt) );
1455
1456     /* The dimensions will be set properly later on.
1457      * Just put sensible values so we can test if there is an encoder. */
1458     id->p_encoder->fmt_in.video.i_width =
1459         id->f_src.video.i_width ?  id->f_src.video.i_width : 16;
1460     id->p_encoder->fmt_in.video.i_height =
1461         id->f_src.video.i_height ? id->f_src.video.i_height : 16;
1462
1463     id->p_encoder->fmt_in.video.i_frame_rate = 25; /* FIXME as it break mpeg */
1464     id->p_encoder->fmt_in.video.i_frame_rate_base= 1;
1465     if( id->ff_dec )
1466     {
1467         id->p_encoder->fmt_in.video.i_frame_rate = id->ff_dec_c->frame_rate;
1468 #if LIBAVCODEC_BUILD >= 4662
1469         id->p_encoder->fmt_in.video.i_frame_rate_base =
1470             id->ff_dec_c->frame_rate_base;
1471 #endif
1472
1473 #if LIBAVCODEC_BUILD >= 4687
1474         if( id->ff_dec_c->height )
1475         id->p_encoder->fmt_in.video.i_aspect = VOUT_ASPECT_FACTOR *
1476             ( av_q2d(id->ff_dec_c->sample_aspect_ratio) *
1477               id->ff_dec_c->width / id->ff_dec_c->height );
1478 #else
1479         id->p_encoder->fmt_in.video.i_aspect = VOUT_ASPECT_FACTOR *
1480             id->ff_dec_c->aspect_ratio;
1481 #endif
1482     }
1483
1484     /* Override with user settings */
1485     if( p_sys->f_fps > 0 )
1486     {
1487         id->p_encoder->fmt_in.video.i_frame_rate = p_sys->f_fps * 1000;
1488         id->p_encoder->fmt_in.video.i_frame_rate_base = 1000;
1489     }
1490
1491     id->f_dst.video.i_frame_rate = id->p_encoder->fmt_in.video.i_frame_rate;
1492     id->f_dst.video.i_frame_rate_base =
1493         id->p_encoder->fmt_in.video.i_frame_rate_base;
1494
1495     /* Check whether a particular aspect ratio was requested */
1496     if( id->f_src.video.i_aspect )
1497     {
1498         id->p_encoder->fmt_in.video.i_aspect = id->f_src.video.i_aspect;
1499         id->f_dst.video.i_aspect = id->f_src.video.i_aspect;
1500     }
1501
1502     id->p_encoder->fmt_out = id->p_encoder->fmt_in;
1503     id->p_encoder->fmt_out.i_codec = id->f_dst.i_codec;
1504     id->p_encoder->fmt_out.i_bitrate = id->f_dst.i_bitrate;
1505
1506     id->p_encoder->i_threads = p_sys->i_threads;
1507
1508     id->p_ff_pic         = avcodec_alloc_frame();
1509     id->p_ff_pic_tmp0    = NULL;
1510     id->p_ff_pic_tmp1    = NULL;
1511     id->p_ff_pic_tmp2    = NULL;
1512     id->p_ff_pic_tmp3    = NULL;
1513     id->p_vresample      = NULL;
1514
1515     id->p_encoder->p_cfg = p_sys->p_video_cfg;
1516
1517     /* Attach object to parent so object variables inheritance works */
1518     vlc_object_attach( id->p_encoder, p_stream );
1519
1520     id->p_encoder->p_module =
1521         module_Need( id->p_encoder, "encoder", p_sys->psz_venc, VLC_TRUE );
1522
1523     if( !id->p_encoder->p_module )
1524     {
1525         vlc_object_detach( id->p_encoder );
1526         vlc_object_destroy( id->p_encoder );
1527         av_free( id->ff_dec_c );
1528         msg_Err( p_stream, "cannot find encoder" );
1529         return VLC_EGENERIC;
1530     }
1531
1532     /* Close the encoder.
1533      * We'll open it only when we have the first frame */
1534     module_Unneed( id->p_encoder, id->p_encoder->p_module );
1535     id->p_encoder->p_module = NULL;
1536
1537     id->b_enc_inited = VLC_FALSE;
1538
1539     if ( p_sys->i_threads >= 1 )
1540     {
1541         p_sys->id_video = id;
1542         vlc_mutex_init( p_stream, &p_sys->lock_out );
1543         vlc_cond_init( p_stream, &p_sys->cond );
1544         memset( p_sys->pp_pics, 0, sizeof(p_sys->pp_pics) );
1545         p_sys->i_first_pic = 0;
1546         p_sys->i_last_pic = 0;
1547         p_sys->p_buffers = NULL;
1548         p_sys->b_die = p_sys->b_error = 0;
1549         if( vlc_thread_create( p_sys, "encoder", EncoderThread,
1550                                VLC_THREAD_PRIORITY_VIDEO, VLC_FALSE ) )
1551         {
1552             vlc_object_detach( id->p_encoder );
1553             vlc_object_destroy( id->p_encoder );
1554             av_free( id->ff_dec_c );
1555             msg_Err( p_stream, "cannot spawn encoder thread" );
1556             return VLC_EGENERIC;
1557         }
1558     }
1559
1560     return VLC_SUCCESS;
1561 }
1562
1563 static void transcode_video_ffmpeg_close ( sout_stream_t *p_stream,
1564                                            sout_stream_id_t *id )
1565 {
1566     if ( p_stream->p_sys->i_threads >= 1 )
1567     {
1568        vlc_mutex_lock( &p_stream->p_sys->lock_out );
1569        p_stream->p_sys->b_die = 1;
1570        vlc_cond_signal( &p_stream->p_sys->cond );
1571        vlc_mutex_unlock( &p_stream->p_sys->lock_out );
1572        vlc_thread_join( p_stream->p_sys );
1573        vlc_mutex_destroy( &p_stream->p_sys->lock_out );
1574        vlc_cond_destroy( &p_stream->p_sys->cond );
1575     }
1576
1577     /* Close decoder */
1578     if( id->ff_dec ) avcodec_close( id->ff_dec_c );
1579     av_free( id->ff_dec_c );
1580
1581     /* Close encoder */
1582     if( id->p_encoder->p_module )
1583         module_Unneed( id->p_encoder, id->p_encoder->p_module );
1584     vlc_object_detach( id->p_encoder );
1585     vlc_object_destroy( id->p_encoder );
1586
1587     /* Misc cleanup */
1588     if( id->p_ff_pic)
1589     {
1590         free( id->p_ff_pic );
1591     }
1592
1593     if( id->p_ff_pic_tmp0 )
1594     {
1595         free( id->p_ff_pic_tmp0->data[0] );
1596         free( id->p_ff_pic_tmp0 );
1597     }
1598     if( id->p_ff_pic_tmp1 )
1599     {
1600         free( id->p_ff_pic_tmp1->data[0] );
1601         free( id->p_ff_pic_tmp1 );
1602     }
1603     if( id->p_ff_pic_tmp2 )
1604     {
1605         free( id->p_ff_pic_tmp2->data[0] );
1606         free( id->p_ff_pic_tmp2 );
1607     }
1608     if( id->p_ff_pic_tmp3 )
1609     {
1610         free( id->p_ff_pic_tmp3->data[0] );
1611         free( id->p_ff_pic_tmp3 );
1612     }
1613     if( id->p_vresample )
1614     {
1615         img_resample_close( id->p_vresample );
1616     }
1617 }
1618
1619 static int transcode_video_ffmpeg_process( sout_stream_t *p_stream,
1620                sout_stream_id_t *id, block_t *in, block_t **out )
1621 {
1622     sout_stream_sys_t *p_sys = p_stream->p_sys;
1623     int i_used, b_gotpicture, i_duplicate = 1;
1624     AVFrame *frame;
1625     mtime_t i_pts;
1626
1627     int i_data;
1628     uint8_t *p_data;
1629
1630     *out = NULL;
1631
1632     i_data = in->i_buffer;
1633     p_data = in->p_buffer;
1634
1635     for( ;; )
1636     {
1637         block_t *p_block;
1638         picture_t * p_pic;
1639         int i_plane;
1640         subpicture_t *p_subpic = 0;
1641
1642         /* decode frame */
1643         frame = id->p_ff_pic;
1644         p_sys->i_input_pts = in->i_pts;
1645         p_sys->i_input_dts = in->i_dts;
1646         if( id->ff_dec )
1647         {
1648             i_used = avcodec_decode_video( id->ff_dec_c, frame,
1649                                            &b_gotpicture,
1650                                            p_data, i_data );
1651         }
1652         else
1653         {
1654             /* raw video */
1655             avpicture_fill( (AVPicture*)frame, p_data,
1656                             id->ff_dec_c->pix_fmt,
1657                             id->ff_dec_c->width, id->ff_dec_c->height );
1658             i_used = i_data;
1659             b_gotpicture = 1;
1660
1661             /* Set PTS */
1662             frame->pts = p_sys->i_input_pts ? p_sys->i_input_pts :
1663                          AV_NOPTS_VALUE;
1664
1665             frame->pict_type = FF_I_TYPE;
1666         }
1667
1668         if( i_used < 0 )
1669         {
1670             msg_Warn( p_stream, "error");
1671             return VLC_EGENERIC;
1672         }
1673         i_data -= i_used;
1674         p_data += i_used;
1675
1676         if( !b_gotpicture )
1677         {
1678             return VLC_SUCCESS;
1679         }
1680
1681         /* Get the pts of the decoded frame if any, otherwise keep the
1682          * interpolated one */
1683         if( frame->pts != AV_NOPTS_VALUE )
1684         {
1685             p_sys->i_output_pts = frame->pts;
1686         }
1687         i_pts = p_sys->i_output_pts;
1688
1689         /* Sanity check (seems to be needed for some streams ) */
1690         if( frame->pict_type == FF_B_TYPE )
1691         {
1692             p_sys->b_input_has_b_frames = VLC_TRUE;
1693         }
1694
1695         if( p_sys->b_audio_sync )
1696         {
1697             mtime_t i_video_drift;
1698
1699             i_pts = date_Get( &id->interpolated_pts ) + 1;
1700             i_video_drift = p_sys->i_output_pts - i_pts;
1701             i_duplicate = 1;
1702
1703             if( i_video_drift < p_sys->i_master_drift - 50000 )
1704             {
1705                 msg_Dbg( p_stream, "dropping frame (%i)",
1706                          (int)(i_video_drift - p_sys->i_master_drift) );
1707                 return VLC_EGENERIC;
1708             }
1709             else if( i_video_drift > p_sys->i_master_drift + 50000 )
1710             {
1711                 msg_Dbg( p_stream, "adding frame (%i)",
1712                          (int)(i_video_drift - p_sys->i_master_drift) );
1713                 i_duplicate = 2;
1714             }
1715
1716             date_Increment( &id->interpolated_pts, 1 );
1717         }
1718
1719         if( !id->b_enc_inited )
1720         {
1721             /* Hack because of the copy packetizer which can fail to detect the
1722              * proper size (which forces us to wait until the 1st frame
1723              * is decoded) */
1724             int i_width = id->ff_dec_c->width - p_sys->i_crop_left -
1725                           p_sys->i_crop_right;
1726             int i_height = id->ff_dec_c->height - p_sys->i_crop_top -
1727                            p_sys->i_crop_bottom;
1728
1729             if( id->f_dst.video.i_width <= 0 && id->f_dst.video.i_height <= 0
1730                 && p_sys->f_scale )
1731             {
1732                 /* Apply the scaling */
1733                 id->f_dst.video.i_width = i_width * p_sys->f_scale;
1734                 id->f_dst.video.i_height = i_height * p_sys->f_scale;
1735             }
1736             else if( id->f_dst.video.i_width > 0 &&
1737                      id->f_dst.video.i_height <= 0 )
1738             {
1739                 id->f_dst.video.i_height =
1740                     id->f_dst.video.i_width / (double)i_width * i_height;
1741             }
1742             else if( id->f_dst.video.i_width <= 0 &&
1743                      id->f_dst.video.i_height > 0 )
1744             {
1745                 id->f_dst.video.i_width =
1746                     id->f_dst.video.i_height / (double)i_height * i_width;
1747             }
1748
1749             id->p_encoder->fmt_in.video.i_width = id->f_dst.video.i_width;
1750             id->p_encoder->fmt_in.video.i_height = id->f_dst.video.i_height;
1751             id->p_encoder->fmt_out = id->f_dst;
1752
1753             id->p_encoder->p_module =
1754                 module_Need( id->p_encoder, "encoder",
1755                              p_sys->psz_venc, VLC_TRUE );
1756             if( !id->p_encoder->p_module )
1757             {
1758                 vlc_object_destroy( id->p_encoder );
1759                 msg_Err( p_stream, "cannot find encoder" );
1760                 id->b_transcode = VLC_FALSE;
1761                 return VLC_EGENERIC;
1762             }
1763
1764             id->f_dst = id->p_encoder->fmt_out;
1765
1766             /* Hack for mp2v/mp1v transcoding support */
1767             if( id->f_dst.i_codec == VLC_FOURCC( 'm','p','1','v' ) ||
1768                 id->f_dst.i_codec == VLC_FOURCC( 'm','p','2','v' ) )
1769             {
1770                 id->f_dst.i_codec = VLC_FOURCC( 'm','p','g','v' );
1771             }
1772
1773             if( !( id->id =
1774                      p_stream->p_sys->p_out->pf_add( p_stream->p_sys->p_out,
1775                                                      &id->f_dst ) ) )
1776             {
1777                 msg_Err( p_stream, "cannot add this stream" );
1778                 transcode_video_ffmpeg_close( p_stream, id );
1779                 id->b_transcode = VLC_FALSE;
1780                 return VLC_EGENERIC;
1781             }
1782
1783             if( id->p_encoder->pf_header )
1784             {
1785                 block_t *p_block_tmp;
1786
1787                 p_block = id->p_encoder->pf_header( id->p_encoder );
1788                 p_block_tmp = p_block;
1789                 while( p_block_tmp )
1790                 {
1791                     p_block_tmp->i_dts = p_block_tmp->i_pts = in->i_dts;
1792                     p_block_tmp = p_block_tmp->p_next;
1793                 }
1794                 block_ChainAppend( out, p_block );
1795             }
1796
1797             id->i_inter_pixfmt =
1798                 get_ff_chroma( id->p_encoder->fmt_in.i_codec );
1799
1800             id->b_enc_inited = VLC_TRUE;
1801         }
1802
1803         /* deinterlace */
1804         if( p_stream->p_sys->b_deinterlace )
1805         {
1806             if( id->p_ff_pic_tmp0 == NULL )
1807             {
1808                 int     i_size;
1809                 uint8_t *buf;
1810                 id->p_ff_pic_tmp0 = avcodec_alloc_frame();
1811                 i_size = avpicture_get_size( id->ff_dec_c->pix_fmt,
1812                                              id->ff_dec_c->width,
1813                                              id->ff_dec_c->height );
1814
1815                 buf = malloc( i_size );
1816
1817                 avpicture_fill( (AVPicture*)id->p_ff_pic_tmp0, buf,
1818                                 id->i_inter_pixfmt,
1819                                 id->ff_dec_c->width, id->ff_dec_c->height );
1820             }
1821
1822             avpicture_deinterlace( (AVPicture*)id->p_ff_pic_tmp0,
1823                                    (AVPicture*)frame, id->ff_dec_c->pix_fmt,
1824                                    id->ff_dec_c->width, id->ff_dec_c->height );
1825
1826 #if LIBAVCODEC_BUILD >= 4685
1827             id->p_ff_pic_tmp0->interlaced_frame = 0;
1828 #endif
1829             id->p_ff_pic_tmp0->repeat_pict = frame->repeat_pict;
1830             frame = id->p_ff_pic_tmp0;
1831         }
1832
1833         /* convert pix format */
1834         if( id->ff_dec_c->pix_fmt != id->i_inter_pixfmt )
1835         {
1836             if( id->p_ff_pic_tmp1 == NULL )
1837             {
1838                 int     i_size;
1839                 uint8_t *buf;
1840                 id->p_ff_pic_tmp1 = avcodec_alloc_frame();
1841                 i_size = avpicture_get_size( id->i_inter_pixfmt,
1842                                              id->ff_dec_c->width,
1843                                              id->ff_dec_c->height );
1844
1845                 buf = malloc( i_size );
1846
1847                 avpicture_fill( (AVPicture*)id->p_ff_pic_tmp1, buf,
1848                                 id->i_inter_pixfmt,
1849                                 id->ff_dec_c->width, id->ff_dec_c->height );
1850             }
1851
1852             img_convert( (AVPicture*)id->p_ff_pic_tmp1, id->i_inter_pixfmt,
1853                          (AVPicture*)frame, id->ff_dec_c->pix_fmt,
1854                          id->ff_dec_c->width, id->ff_dec_c->height );
1855
1856             id->p_ff_pic_tmp1->repeat_pict = frame->repeat_pict;
1857 #if LIBAVCODEC_BUILD >= 4685
1858             id->p_ff_pic_tmp1->interlaced_frame = frame->interlaced_frame;
1859             id->p_ff_pic_tmp1->top_field_first = frame->top_field_first;
1860 #endif
1861             frame = id->p_ff_pic_tmp1;
1862         }
1863
1864         /* convert size and crop */
1865         if( id->ff_dec_c->width  != id->f_dst.video.i_width ||
1866             id->ff_dec_c->height != id->f_dst.video.i_height ||
1867             p_sys->i_crop_top > 0 || p_sys->i_crop_bottom > 0 ||
1868             p_sys->i_crop_left > 0 || p_sys->i_crop_right > 0 )
1869         {
1870             if( id->p_ff_pic_tmp2 == NULL )
1871             {
1872                 int     i_size;
1873                 uint8_t *buf;
1874                 id->p_ff_pic_tmp2 = avcodec_alloc_frame();
1875                 i_size = avpicture_get_size( id->i_inter_pixfmt,
1876                                              id->f_dst.video.i_width,
1877                                              id->f_dst.video.i_height );
1878
1879                 buf = malloc( i_size );
1880
1881                 avpicture_fill( (AVPicture*)id->p_ff_pic_tmp2, buf,
1882                                 id->i_inter_pixfmt,
1883                                 id->f_dst.video.i_width,
1884                                 id->f_dst.video.i_height );
1885
1886                 id->p_vresample =
1887                     img_resample_full_init( id->f_dst.video.i_width,
1888                                             id->f_dst.video.i_height,
1889                                             id->ff_dec_c->width,
1890                                             id->ff_dec_c->height,
1891                                             p_stream->p_sys->i_crop_top,
1892                                             p_stream->p_sys->i_crop_bottom,
1893                                             p_stream->p_sys->i_crop_left,
1894                                             p_stream->p_sys->i_crop_right
1895 #if LIBAVCODEC_BUILD >= 4708
1896                                             ,0, 0, 0, 0 );
1897 #else
1898                                           );
1899 #endif
1900             }
1901
1902             img_resample( id->p_vresample, (AVPicture*)id->p_ff_pic_tmp2,
1903                           (AVPicture*)frame );
1904
1905             id->p_ff_pic_tmp2->repeat_pict = frame->repeat_pict;
1906 #if LIBAVCODEC_BUILD >= 4685
1907             id->p_ff_pic_tmp2->interlaced_frame = frame->interlaced_frame;
1908             id->p_ff_pic_tmp2->top_field_first = frame->top_field_first;
1909 #endif
1910             frame = id->p_ff_pic_tmp2;
1911         }
1912
1913         /* Encoding */
1914         p_pic = malloc(sizeof(picture_t));
1915         vout_InitPicture( VLC_OBJECT(p_stream), p_pic,
1916                           id->p_encoder->fmt_in.i_codec,
1917                           id->f_dst.video.i_width, id->f_dst.video.i_height,
1918                           id->f_dst.video.i_width * VOUT_ASPECT_FACTOR /
1919                           id->f_dst.video.i_height );
1920
1921         /* Check if we have a subpicture to overlay */
1922         if( p_sys->p_filter_blend )
1923         {
1924             p_subpic = transcode_spu_get( p_stream, id, p_sys->i_output_pts );
1925
1926             if( p_subpic && frame != id->p_ff_pic_tmp0 &&
1927                 frame != id->p_ff_pic_tmp1 && frame != id->p_ff_pic_tmp2 )
1928             {
1929                 if( id->p_ff_pic_tmp3 == NULL )
1930                 {
1931                     uint8_t *buf = malloc( frame->linesize[0] *
1932                                            p_pic->p[0].i_lines * 3 );
1933                     id->p_ff_pic_tmp3 = avcodec_alloc_frame();
1934                     *id->p_ff_pic_tmp3 = *frame;
1935                     id->p_ff_pic_tmp3->data[0] = buf;
1936                     id->p_ff_pic_tmp3->data[1] = id->p_ff_pic_tmp3->data[0] +
1937                         frame->linesize[0] * p_pic->p[0].i_lines;
1938                     id->p_ff_pic_tmp3->data[2] = id->p_ff_pic_tmp3->data[1] +
1939                         frame->linesize[1] * p_pic->p[1].i_lines;
1940                 }
1941
1942                 for( i_plane = 0; i_plane < p_pic->i_planes; i_plane++ )
1943                 {
1944                     p_stream->p_vlc->pf_memcpy(
1945                         id->p_ff_pic_tmp3->data[i_plane],
1946                         frame->data[i_plane],
1947                         p_pic->p[i_plane].i_lines * frame->linesize[i_plane] );
1948                 }
1949
1950                 id->p_ff_pic_tmp3->repeat_pict = frame->repeat_pict;
1951 #if LIBAVCODEC_BUILD >= 4685
1952                 id->p_ff_pic_tmp3->interlaced_frame = frame->interlaced_frame;
1953                 id->p_ff_pic_tmp3->top_field_first = frame->top_field_first;
1954 #endif
1955                 frame = id->p_ff_pic_tmp3;
1956             }
1957         }
1958
1959         for( i_plane = 0; i_plane < p_pic->i_planes; i_plane++ )
1960         {
1961             p_pic->p[i_plane].i_pitch = frame->linesize[i_plane];
1962             if ( p_sys->i_threads >= 1 )
1963             {
1964                 p_pic->p[i_plane].p_pixels = malloc(p_pic->p[i_plane].i_lines *
1965                                                     p_pic->p[i_plane].i_pitch);
1966                 p_stream->p_vlc->pf_memcpy( p_pic->p[i_plane].p_pixels,
1967                     frame->data[i_plane], p_pic->p[i_plane].i_lines *
1968                      p_pic->p[i_plane].i_pitch );
1969             }
1970             else
1971             {
1972                 p_pic->p[i_plane].p_pixels = frame->data[i_plane];
1973             }
1974         }
1975
1976         /* Set the pts of the frame being encoded */
1977         p_pic->date = i_pts;
1978
1979         p_pic->i_nb_fields = frame->repeat_pict;
1980 #if LIBAVCODEC_BUILD >= 4685
1981         p_pic->b_progressive = !frame->interlaced_frame;
1982         p_pic->b_top_field_first = frame->top_field_first;
1983 #endif
1984
1985         /* Interpolate the next PTS
1986          * (needed by the mpeg video packetizer which can send pts <= 0 ) */
1987         if( id->ff_dec_c && id->ff_dec_c->frame_rate > 0 )
1988         {
1989             p_sys->i_output_pts += I64C(1000000) * (2 + frame->repeat_pict) *
1990               id->ff_dec_c->frame_rate_base / (2 * id->ff_dec_c->frame_rate);
1991         }
1992
1993         /* Overlay subpicture */
1994         if( p_subpic )
1995         {
1996             int i_width, i_height;
1997
1998             p_sys->p_filter_blend->fmt_out = id->p_encoder->fmt_in;
1999             p_sys->p_filter_blend->fmt_out.video.i_visible_width =
2000                 p_sys->p_filter_blend->fmt_out.video.i_width;
2001             p_sys->p_filter_blend->fmt_out.video.i_visible_height =
2002                 p_sys->p_filter_blend->fmt_out.video.i_height;
2003             p_sys->p_filter_blend->fmt_out.video.i_chroma =
2004                 VLC_FOURCC('I','4','2','0');
2005
2006             i_width = id->p_encoder->fmt_in.video.i_width;
2007             i_height = id->p_encoder->fmt_in.video.i_height;
2008
2009             while( p_subpic != NULL )
2010             {
2011                 subpicture_region_t *p_region = p_subpic->p_region;
2012
2013                 while( p_region && p_sys->p_filter_blend &&
2014                        p_sys->p_filter_blend->pf_video_blend )
2015                 {
2016                     int i_x_offset = p_region->i_x + p_subpic->i_x;
2017                     int i_y_offset = p_region->i_y + p_subpic->i_y;
2018
2019                     if( p_subpic->i_flags & OSD_ALIGN_BOTTOM )
2020                     {
2021                         i_y_offset = i_height - p_region->fmt.i_height -
2022                             p_subpic->i_y;
2023                     }
2024                     else if ( !(p_subpic->i_flags & OSD_ALIGN_TOP) )
2025                     {
2026                         i_y_offset = i_height / 2 - p_region->fmt.i_height / 2;
2027                     }
2028
2029                     if( p_subpic->i_flags & OSD_ALIGN_RIGHT )
2030                     {
2031                         i_x_offset = i_width - p_region->fmt.i_width -
2032                             p_subpic->i_x;
2033                     }
2034                     else if ( !(p_subpic->i_flags & OSD_ALIGN_LEFT) )
2035                     {
2036                         i_x_offset = i_width / 2 - p_region->fmt.i_width / 2;
2037                     }
2038
2039                     if( p_subpic->b_absolute )
2040                     {
2041                         i_x_offset = p_region->i_x + p_subpic->i_x;
2042                         i_y_offset = p_region->i_y + p_subpic->i_y;
2043                     }
2044
2045                     p_sys->p_filter_blend->fmt_in.video = p_region->fmt;
2046
2047                     p_sys->p_filter_blend->pf_video_blend(
2048                          p_sys->p_filter_blend, p_pic, p_pic,
2049                          &p_region->picture, i_x_offset, i_y_offset );
2050
2051                     p_region = p_region->p_next;
2052                 }
2053
2054                 p_subpic = p_subpic->p_next;
2055             }
2056         }
2057
2058         if ( p_sys->i_threads >= 1 )
2059         {
2060             vlc_mutex_lock( &p_sys->lock_out );
2061             p_sys->pp_pics[p_sys->i_last_pic++] = p_pic;
2062             p_sys->i_last_pic %= PICTURE_RING_SIZE;
2063             *out = p_sys->p_buffers;
2064             p_sys->p_buffers = NULL;
2065             vlc_cond_signal( &p_sys->cond );
2066             vlc_mutex_unlock( &p_sys->lock_out );
2067         }
2068         else
2069         {
2070             block_t *p_block;
2071             p_block = id->p_encoder->pf_encode_video( id->p_encoder, p_pic );
2072             block_ChainAppend( out, p_block );
2073
2074             if( p_sys->b_audio_sync && i_duplicate > 1 )
2075             {
2076                 i_pts = date_Get( &id->interpolated_pts ) + 1;
2077                 date_Increment( &id->interpolated_pts, 1 );
2078                 p_pic->date = i_pts;
2079                 p_block = id->p_encoder->pf_encode_video( id->p_encoder, p_pic );
2080                 block_ChainAppend( out, p_block );
2081             }
2082
2083             free( p_pic );
2084         }
2085
2086         if( i_data <= 0 )
2087         {
2088             return VLC_SUCCESS;
2089         }
2090     }
2091
2092     return VLC_SUCCESS;
2093 }
2094
2095 static int EncoderThread( sout_stream_sys_t * p_sys )
2096 {
2097     sout_stream_id_t * id = p_sys->id_video;
2098     picture_t * p_pic;
2099     int i_plane;
2100
2101     while ( !p_sys->b_die && !p_sys->b_error )
2102     {
2103         block_t *p_block;
2104
2105         vlc_mutex_lock( &p_sys->lock_out );
2106         while ( p_sys->i_last_pic == p_sys->i_first_pic )
2107         {
2108             vlc_cond_wait( &p_sys->cond, &p_sys->lock_out );
2109             if ( p_sys->b_die || p_sys->b_error )
2110                 break;
2111         }
2112         if ( p_sys->b_die || p_sys->b_error )
2113         {
2114             vlc_mutex_unlock( &p_sys->lock_out );
2115             break;
2116         }
2117
2118         p_pic = p_sys->pp_pics[p_sys->i_first_pic++];
2119         p_sys->i_first_pic %= PICTURE_RING_SIZE;
2120         vlc_mutex_unlock( &p_sys->lock_out );
2121
2122         p_block = id->p_encoder->pf_encode_video( id->p_encoder, p_pic );
2123         vlc_mutex_lock( &p_sys->lock_out );
2124         block_ChainAppend( &p_sys->p_buffers, p_block );
2125         vlc_mutex_unlock( &p_sys->lock_out );
2126
2127         for( i_plane = 0; i_plane < p_pic->i_planes; i_plane++ )
2128         {
2129             free( p_pic->p[i_plane].p_pixels );
2130         }
2131         free( p_pic );
2132     }
2133
2134     while ( p_sys->i_last_pic != p_sys->i_first_pic )
2135     {
2136         p_pic = p_sys->pp_pics[p_sys->i_first_pic++];
2137         p_sys->i_first_pic %= PICTURE_RING_SIZE;
2138
2139         for( i_plane = 0; i_plane < p_pic->i_planes; i_plane++ )
2140         {
2141             free( p_pic->p[i_plane].p_pixels );
2142         }
2143         free( p_pic );
2144     }
2145
2146     block_ChainRelease( p_sys->p_buffers );
2147
2148     return 0;
2149 }
2150
2151 /*****************************************************************************
2152  * transcode_video_ffmpeg_getframebuf:
2153  *
2154  * Callback used by ffmpeg to get a frame buffer.
2155  * We use it to get the right PTS for each decoded picture.
2156  *****************************************************************************/
2157 static int transcode_video_ffmpeg_getframebuf(struct AVCodecContext *p_context,
2158                                               AVFrame *p_frame)
2159 {
2160     sout_stream_sys_t *p_sys = (sout_stream_sys_t *)p_context->opaque;
2161
2162     /* Set PTS */
2163     if( p_sys->i_input_pts )
2164     {
2165         p_frame->pts = p_sys->i_input_pts;
2166     }
2167     else if( p_sys->i_input_dts )
2168     {
2169         /* Some demuxers/packetizers only set the dts so let's try to find a
2170          * useful timestamp from this */
2171         if( !p_context->has_b_frames || !p_sys->b_input_has_b_frames ||
2172             !p_frame->reference || !p_sys->i_output_pts )
2173         {
2174             p_frame->pts = p_sys->i_input_dts +
2175             /* Hack: ffmpeg encoding doesn't like frames with identical pts */
2176                 (p_sys->i_output_pts ? 0 : 50000);
2177         }
2178         else p_frame->pts = AV_NOPTS_VALUE;
2179     }
2180     else p_frame->pts = AV_NOPTS_VALUE;
2181
2182     if( p_sys->i_output_pts ) /* make sure 1st frame has a pts > 0 */
2183     {
2184         p_sys->i_input_pts = 0;
2185         p_sys->i_input_dts = 0;
2186     }
2187
2188     return avcodec_default_get_buffer( p_context, p_frame );
2189 }
2190
2191 /*
2192  * SPU
2193  */
2194 static subpicture_t *spu_new_buffer( decoder_t * );
2195 static void spu_del_buffer( decoder_t *, subpicture_t * );
2196
2197 static int transcode_spu_new( sout_stream_t *p_stream, sout_stream_id_t *id )
2198 {
2199     sout_stream_sys_t *p_sys = p_stream->p_sys;
2200
2201     /* Open decoder */
2202     id->p_decoder = vlc_object_create( p_stream, VLC_OBJECT_DECODER );
2203
2204     /* Initialization of decoder format structures */
2205     id->p_decoder->fmt_in = id->f_src;
2206     id->p_decoder->pf_spu_buffer_new = spu_new_buffer;
2207     id->p_decoder->pf_spu_buffer_del = spu_del_buffer;
2208     //id->p_decoder->p_cfg = p_sys->p_spu_cfg;
2209
2210     /* Attach object to parent so object variables inheritance works */
2211     vlc_object_attach( id->p_decoder, p_stream );
2212
2213     id->p_decoder->p_module =
2214         module_Need( id->p_decoder, "decoder", "$codec", VLC_TRUE );
2215
2216     if( !id->p_decoder->p_module )
2217     {
2218         vlc_object_detach( id->p_decoder );
2219         vlc_object_destroy( id->p_decoder );
2220         msg_Err( p_stream, "cannot find decoder" );
2221         return VLC_EGENERIC;
2222     }
2223
2224     if( !p_sys->b_soverlay )
2225     {
2226         /* Open encoder */
2227         id->p_encoder = vlc_object_create( p_stream, VLC_OBJECT_ENCODER );
2228
2229         /* Initialization of encoder format structures */
2230         es_format_Init( &id->p_encoder->fmt_in,
2231                         id->f_src.i_cat, id->f_src.i_codec );
2232
2233         id->p_encoder->fmt_out = id->f_dst;
2234
2235         id->p_encoder->p_cfg = p_sys->p_spu_cfg;
2236
2237         /* Attach object to parent so object variables inheritance works */
2238         vlc_object_attach( id->p_encoder, p_stream );
2239
2240         id->p_encoder->p_module =
2241             module_Need( id->p_encoder, "encoder", p_sys->psz_senc, VLC_TRUE );
2242
2243         if( !id->p_encoder->p_module )
2244         {
2245             module_Unneed( id->p_decoder, id->p_decoder->p_module );
2246             vlc_object_detach( id->p_decoder );
2247             vlc_object_destroy( id->p_decoder );
2248
2249             vlc_object_detach( id->p_encoder );
2250             vlc_object_destroy( id->p_encoder );
2251             msg_Err( p_stream, "cannot find encoder" );
2252             return VLC_EGENERIC;
2253         }
2254
2255         id->f_dst = id->p_encoder->fmt_out;
2256     }
2257     else
2258     {
2259         p_sys->p_filter_blend =
2260             vlc_object_create( p_stream, sizeof(filter_t) );
2261         vlc_object_attach( p_sys->p_filter_blend, p_stream );
2262         p_sys->p_filter_blend->fmt_out.video.i_chroma =
2263             VLC_FOURCC('I','4','2','0');
2264         p_sys->p_filter_blend->fmt_in.video.i_chroma =
2265             VLC_FOURCC('Y','U','V','A');
2266         p_sys->p_filter_blend->p_module =
2267             module_Need( p_sys->p_filter_blend, "video blending", 0, 0 );
2268     }
2269
2270     return VLC_SUCCESS;
2271 }
2272
2273 static void transcode_spu_close( sout_stream_t *p_stream, sout_stream_id_t *id)
2274 {
2275     sout_stream_sys_t *p_sys = p_stream->p_sys;
2276     int i;
2277
2278     /* Close decoder */
2279     if( id->p_decoder->p_module )
2280         module_Unneed( id->p_decoder, id->p_decoder->p_module );
2281     vlc_object_detach( id->p_decoder );
2282     vlc_object_destroy( id->p_decoder );
2283
2284     /* Close encoder */
2285     if( id->p_encoder )
2286     {
2287         if( id->p_encoder->p_module )
2288             module_Unneed( id->p_encoder, id->p_encoder->p_module );
2289         vlc_object_detach( id->p_encoder );
2290         vlc_object_destroy( id->p_encoder );
2291     }
2292
2293     /* Free subpictures */
2294     for( i = 0; i < SUBPICTURE_RING_SIZE; i++ )
2295     {
2296         if( !p_sys->pp_subpics[i] ) continue;
2297
2298         spu_del_buffer( id->p_decoder, p_sys->pp_subpics[i] );
2299         p_sys->pp_subpics[i] = NULL;
2300     }
2301 }
2302
2303 static int transcode_spu_process( sout_stream_t *p_stream,
2304                                   sout_stream_id_t *id,
2305                                   block_t *in, block_t **out )
2306 {
2307     sout_stream_sys_t *p_sys = p_stream->p_sys;
2308     subpicture_t *p_subpic;
2309     *out = NULL;
2310
2311     p_subpic = id->p_decoder->pf_decode_sub( id->p_decoder, &in );
2312     if( p_subpic && p_sys->b_soverlay )
2313     {
2314         int i;
2315
2316         /* Find a free slot in our supictures ring buffer */
2317         for( i = 0; i < SUBPICTURE_RING_SIZE; i++ )
2318         {
2319             if( !p_sys->pp_subpics[i] )
2320             {
2321                 p_sys->pp_subpics[i] = p_subpic;
2322                 break;
2323             }
2324         }
2325         if( i == SUBPICTURE_RING_SIZE )
2326         {
2327             spu_del_buffer( id->p_decoder, p_subpic );
2328         }
2329     }
2330
2331     if(  p_subpic && !p_sys->b_soverlay )
2332     {
2333         block_t *p_block;
2334
2335         p_block = id->p_encoder->pf_encode_sub( id->p_encoder, p_subpic );
2336         spu_del_buffer( id->p_decoder, p_subpic );
2337
2338         if( p_block )
2339         {
2340             block_ChainAppend( out, p_block );
2341             return VLC_SUCCESS;
2342         }
2343     }
2344
2345     return VLC_EGENERIC;
2346 }
2347
2348 static subpicture_t *transcode_spu_get( sout_stream_t *p_stream,
2349                                         sout_stream_id_t *id,
2350                                         mtime_t display_date )
2351 {
2352     sout_stream_sys_t *p_sys = p_stream->p_sys;
2353     subpicture_t *p_subpic = 0;
2354     subpicture_t *p_ephemer = 0;
2355     subpicture_t **pp_subpic = &p_subpic;
2356     int i;
2357
2358     /* Find current subpictures and remove old ones */
2359     for( i = 0; i < SUBPICTURE_RING_SIZE; i++ )
2360     {
2361         if( !p_sys->pp_subpics[i] ) continue;
2362
2363         if( !p_sys->pp_subpics[i]->b_ephemer &&
2364             p_sys->pp_subpics[i]->i_stop < display_date )
2365         {
2366             spu_del_buffer( id->p_decoder, p_sys->pp_subpics[i] );
2367             p_sys->pp_subpics[i] = NULL;
2368             continue;
2369         }
2370
2371         if( p_sys->pp_subpics[i]->i_start > display_date ) continue;
2372
2373         if( p_sys->pp_subpics[i]->b_ephemer && !p_ephemer )
2374         {
2375             p_ephemer = p_sys->pp_subpics[i];
2376         }
2377         else if( p_sys->pp_subpics[i]->b_ephemer )
2378         {
2379             if( p_ephemer->i_start < p_sys->pp_subpics[i]->i_start )
2380             {
2381                 subpicture_t tmp;
2382                 tmp = *p_ephemer;
2383                 *p_ephemer = *p_sys->pp_subpics[i];
2384                 *p_sys->pp_subpics[i] = tmp;
2385             }
2386
2387             spu_del_buffer( id->p_decoder, p_sys->pp_subpics[i] );
2388             p_sys->pp_subpics[i] = NULL;
2389             continue;
2390         }
2391
2392         /* Add subpicture to the list */
2393         *pp_subpic = p_sys->pp_subpics[i];
2394         pp_subpic = &p_sys->pp_subpics[i]->p_next;
2395     }
2396
2397     return p_subpic;
2398 }
2399
2400 static subpicture_t *spu_new_buffer( decoder_t *p_dec )
2401 {
2402     subpicture_t *p_subpic = (subpicture_t *)malloc(sizeof(subpicture_t));
2403     memset( p_subpic, 0, sizeof(subpicture_t) );
2404     p_subpic->b_absolute = VLC_TRUE;
2405
2406     p_subpic->pf_create_region = __spu_CreateRegion;
2407     p_subpic->pf_destroy_region = __spu_DestroyRegion;
2408
2409     return p_subpic;
2410 }
2411
2412 static void spu_del_buffer( decoder_t *p_dec, subpicture_t *p_subpic )
2413 {
2414     while( p_subpic->p_region )
2415     {
2416         subpicture_region_t *p_region = p_subpic->p_region;
2417         p_subpic->p_region = p_region->p_next;
2418         p_subpic->pf_destroy_region( VLC_OBJECT(p_dec), p_region );
2419     }
2420
2421     free( p_subpic );
2422 }