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