]> git.sesse.net Git - vlc/blob - modules/stream_out/switcher.c
Merge branch 1.0-bugfix
[vlc] / modules / stream_out / switcher.c
1 /*****************************************************************************
2  * switcher.c: MPEG2 video switcher module
3  *****************************************************************************
4  * Copyright (C) 2004 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Christophe Massiot <massiot@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <math.h>
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_sout.h>
36 #include <vlc_avcodec.h>
37
38 #include <vlc_block.h>
39
40 #include <vlc_charset.h>
41 #include <vlc_network.h>
42
43 #define HAVE_MMX
44 #ifdef HAVE_LIBAVCODEC_AVCODEC_H
45 #   include <libavcodec/avcodec.h>
46 #elif defined(HAVE_FFMPEG_AVCODEC_H)
47 #   include <ffmpeg/avcodec.h>
48 #else
49 #   include <avcodec.h>
50 #endif
51
52 #ifdef HAVE_POSTPROC_POSTPROCESS_H
53 #   include <postproc/postprocess.h>
54 #else
55 #   include <libpostproc/postprocess.h>
56 #endif
57
58 #define SOUT_CFG_PREFIX "sout-switcher-"
59 #define MAX_PICTURES 10
60 #define MAX_AUDIO 30
61 #define MAX_THRESHOLD 99999999
62
63 /*****************************************************************************
64  * Local prototypes
65  *****************************************************************************/
66 static int      Open    ( vlc_object_t * );
67 static void     Close   ( vlc_object_t * );
68
69 static sout_stream_id_t *Add( sout_stream_t *, es_format_t * );
70 static int Del( sout_stream_t *, sout_stream_id_t * );
71 static int Send( sout_stream_t *, sout_stream_id_t *, block_t * );
72
73 static mtime_t Process( sout_stream_t *p_stream, sout_stream_id_t *id,
74                         mtime_t i_max_dts );
75 static int UnpackFromFile( sout_stream_t *p_stream, const char *psz_file,
76                            int i_width, int i_height,
77                            picture_t *p_pic );
78 static void NetCommand( sout_stream_t *p_stream );
79 static mtime_t VideoCommand( sout_stream_t *p_stream, sout_stream_id_t *id );
80 static block_t *VideoGetBuffer( sout_stream_t *p_stream, sout_stream_id_t *id,
81                                 block_t *p_buffer );
82 static block_t *AudioGetBuffer( sout_stream_t *p_stream, sout_stream_id_t *id,
83                                 block_t *p_buffer );
84
85 /*****************************************************************************
86  * Module descriptor
87  *****************************************************************************/
88 #define FILES_TEXT N_("Files")
89 #define FILES_LONGTEXT N_( \
90     "Full paths of the files separated by colons." )
91 #define SIZES_TEXT N_("Sizes")
92 #define SIZES_LONGTEXT N_( \
93     "List of sizes separated by colons (720x576:480x576)." )
94 #define RATIO_TEXT N_("Aspect ratio")
95 #define RATIO_LONGTEXT N_( \
96     "Aspect ratio (4:3, 16:9)." )
97 #define PORT_TEXT N_("Command UDP port")
98 #define PORT_LONGTEXT N_( \
99     "UDP port to listen to for commands." )
100 #define COMMAND_TEXT N_("Command")
101 #define COMMAND_LONGTEXT N_( \
102     "Initial command to execute." )
103 #define GOP_TEXT N_("GOP size")
104 #define GOP_LONGTEXT N_( \
105     "Number of P frames between two I frames." )
106 #define QSCALE_TEXT N_("Quantizer scale")
107 #define QSCALE_LONGTEXT N_( \
108     "Fixed quantizer scale to use." )
109 #define AUDIO_TEXT N_("Mute audio")
110 #define AUDIO_LONGTEXT N_( \
111     "Mute audio when command is not 0." )
112
113 vlc_module_begin ()
114     set_description( N_("MPEG2 video switcher stream output") )
115     set_capability( "sout stream", 50 )
116     add_shortcut( "switcher" )
117     set_callbacks( Open, Close )
118
119     add_string( SOUT_CFG_PREFIX "files", "", NULL, FILES_TEXT,
120                 FILES_LONGTEXT, false )
121     add_string( SOUT_CFG_PREFIX "sizes", "", NULL, SIZES_TEXT,
122                 SIZES_LONGTEXT, false )
123     add_string( SOUT_CFG_PREFIX "aspect-ratio", "4:3", NULL, RATIO_TEXT,
124                 RATIO_LONGTEXT, false )
125     add_integer( SOUT_CFG_PREFIX "port", 5001, NULL,
126                  PORT_TEXT, PORT_LONGTEXT, true )
127     add_integer( SOUT_CFG_PREFIX "command", 0, NULL,
128                  COMMAND_TEXT, COMMAND_LONGTEXT, true )
129     add_integer( SOUT_CFG_PREFIX "gop", 8, NULL,
130                  GOP_TEXT, GOP_LONGTEXT, true )
131     add_integer( SOUT_CFG_PREFIX "qscale", 5, NULL,
132                  QSCALE_TEXT, QSCALE_LONGTEXT, true )
133     add_bool( SOUT_CFG_PREFIX "mute-audio", 1, NULL,
134               AUDIO_TEXT, AUDIO_LONGTEXT, true )
135 vlc_module_end ()
136
137 static const char *const ppsz_sout_options[] = {
138     "files", "sizes", "aspect-ratio", "port", "command", "gop", "qscale",
139     "mute-audio", NULL
140 };
141
142 struct sout_stream_sys_t
143 {
144     sout_stream_t   *p_out;
145     int             i_gop;
146     int             i_qscale;
147     int             i_aspect;
148     sout_stream_id_t *pp_audio_ids[MAX_AUDIO];
149     bool      b_audio;
150
151     /* Pictures */
152     picture_t       p_pictures[MAX_PICTURES];
153     int             i_nb_pictures;
154
155     /* Command */
156     int             i_fd;
157     int             i_cmd, i_old_cmd;
158 };
159
160 struct sout_stream_id_t
161 {
162     void            *id;
163     bool      b_switcher_video;
164     bool      b_switcher_audio;
165     es_format_t     f_src;
166     block_t         *p_queued;
167
168     /* ffmpeg part */
169     AVCodec         *ff_enc;
170     AVCodecContext  *ff_enc_c;
171     AVFrame         *p_frame;
172     uint8_t         *p_buffer_out;
173     int             i_nb_pred;
174     int16_t         *p_samples;
175 };
176
177 /*****************************************************************************
178  * Open:
179  *****************************************************************************/
180 static int Open( vlc_object_t *p_this )
181 {
182     sout_stream_t     *p_stream = (sout_stream_t*)p_this;
183     sout_stream_sys_t *p_sys;
184     vlc_value_t       val;
185     char              *psz_files, *psz_sizes;
186     int               i_height = 0, i_width = 0;
187
188     p_sys = calloc( 1, sizeof(sout_stream_sys_t) );
189     if( !p_sys )
190         return VLC_ENOMEM;
191
192     p_sys->p_out = sout_StreamNew( p_stream->p_sout, p_stream->psz_next );
193     if( !p_sys->p_out )
194     {
195         msg_Err( p_stream, "cannot create chain" );
196         free( p_sys );
197         return VLC_EGENERIC;
198     }
199
200     config_ChainParse( p_stream, SOUT_CFG_PREFIX, ppsz_sout_options,
201                    p_stream->p_cfg );
202
203     var_Get( p_stream, SOUT_CFG_PREFIX "files", &val );
204     psz_files = val.psz_string;
205     var_Get( p_stream, SOUT_CFG_PREFIX "sizes", &val );
206     psz_sizes = val.psz_string;
207
208     p_sys->i_nb_pictures = 0;
209     while ( psz_files && *psz_files )
210     {
211         char * psz_file = psz_files;
212         char * psz_size = psz_sizes;
213
214         while ( *psz_files && *psz_files != ':' )
215             psz_files++;
216         if ( *psz_files == ':' )
217            *psz_files++ = '\0';
218
219         if ( *psz_sizes )
220         {
221             while ( *psz_sizes && *psz_sizes != ':' )
222                 psz_sizes++;
223             if ( *psz_sizes == ':' )
224                 *psz_sizes++ = '\0';
225             if ( sscanf( psz_size, "%dx%d", &i_width, &i_height ) != 2 )
226             {
227                 msg_Err( p_stream, "bad size %s for file %s", psz_size,
228                          psz_file );
229                 free( p_sys );
230                 return VLC_EGENERIC;
231             }
232         }
233
234         if ( UnpackFromFile( p_stream, psz_file, i_width, i_height,
235                              &p_sys->p_pictures[p_sys->i_nb_pictures] ) < 0 )
236         {
237             free( p_sys );
238             return VLC_EGENERIC;
239         }
240         p_sys->i_nb_pictures++;
241     }
242
243     var_Get( p_stream, SOUT_CFG_PREFIX "aspect-ratio", &val );
244     if ( val.psz_string )
245     {
246         char *psz_parser = strchr( val.psz_string, ':' );
247
248         if( psz_parser )
249         {
250             *psz_parser++ = '\0';
251             p_sys->i_aspect = atoi( val.psz_string ) * VOUT_ASPECT_FACTOR
252                 / atoi( psz_parser );
253         }
254         else
255         {
256             msg_Warn( p_stream, "bad aspect ratio %s", val.psz_string );
257             p_sys->i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;
258         }
259
260         free( val.psz_string );
261     }
262     else
263     {
264         p_sys->i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;
265     }
266
267     var_Get( p_stream, SOUT_CFG_PREFIX "port", &val );
268     p_sys->i_fd = net_ListenUDP1( p_stream, NULL, val.i_int );
269     if ( p_sys->i_fd < 0 )
270     {
271         free( p_sys );
272         return VLC_EGENERIC;
273     }
274
275     var_Get( p_stream, SOUT_CFG_PREFIX "command", &val );
276     p_sys->i_cmd = val.i_int;
277     p_sys->i_old_cmd = 0;
278
279     var_Get( p_stream, SOUT_CFG_PREFIX "gop", &val );
280     p_sys->i_gop = val.i_int;
281
282     var_Get( p_stream, SOUT_CFG_PREFIX "qscale", &val );
283     p_sys->i_qscale = val.i_int;
284
285     var_Get( p_stream, SOUT_CFG_PREFIX "mute-audio", &val );
286     p_sys->b_audio = val.b_bool;
287
288     p_stream->pf_add    = Add;
289     p_stream->pf_del    = Del;
290     p_stream->pf_send   = Send;
291     p_stream->p_sys     = p_sys;
292
293     avcodec_init();
294     avcodec_register_all();
295
296     return VLC_SUCCESS;
297 }
298
299 /*****************************************************************************
300  * Close:
301  *****************************************************************************/
302 static void Close( vlc_object_t * p_this )
303 {
304     sout_stream_t       *p_stream = (sout_stream_t *)p_this;
305     sout_stream_sys_t   *p_sys = p_stream->p_sys;
306
307     sout_StreamDelete( p_sys->p_out );
308
309     free( p_sys );
310 }
311
312 /*****************************************************************************
313  * Add: Add an input elementary stream
314  *****************************************************************************/
315 static sout_stream_id_t *Add( sout_stream_t *p_stream, es_format_t *p_fmt )
316 {
317     sout_stream_sys_t   *p_sys = p_stream->p_sys;
318     sout_stream_id_t    *id;
319
320     id = calloc( 1, sizeof( sout_stream_id_t ) );
321     if( !id )
322         return NULL;
323
324     if( p_fmt->i_cat == VIDEO_ES &&
325         ( p_fmt->i_codec == VLC_CODEC_MPGV ||
326           p_fmt->i_codec == VLC_FOURCC('f', 'a', 'k', 'e') ) )
327     {
328         id->b_switcher_video = true;
329         p_fmt->i_codec = VLC_CODEC_MPGV;
330         msg_Dbg( p_stream, "creating video switcher for fcc=`%4.4s' cmd:%d",
331                  (char*)&p_fmt->i_codec, p_sys->i_cmd );
332     }
333     else if ( p_fmt->i_cat == AUDIO_ES &&
334               p_fmt->i_codec == VLC_CODEC_MPGA &&
335               p_sys->b_audio )
336     {
337         int i_ff_codec = CODEC_ID_MP2;
338         int i;
339
340         id->b_switcher_audio = true;
341         msg_Dbg( p_stream, "creating audio switcher for fcc=`%4.4s' cmd:%d",
342                  (char*)&p_fmt->i_codec, p_sys->i_cmd );
343
344         /* Allocate the encoder right now. */
345         if( i_ff_codec == 0 )
346         {
347             msg_Err( p_stream, "cannot find encoder" );
348             free( id );
349             return NULL;
350         }
351
352         id->ff_enc = avcodec_find_encoder( i_ff_codec );
353         if( !id->ff_enc )
354         {
355             msg_Err( p_stream, "cannot find encoder (avcodec)" );
356             free( id );
357             return NULL;
358         }
359
360         id->ff_enc_c = avcodec_alloc_context();
361
362         /* Set CPU capabilities */
363         unsigned i_cpu = vlc_CPU();
364         id->ff_enc_c->dsp_mask = 0;
365         if( !(i_cpu & CPU_CAPABILITY_MMX) )
366         {
367             id->ff_enc_c->dsp_mask |= FF_MM_MMX;
368         }
369         if( !(i_cpu & CPU_CAPABILITY_MMXEXT) )
370         {
371             id->ff_enc_c->dsp_mask |= FF_MM_MMXEXT;
372         }
373         if( !(i_cpu & CPU_CAPABILITY_3DNOW) )
374         {
375             id->ff_enc_c->dsp_mask |= FF_MM_3DNOW;
376         }
377         if( !(i_cpu & CPU_CAPABILITY_SSE) )
378         {
379             id->ff_enc_c->dsp_mask |= FF_MM_SSE;
380             id->ff_enc_c->dsp_mask |= FF_MM_SSE2;
381         }
382
383         id->ff_enc_c->sample_rate = p_fmt->audio.i_rate;
384         id->ff_enc_c->channels    = p_fmt->audio.i_channels;
385         id->ff_enc_c->bit_rate    = p_fmt->i_bitrate;
386
387         vlc_avcodec_lock();
388         if( avcodec_open( id->ff_enc_c, id->ff_enc ) )
389         {
390             avcodec_unlock();
391             msg_Err( p_stream, "cannot open encoder" );
392             av_free( id->ff_enc_c );
393             free( id );
394             return NULL;
395         }
396         avcodec_unlock();
397
398         id->p_buffer_out = malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * 2 );
399         id->p_samples = calloc( id->ff_enc_c->frame_size * p_fmt->audio.i_channels,
400                                 sizeof(int16_t) );
401         if( !id->p_buffer_out || !id->p_samples )
402             goto error;
403
404         for( i = 0; i < MAX_AUDIO; i++ )
405         {
406             if( p_sys->pp_audio_ids[i] == NULL )
407             {
408                 p_sys->pp_audio_ids[i] = id;
409                 break;
410             }
411         }
412         if( i == MAX_AUDIO )
413         {
414             msg_Err( p_stream, "too many audio streams!" );
415             goto error;
416         }
417     }
418     else
419     {
420         msg_Dbg( p_stream, "do not know what to do when switching (fcc=`%4.4s')",
421                  (char*)&p_fmt->i_codec );
422     }
423
424     /* src format */
425     memcpy( &id->f_src, p_fmt, sizeof( es_format_t ) );
426
427     /* open output stream */
428     id->id = p_sys->p_out->pf_add( p_sys->p_out, p_fmt );
429
430     if( id->id != NULL )
431         return id;
432
433 error:
434     vlc_avcodec_lock();
435     avcodec_close( id->ff_enc_c );
436     vlc_avcodec_unlock();
437     free( id->p_samples );
438     free( id->p_buffer_out );
439     av_free( id->ff_enc_c );
440     free( id );
441     return NULL;
442 }
443
444 /*****************************************************************************
445  * Del: Del an elementary stream
446  *****************************************************************************/
447 static int Del( sout_stream_t *p_stream, sout_stream_id_t *id )
448 {
449     sout_stream_sys_t   *p_sys = p_stream->p_sys;
450
451     if ( id->b_switcher_audio )
452     {
453         int i;
454         for ( i = 0; i < MAX_AUDIO; i++ )
455         {
456             if ( p_sys->pp_audio_ids[i] == id )
457             {
458                 p_sys->pp_audio_ids[i] = NULL;
459                 break;
460             }
461         }
462     }
463
464     if ( id->ff_enc )
465     {
466         vlc_avcodec_lock();
467         avcodec_close( id->ff_enc_c );
468         vlc_avcodec_unlock();
469         av_free( id->ff_enc_c );
470         av_free( id->p_frame );
471         free( id->p_buffer_out );
472     }
473
474     if ( id->id )
475     {
476         p_sys->p_out->pf_del( p_sys->p_out, id->id );
477     }
478     free( id );
479
480     return VLC_SUCCESS;
481 }
482
483 /*****************************************************************************
484  * Send: Process an input packet
485  *****************************************************************************/
486 static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
487                  block_t *p_buffer )
488 {
489     sout_stream_sys_t *p_sys = p_stream->p_sys;
490
491     if ( !id->id )
492     {
493         block_Release( p_buffer );
494         return VLC_EGENERIC;
495     }
496
497     if ( !id->b_switcher_video && !id->b_switcher_audio )
498     {
499         return p_sys->p_out->pf_send( p_sys->p_out, id->id, p_buffer );
500     }
501
502     block_ChainAppend( &id->p_queued, p_buffer );
503
504     if ( id->b_switcher_video )
505     {
506         /* Check for commands for every video frame. */
507         NetCommand( p_stream );
508
509         while ( id->p_queued != NULL )
510         {
511             mtime_t i_dts = 0;
512             int i;
513
514             if ( p_sys->i_old_cmd != p_sys->i_cmd )
515             {
516                 i_dts = VideoCommand( p_stream, id );
517             }
518
519             i_dts = Process( p_stream, id, i_dts );
520
521             for ( i = 0; i < MAX_AUDIO; i++ )
522             {
523                 if ( p_sys->pp_audio_ids[i] != NULL )
524                     Process( p_stream, p_sys->pp_audio_ids[i], i_dts );
525             }
526         }
527     }
528
529     return VLC_SUCCESS;
530 }
531
532 /*****************************************************************************
533  * Process: Process and dispatch buffers
534  *****************************************************************************/
535 static mtime_t Process( sout_stream_t *p_stream, sout_stream_id_t *id,
536                         mtime_t i_max_dts )
537 {
538     sout_stream_sys_t *p_sys = p_stream->p_sys;
539     mtime_t i_dts = 0;
540     block_t *p_blocks = NULL;
541     block_t *p_blocks_out = NULL;
542
543     /* Find out the blocks we need. */
544     while ( id->p_queued != NULL
545              && (!i_max_dts || id->p_queued->i_dts <= i_max_dts) )
546     {
547         block_t *p_next = id->p_queued->p_next;
548         id->p_queued->p_next = NULL;
549         i_dts = id->p_queued->i_dts;
550         block_ChainAppend( &p_blocks, id->p_queued );
551         id->p_queued = p_next;
552     }
553
554     if ( p_sys->i_old_cmd == 0 )
555     {
556         /* Full forward */
557         if ( p_blocks != NULL )
558             p_sys->p_out->pf_send( p_sys->p_out, id->id, p_blocks );
559         return i_dts;
560     }
561
562     if ( p_sys->i_old_cmd == -1 )
563     {
564         /* No output at all */
565         while ( p_blocks != NULL )
566         {
567             block_t * p_next = p_blocks->p_next;
568             block_Release( p_blocks );
569             p_blocks = p_next;
570         }
571         return i_dts;
572     }
573
574     while ( p_blocks != NULL )
575     {
576         block_t * p_next = p_blocks->p_next;
577         block_t * p_out;
578
579         if ( id->b_switcher_video )
580         {
581             p_out = VideoGetBuffer( p_stream, id, p_blocks );
582         }
583         else
584         {
585             p_out = AudioGetBuffer( p_stream, id, p_blocks );
586         }
587         p_blocks = p_next;
588         if ( p_out != NULL )
589         {
590             block_ChainAppend( &p_blocks_out, p_out );
591         }
592     }
593
594     if ( p_blocks_out != NULL )
595         p_sys->p_out->pf_send( p_sys->p_out, id->id, p_blocks_out );
596     return i_dts;
597 }
598
599 /*****************************************************************************
600  * UnpackFromFile: Read a YUV picture and store it in our format
601  *****************************************************************************/
602 static int UnpackFromFile( sout_stream_t *p_stream, const char *psz_file,
603                            int i_width, int i_height,
604                            picture_t *p_pic )
605 {
606     int i, j;
607     FILE *p_file = utf8_fopen( psz_file, "r" );
608
609     if ( p_file == NULL )
610     {
611         msg_Err( p_stream, "file %s not found", psz_file );
612         return -1;
613     }
614
615     if( picture_Setup( p_pic, VLC_CODEC_I420,
616                        i_width, i_height,
617                        i_width * VOUT_ASPECT_FACTOR / i_height ) )
618     {
619         msg_Err( p_stream, "unknown chroma" );
620         return -1;
621     }
622     for ( i = 0; i < p_pic->i_planes; i++ )
623     {
624         p_pic->p[i].p_pixels = malloc( p_pic->p[i].i_lines *
625                                            p_pic->p[i].i_pitch );
626         memset( p_pic->p[i].p_pixels, 0, p_pic->p[i].i_lines *
627                     p_pic->p[i].i_pitch );
628     }
629
630     for ( i = 0; i < i_height; i++ )
631     {
632         int i_chroma;
633         uint8_t p_buffer[i_width * 2];
634         uint8_t *p_char = p_buffer;
635         uint8_t *p_y = &p_pic->p[0].p_pixels[i * p_pic->p[0].i_pitch];
636         uint8_t *p_u = &p_pic->p[1].p_pixels[i/2 * p_pic->p[1].i_pitch];
637         uint8_t *p_v = &p_pic->p[2].p_pixels[i/2 * p_pic->p[2].i_pitch];
638
639         if ( fread( p_buffer, 2, i_width, p_file ) != (size_t)i_width )
640         {
641             msg_Err( p_stream, "premature end of file %s", psz_file );
642             fclose( p_file );
643             for ( i = 0; i < p_pic->i_planes; i++ )
644             {
645                 free( p_pic->p[i].p_pixels );
646             }
647             return -1;
648         }
649
650         i_chroma = 0;
651         for ( j = 0; j < i_width; j++ )
652         {
653             uint8_t **pp_chroma = i_chroma ? &p_v : &p_u;
654             i_chroma = !i_chroma;
655             if ( i & 1 )
656                 **pp_chroma = (**pp_chroma + *p_char + 1) / 2;
657             else
658                 **pp_chroma = *p_char;
659             (*pp_chroma)++;
660             p_char++;
661             *p_y++ = *p_char++;
662         }
663     }
664
665     fclose( p_file );
666     return 0;
667 }
668
669 /*****************************************************************************
670  * NetCommand: Get a command from the network
671  *****************************************************************************/
672 static void NetCommand( sout_stream_t *p_stream )
673 {
674     sout_stream_sys_t *p_sys = p_stream->p_sys;
675     char psz_buffer[11];
676     int i_len = recv( p_sys->i_fd, psz_buffer, sizeof( psz_buffer ) - 1, 0 );
677
678     if ( i_len > 0 )
679     {
680         psz_buffer[i_len] = '\0';
681         int i_cmd = strtol( psz_buffer, NULL, 0 );
682         if ( i_cmd < -1 || i_cmd > p_sys->i_nb_pictures )
683         {
684             msg_Err( p_stream, "got a wrong command (%d)", i_cmd );
685             return;
686         }
687
688         p_sys->i_cmd = i_cmd;
689
690         msg_Dbg( p_stream, "new command: %d old:%d", p_sys->i_cmd,
691                  p_sys->i_old_cmd );
692     }
693 }
694
695 /*****************************************************************************
696  * VideoCommand: Create/Delete a video encoder
697  *****************************************************************************/
698 static mtime_t VideoCommand( sout_stream_t *p_stream, sout_stream_id_t *id )
699 {
700     sout_stream_sys_t *p_sys = p_stream->p_sys;
701
702     if ( p_sys->i_cmd == 0 && !(id->p_queued->i_flags & BLOCK_FLAG_TYPE_I) )
703     {
704         mtime_t i_dts = id->p_queued->i_dts;
705         block_t *p_block = id->p_queued->p_next;
706
707         while ( p_block != NULL )
708         {
709             if ( p_block->i_flags & BLOCK_FLAG_TYPE_I )
710                 return i_dts;
711             i_dts = p_block->i_dts;
712             p_block = p_block->p_next;
713         }
714
715         return 0;
716     }
717
718     p_sys->i_old_cmd = p_sys->i_cmd;
719
720     if ( id->ff_enc )
721     {
722         vlc_avcodec_lock();
723         avcodec_close( id->ff_enc_c );
724         vlc_avcodec_unlock();
725         av_free( id->ff_enc_c );
726         av_free( id->p_frame );
727         free( id->p_buffer_out );
728         id->ff_enc = NULL;
729     }
730
731     if ( p_sys->i_cmd > 0 )
732     {
733         /* Create a new encoder. */
734         int i_ff_codec = CODEC_ID_MPEG2VIDEO;
735         int i_aspect_num, i_aspect_den;
736
737         if( i_ff_codec == 0 )
738         {
739             msg_Err( p_stream, "cannot find encoder" );
740             return 0;
741         }
742
743         id->ff_enc = avcodec_find_encoder( i_ff_codec );
744         if( !id->ff_enc )
745         {
746             msg_Err( p_stream, "cannot find encoder (avcodec)" );
747             return 0;
748         }
749
750         id->ff_enc_c = avcodec_alloc_context();
751
752         /* Set CPU capabilities */
753         unsigned i_cpu = vlc_CPU();
754         id->ff_enc_c->dsp_mask = 0;
755         if( !(i_cpu & CPU_CAPABILITY_MMX) )
756         {
757             id->ff_enc_c->dsp_mask |= FF_MM_MMX;
758         }
759         if( !(i_cpu & CPU_CAPABILITY_MMXEXT) )
760         {
761             id->ff_enc_c->dsp_mask |= FF_MM_MMXEXT;
762         }
763         if( !(i_cpu & CPU_CAPABILITY_3DNOW) )
764         {
765             id->ff_enc_c->dsp_mask |= FF_MM_3DNOW;
766         }
767         if( !(i_cpu & CPU_CAPABILITY_SSE) )
768         {
769             id->ff_enc_c->dsp_mask |= FF_MM_SSE;
770             id->ff_enc_c->dsp_mask |= FF_MM_SSE2;
771         }
772
773         id->ff_enc_c->width = p_sys->p_pictures[p_sys->i_cmd-1].format.i_width;
774         id->ff_enc_c->height = p_sys->p_pictures[p_sys->i_cmd-1].format.i_height;
775         av_reduce( &i_aspect_num, &i_aspect_den,
776                    p_sys->i_aspect,
777                    VOUT_ASPECT_FACTOR, 1 << 30 /* something big */ );
778         av_reduce( &id->ff_enc_c->sample_aspect_ratio.num,
779                    &id->ff_enc_c->sample_aspect_ratio.den,
780                    i_aspect_num * (int64_t)id->ff_enc_c->height,
781                    i_aspect_den * (int64_t)id->ff_enc_c->width, 1 << 30 );
782
783 #if LIBAVCODEC_BUILD >= 4754
784         id->ff_enc_c->time_base.num = 1;
785         id->ff_enc_c->time_base.den = 25; /* FIXME */
786 #else
787         id->ff_enc_c->frame_rate    = 25; /* FIXME */
788         id->ff_enc_c->frame_rate_base = 1;
789 #endif
790
791         id->ff_enc_c->gop_size = 200;
792         id->ff_enc_c->max_b_frames = 0;
793
794         id->ff_enc_c->flags |= CODEC_FLAG_QSCALE
795                             | CODEC_FLAG_INPUT_PRESERVED
796                             | CODEC_FLAG_LOW_DELAY;
797
798         id->ff_enc_c->mb_decision = FF_MB_DECISION_SIMPLE;
799         id->ff_enc_c->pix_fmt = PIX_FMT_YUV420P;
800
801         avcodec_lock();
802         if( avcodec_open( id->ff_enc_c, id->ff_enc ) )
803         {
804             avcodec_unlock();
805             msg_Err( p_stream, "cannot open encoder" );
806             return 0;
807         }
808         avcodec_unlock();
809
810         id->p_buffer_out = malloc( id->ff_enc_c->width * id->ff_enc_c->height * 3 );
811         id->p_frame = avcodec_alloc_frame();
812         id->p_frame->linesize[0] = p_sys->p_pictures[p_sys->i_cmd-1].p[0].i_pitch;
813         id->p_frame->linesize[1] = p_sys->p_pictures[p_sys->i_cmd-1].p[1].i_pitch;
814         id->p_frame->linesize[2] = p_sys->p_pictures[p_sys->i_cmd-1].p[2].i_pitch;
815         id->p_frame->data[0] = p_sys->p_pictures[p_sys->i_cmd-1].p[0].p_pixels;
816         id->p_frame->data[1] = p_sys->p_pictures[p_sys->i_cmd-1].p[1].p_pixels;
817         id->p_frame->data[2] = p_sys->p_pictures[p_sys->i_cmd-1].p[2].p_pixels;
818
819         id->i_nb_pred = p_sys->i_gop;
820     }
821
822     return 0;
823 }
824
825 /*****************************************************************************
826  * VideoGetBuffer: Build an alternate video buffer
827  *****************************************************************************/
828 static block_t *VideoGetBuffer( sout_stream_t *p_stream, sout_stream_id_t *id,
829                                 block_t *p_buffer )
830 {
831     sout_stream_sys_t *p_sys = p_stream->p_sys;
832     int i_out;
833     block_t *p_out;
834
835     id->p_frame->quality = p_sys->i_qscale * powf(2.0, FF_LAMBDA_SHIFT + 7.0)
836                             / 139.0;
837     id->p_frame->interlaced_frame = 0;
838     id->p_frame->top_field_first = 1;
839     id->p_frame->pts = p_buffer->i_dts;
840
841     if ( id->i_nb_pred >= p_sys->i_gop )
842     {
843         id->p_frame->pict_type = FF_I_TYPE;
844 #if 0
845         id->p_frame->me_threshold = 0;
846         id->p_frame->mb_threshold = 0;
847 #endif
848         id->i_nb_pred = 0;
849     }
850     else
851     {
852         id->p_frame->pict_type = FF_P_TYPE;
853 #if 0
854         if ( id->p_frame->mb_type != NULL )
855         {
856             id->p_frame->me_threshold = MAX_THRESHOLD;
857             id->p_frame->mb_threshold = MAX_THRESHOLD;
858         }
859 #endif
860         id->i_nb_pred++;
861     }
862
863     i_out = avcodec_encode_video( id->ff_enc_c, id->p_buffer_out,
864                                   id->ff_enc_c->width * id->ff_enc_c->height * 3,
865                                   id->p_frame );
866
867     if ( i_out <= 0 )
868         return NULL;
869
870 #if 0
871     if ( id->p_frame->mb_type == NULL
872           && id->ff_enc_c->coded_frame->pict_type != FF_I_TYPE )
873     {
874         int mb_width = (id->ff_enc_c->width + 15) / 16;
875         int mb_height = (id->ff_enc_c->height + 15) / 16;
876         int h_chroma_shift, v_chroma_shift;
877         int i;
878
879         avcodec_get_chroma_sub_sample( id->ff_enc_c->pix_fmt, &h_chroma_shift,
880                                        &v_chroma_shift );
881
882         id->p_frame->motion_subsample_log2
883             = id->ff_enc_c->coded_frame->motion_subsample_log2;
884         id->p_frame->mb_type = malloc( ((mb_width + 1) * (mb_height + 1) + 1)
885                                     * sizeof(uint32_t) );
886         vlc_memcpy( id->p_frame->mb_type, id->ff_enc_c->coded_frame->mb_type,
887                     (mb_width + 1) * mb_height * sizeof(id->p_frame->mb_type[0]));
888
889         for ( i = 0; i < 2; i++ )
890         {
891             int stride = ((16 * mb_width )
892                     >> id->ff_enc_c->coded_frame->motion_subsample_log2) + 1;
893             int height = ((16 * mb_height)
894                     >> id->ff_enc_c->coded_frame->motion_subsample_log2);
895             int b8_stride = mb_width * 2 + 1;
896
897             if ( id->ff_enc_c->coded_frame->motion_val[i] )
898             {
899                 id->p_frame->motion_val[i] = malloc( 2 * stride * height
900                                                 * sizeof(int16_t) );
901                 vlc_memcpy( id->p_frame->motion_val[i],
902                             id->ff_enc_c->coded_frame->motion_val[i],
903                             2 * stride * height * sizeof(int16_t) );
904             }
905             if ( id->ff_enc_c->coded_frame->ref_index[i] )
906             {
907                 id->p_frame->ref_index[i] = malloc( b8_stride * 2 * mb_height
908                                                * sizeof(int8_t) );
909                 vlc_memcpy( id->p_frame->ref_index[i],
910                             id->ff_enc_c->coded_frame->ref_index[i],
911                             b8_stride * 2 * mb_height * sizeof(int8_t));
912             }
913         }
914     }
915 #endif
916
917     p_out = block_New( p_stream, i_out );
918     vlc_memcpy( p_out->p_buffer, id->p_buffer_out, i_out );
919     p_out->i_length = p_buffer->i_length;
920     p_out->i_pts = p_buffer->i_dts;
921     p_out->i_dts = p_buffer->i_dts;
922     p_out->i_rate = p_buffer->i_rate;
923
924     switch ( id->ff_enc_c->coded_frame->pict_type )
925     {
926     case FF_I_TYPE:
927         p_out->i_flags |= BLOCK_FLAG_TYPE_I;
928         break;
929     case FF_P_TYPE:
930         p_out->i_flags |= BLOCK_FLAG_TYPE_P;
931         break;
932     case FF_B_TYPE:
933         p_out->i_flags |= BLOCK_FLAG_TYPE_B;
934         break;
935     default:
936         break;
937     }
938
939     block_Release( p_buffer );
940
941     return p_out;
942 }
943
944 /*****************************************************************************
945  * AudioGetBuffer: Build an alternate audio buffer
946  *****************************************************************************/
947 static block_t *AudioGetBuffer( sout_stream_t *p_stream, sout_stream_id_t *id,
948                                 block_t *p_buffer )
949 {
950     int i_out;
951     block_t *p_out;
952
953     i_out = avcodec_encode_audio( id->ff_enc_c, id->p_buffer_out,
954                                   2 * AVCODEC_MAX_AUDIO_FRAME_SIZE,
955                                   id->p_samples );
956
957     if ( i_out <= 0 )
958         return NULL;
959
960     p_out = block_New( p_stream, i_out );
961     vlc_memcpy( p_out->p_buffer, id->p_buffer_out, i_out );
962     p_out->i_length = p_buffer->i_length;
963     p_out->i_pts = p_buffer->i_dts;
964     p_out->i_dts = p_buffer->i_dts;
965     p_out->i_rate = p_buffer->i_rate;
966
967     block_Release( p_buffer );
968
969     return p_out;
970 }