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