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