]> git.sesse.net Git - vlc/blob - modules/stream_out/switcher.c
Use a vlc_CPU() wrapper instead of (ab)using libvlc_global
[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         unsigned i_cpu = vlc_CPU();
356         id->ff_enc_c->dsp_mask = 0;
357         if( !(i_cpu & CPU_CAPABILITY_MMX) )
358         {
359             id->ff_enc_c->dsp_mask |= FF_MM_MMX;
360         }
361         if( !(i_cpu & CPU_CAPABILITY_MMXEXT) )
362         {
363             id->ff_enc_c->dsp_mask |= FF_MM_MMXEXT;
364         }
365         if( !(i_cpu & CPU_CAPABILITY_3DNOW) )
366         {
367             id->ff_enc_c->dsp_mask |= FF_MM_3DNOW;
368         }
369         if( !(i_cpu & CPU_CAPABILITY_SSE) )
370         {
371             id->ff_enc_c->dsp_mask |= FF_MM_SSE;
372             id->ff_enc_c->dsp_mask |= FF_MM_SSE2;
373         }
374
375         id->ff_enc_c->sample_rate = p_fmt->audio.i_rate;
376         id->ff_enc_c->channels    = p_fmt->audio.i_channels;
377         id->ff_enc_c->bit_rate    = p_fmt->i_bitrate;
378
379         if( avcodec_open( id->ff_enc_c, id->ff_enc ) )
380         {
381             msg_Err( p_stream, "cannot open encoder" );
382             return NULL;
383         }
384
385         id->p_buffer_out = malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * 2 );
386         id->p_samples = malloc( id->ff_enc_c->frame_size
387                                  * p_fmt->audio.i_channels * sizeof(int16_t) );
388         memset( id->p_samples, 0,
389                 id->ff_enc_c->frame_size * p_fmt->audio.i_channels
390                  * sizeof(int16_t) );
391
392         for ( i = 0; i < MAX_AUDIO; i++ )
393         {
394             if ( p_sys->pp_audio_ids[i] == NULL )
395             {
396                 p_sys->pp_audio_ids[i] = id;
397                 break;
398             }
399         }
400         if ( i == MAX_AUDIO )
401         {
402             msg_Err( p_stream, "too many audio streams!" );
403             free( id );
404             return NULL;
405         }
406     }
407     else
408     {
409         msg_Dbg( p_stream, "do not know what to do when switching (fcc=`%4.4s')",
410                  (char*)&p_fmt->i_codec );
411     }
412
413     /* src format */
414     memcpy( &id->f_src, p_fmt, sizeof( es_format_t ) );
415
416     /* open output stream */
417     id->id = p_sys->p_out->pf_add( p_sys->p_out, p_fmt );
418
419     if ( id->id == NULL )
420     {
421         free( id );
422         return NULL;
423     }
424
425     return id;
426 }
427
428 /*****************************************************************************
429  * Del: Del an elementary stream
430  *****************************************************************************/
431 static int Del( sout_stream_t *p_stream, sout_stream_id_t *id )
432 {
433     sout_stream_sys_t   *p_sys = p_stream->p_sys;
434
435     if ( id->b_switcher_audio )
436     {
437         int i;
438         for ( i = 0; i < MAX_AUDIO; i++ )
439         {
440             if ( p_sys->pp_audio_ids[i] == id )
441             {
442                 p_sys->pp_audio_ids[i] = NULL;
443                 break;
444             }
445         }
446     }
447
448     if ( id->ff_enc )
449     {
450         avcodec_close( id->ff_enc_c );
451         av_free( id->ff_enc_c );
452         av_free( id->p_frame );
453         free( id->p_buffer_out );
454     }
455
456     if ( id->id )
457     {
458         p_sys->p_out->pf_del( p_sys->p_out, id->id );
459     }
460     free( id );
461
462     return VLC_SUCCESS;
463 }
464
465 /*****************************************************************************
466  * Send: Process an input packet
467  *****************************************************************************/
468 static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
469                  block_t *p_buffer )
470 {
471     sout_stream_sys_t *p_sys = p_stream->p_sys;
472
473     if ( !id->id )
474     {
475         block_Release( p_buffer );
476         return VLC_EGENERIC;
477     }
478
479     if ( !id->b_switcher_video && !id->b_switcher_audio )
480     {
481         return p_sys->p_out->pf_send( p_sys->p_out, id->id, p_buffer );
482     }
483
484     block_ChainAppend( &id->p_queued, p_buffer );
485
486     if ( id->b_switcher_video )
487     {
488         /* Check for commands for every video frame. */
489         NetCommand( p_stream );
490
491         while ( id->p_queued != NULL )
492         {
493             mtime_t i_dts = 0;
494             int i;
495
496             if ( p_sys->i_old_cmd != p_sys->i_cmd )
497             {
498                 i_dts = VideoCommand( p_stream, id );
499             }
500
501             i_dts = Process( p_stream, id, i_dts );
502
503             for ( i = 0; i < MAX_AUDIO; i++ )
504             {
505                 if ( p_sys->pp_audio_ids[i] != NULL )
506                     Process( p_stream, p_sys->pp_audio_ids[i], i_dts );
507             }
508         }
509     }
510
511     return VLC_SUCCESS;
512 }
513
514 /*****************************************************************************
515  * Process: Process and dispatch buffers
516  *****************************************************************************/
517 static mtime_t Process( sout_stream_t *p_stream, sout_stream_id_t *id,
518                         mtime_t i_max_dts )
519 {
520     sout_stream_sys_t *p_sys = p_stream->p_sys;
521     mtime_t i_dts = 0;
522     block_t *p_blocks = NULL;
523     block_t *p_blocks_out = NULL;
524
525     /* Find out the blocks we need. */
526     while ( id->p_queued != NULL
527              && (!i_max_dts || id->p_queued->i_dts <= i_max_dts) )
528     {
529         block_t *p_next = id->p_queued->p_next;
530         id->p_queued->p_next = NULL;
531         i_dts = id->p_queued->i_dts;
532         block_ChainAppend( &p_blocks, id->p_queued );
533         id->p_queued = p_next;
534     }
535
536     if ( p_sys->i_old_cmd == 0 )
537     {
538         /* Full forward */
539         if ( p_blocks != NULL )
540             p_sys->p_out->pf_send( p_sys->p_out, id->id, p_blocks );
541         return i_dts;
542     }
543
544     if ( p_sys->i_old_cmd == -1 )
545     {
546         /* No output at all */
547         while ( p_blocks != NULL )
548         {
549             block_t * p_next = p_blocks->p_next;
550             block_Release( p_blocks );
551             p_blocks = p_next;
552         }
553         return i_dts;
554     }
555
556     while ( p_blocks != NULL )
557     {
558         block_t * p_next = p_blocks->p_next;
559         block_t * p_out;
560
561         if ( id->b_switcher_video )
562         {
563             p_out = VideoGetBuffer( p_stream, id, p_blocks );
564         }
565         else
566         {
567             p_out = AudioGetBuffer( p_stream, id, p_blocks );
568         }
569         p_blocks = p_next;
570         if ( p_out != NULL )
571         {
572             block_ChainAppend( &p_blocks_out, p_out );
573         }
574     }
575
576     if ( p_blocks_out != NULL )
577         p_sys->p_out->pf_send( p_sys->p_out, id->id, p_blocks_out );
578     return i_dts;
579 }
580
581 /*****************************************************************************
582  * UnpackFromFile: Read a YUV picture and store it in our format
583  *****************************************************************************/
584 static int UnpackFromFile( sout_stream_t *p_stream, const char *psz_file,
585                            int i_width, int i_height,
586                            picture_t *p_pic )
587 {
588     int i, j;
589     FILE *p_file = utf8_fopen( psz_file, "r" );
590
591     if ( p_file == NULL )
592     {
593         msg_Err( p_stream, "file %s not found", psz_file );
594         return -1;
595     }
596
597     vout_InitPicture( VLC_OBJECT(p_stream), p_pic, VLC_FOURCC('I','4','2','0'),
598                       i_width, i_height,
599                       i_width * VOUT_ASPECT_FACTOR / i_height );
600     for ( i = 0; i < p_pic->i_planes; i++ )
601     {
602         p_pic->p[i].p_pixels = malloc( p_pic->p[i].i_lines *
603                                            p_pic->p[i].i_pitch );
604         memset( p_pic->p[i].p_pixels, 0, p_pic->p[i].i_lines *
605                     p_pic->p[i].i_pitch );
606     }
607
608     for ( i = 0; i < i_height; i++ )
609     {
610         int i_chroma;
611         uint8_t p_buffer[i_width * 2];
612         uint8_t *p_char = p_buffer;
613         uint8_t *p_y = &p_pic->p[0].p_pixels[i * p_pic->p[0].i_pitch];
614         uint8_t *p_u = &p_pic->p[1].p_pixels[i/2 * p_pic->p[1].i_pitch];
615         uint8_t *p_v = &p_pic->p[2].p_pixels[i/2 * p_pic->p[2].i_pitch];
616
617         if ( fread( p_buffer, 2, i_width, p_file ) != (size_t)i_width )
618         {
619             msg_Err( p_stream, "premature end of file %s", psz_file );
620             fclose( p_file );
621             for ( i = 0; i < p_pic->i_planes; i++ )
622             {
623                 free( p_pic->p[i].p_pixels );
624             }
625             return -1;
626         }
627
628         i_chroma = 0;
629         for ( j = 0; j < i_width; j++ )
630         {
631             uint8_t **pp_chroma = i_chroma ? &p_v : &p_u;
632             i_chroma = !i_chroma;
633             if ( i & 1 )
634                 **pp_chroma = (**pp_chroma + *p_char + 1) / 2;
635             else
636                 **pp_chroma = *p_char;
637             (*pp_chroma)++;
638             p_char++;
639             *p_y++ = *p_char++;
640         }
641     }
642
643     fclose( p_file );
644     return 0;
645 }
646
647 /*****************************************************************************
648  * NetCommand: Get a command from the network
649  *****************************************************************************/
650 static void NetCommand( sout_stream_t *p_stream )
651 {
652     sout_stream_sys_t *p_sys = p_stream->p_sys;
653     char psz_buffer[11];
654     int i_len = recv( p_sys->i_fd, psz_buffer, sizeof( psz_buffer ) - 1, 0 );
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         unsigned i_cpu = vlc_CPU();
730         id->ff_enc_c->dsp_mask = 0;
731         if( !(i_cpu & CPU_CAPABILITY_MMX) )
732         {
733             id->ff_enc_c->dsp_mask |= FF_MM_MMX;
734         }
735         if( !(i_cpu & CPU_CAPABILITY_MMXEXT) )
736         {
737             id->ff_enc_c->dsp_mask |= FF_MM_MMXEXT;
738         }
739         if( !(i_cpu & CPU_CAPABILITY_3DNOW) )
740         {
741             id->ff_enc_c->dsp_mask |= FF_MM_3DNOW;
742         }
743         if( !(i_cpu & CPU_CAPABILITY_SSE) )
744         {
745             id->ff_enc_c->dsp_mask |= FF_MM_SSE;
746             id->ff_enc_c->dsp_mask |= FF_MM_SSE2;
747         }
748
749         id->ff_enc_c->width = p_sys->p_pictures[p_sys->i_cmd-1].format.i_width;
750         id->ff_enc_c->height = p_sys->p_pictures[p_sys->i_cmd-1].format.i_height;
751         av_reduce( &i_aspect_num, &i_aspect_den,
752                    p_sys->i_aspect,
753                    VOUT_ASPECT_FACTOR, 1 << 30 /* something big */ );
754         av_reduce( &id->ff_enc_c->sample_aspect_ratio.num,
755                    &id->ff_enc_c->sample_aspect_ratio.den,
756                    i_aspect_num * (int64_t)id->ff_enc_c->height,
757                    i_aspect_den * (int64_t)id->ff_enc_c->width, 1 << 30 );
758
759 #if LIBAVCODEC_BUILD >= 4754
760         id->ff_enc_c->time_base.num = 1;
761         id->ff_enc_c->time_base.den = 25; /* FIXME */
762 #else
763         id->ff_enc_c->frame_rate    = 25; /* FIXME */
764         id->ff_enc_c->frame_rate_base = 1;
765 #endif
766
767         id->ff_enc_c->gop_size = 200;
768         id->ff_enc_c->max_b_frames = 0;
769
770         id->ff_enc_c->flags |= CODEC_FLAG_QSCALE
771                             | CODEC_FLAG_INPUT_PRESERVED
772                             | CODEC_FLAG_LOW_DELAY;
773
774         id->ff_enc_c->mb_decision = FF_MB_DECISION_SIMPLE;
775         id->ff_enc_c->pix_fmt = PIX_FMT_YUV420P;
776
777         if( avcodec_open( id->ff_enc_c, id->ff_enc ) )
778         {
779             msg_Err( p_stream, "cannot open encoder" );
780             return 0;
781         }
782
783         id->p_buffer_out = malloc( id->ff_enc_c->width * id->ff_enc_c->height * 3 );
784         id->p_frame = avcodec_alloc_frame();
785         id->p_frame->linesize[0] = p_sys->p_pictures[p_sys->i_cmd-1].p[0].i_pitch;
786         id->p_frame->linesize[1] = p_sys->p_pictures[p_sys->i_cmd-1].p[1].i_pitch;
787         id->p_frame->linesize[2] = p_sys->p_pictures[p_sys->i_cmd-1].p[2].i_pitch;
788         id->p_frame->data[0] = p_sys->p_pictures[p_sys->i_cmd-1].p[0].p_pixels;
789         id->p_frame->data[1] = p_sys->p_pictures[p_sys->i_cmd-1].p[1].p_pixels;
790         id->p_frame->data[2] = p_sys->p_pictures[p_sys->i_cmd-1].p[2].p_pixels;
791
792         id->i_nb_pred = p_sys->i_gop;
793     }
794
795     return 0;
796 }
797
798 /*****************************************************************************
799  * VideoGetBuffer: Build an alternate video buffer
800  *****************************************************************************/
801 static block_t *VideoGetBuffer( sout_stream_t *p_stream, sout_stream_id_t *id,
802                                 block_t *p_buffer )
803 {
804     sout_stream_sys_t *p_sys = p_stream->p_sys;
805     int i_out;
806     block_t *p_out;
807
808     id->p_frame->quality = p_sys->i_qscale * powf(2.0, FF_LAMBDA_SHIFT + 7.0)
809                             / 139.0;
810     id->p_frame->interlaced_frame = 0;
811     id->p_frame->top_field_first = 1;
812     id->p_frame->pts = p_buffer->i_dts;
813
814     if ( id->i_nb_pred >= p_sys->i_gop )
815     {
816         id->p_frame->pict_type = FF_I_TYPE;
817 #if 0
818         id->p_frame->me_threshold = 0;
819         id->p_frame->mb_threshold = 0;
820 #endif
821         id->i_nb_pred = 0;
822     }
823     else
824     {
825         id->p_frame->pict_type = FF_P_TYPE;
826 #if 0
827         if ( id->p_frame->mb_type != NULL )
828         {
829             id->p_frame->me_threshold = MAX_THRESHOLD;
830             id->p_frame->mb_threshold = MAX_THRESHOLD;
831         }
832 #endif
833         id->i_nb_pred++;
834     }
835
836     i_out = avcodec_encode_video( id->ff_enc_c, id->p_buffer_out,
837                                   id->ff_enc_c->width * id->ff_enc_c->height * 3,
838                                   id->p_frame );
839
840     if ( i_out <= 0 )
841         return NULL;
842
843 #if 0
844     if ( id->p_frame->mb_type == NULL
845           && id->ff_enc_c->coded_frame->pict_type != FF_I_TYPE )
846     {
847         int mb_width = (id->ff_enc_c->width + 15) / 16;
848         int mb_height = (id->ff_enc_c->height + 15) / 16;
849         int h_chroma_shift, v_chroma_shift;
850         int i;
851
852         avcodec_get_chroma_sub_sample( id->ff_enc_c->pix_fmt, &h_chroma_shift,
853                                        &v_chroma_shift );
854
855         id->p_frame->motion_subsample_log2
856             = id->ff_enc_c->coded_frame->motion_subsample_log2;
857         id->p_frame->mb_type = malloc( ((mb_width + 1) * (mb_height + 1) + 1)
858                                     * sizeof(uint32_t) );
859         p_stream->p_libvlc->pf_memcpy( id->p_frame->mb_type,
860                                     id->ff_enc_c->coded_frame->mb_type,
861                                     (mb_width + 1) * mb_height
862                                       * sizeof(id->p_frame->mb_type[0]));
863
864         for ( i = 0; i < 2; i++ )
865         {
866             int stride = ((16 * mb_width )
867                     >> id->ff_enc_c->coded_frame->motion_subsample_log2) + 1;
868             int height = ((16 * mb_height)
869                     >> id->ff_enc_c->coded_frame->motion_subsample_log2);
870             int b8_stride = mb_width * 2 + 1;
871
872             if ( id->ff_enc_c->coded_frame->motion_val[i] )
873             {
874                 id->p_frame->motion_val[i] = malloc( 2 * stride * height
875                                                 * sizeof(int16_t) );
876                 p_stream->p_libvlc->pf_memcpy( id->p_frame->motion_val[i],
877                                      id->ff_enc_c->coded_frame->motion_val[i],
878                                      2 * stride * height * sizeof(int16_t) );
879             }
880             if ( id->ff_enc_c->coded_frame->ref_index[i] )
881             {
882                 id->p_frame->ref_index[i] = malloc( b8_stride * 2 * mb_height
883                                                * sizeof(int8_t) );
884                 p_stream->p_libvlc->pf_memcpy( id->p_frame->ref_index[i],
885                                  id->ff_enc_c->coded_frame->ref_index[i],
886                                  b8_stride * 2 * mb_height * sizeof(int8_t));
887             }
888         }
889     }
890 #endif
891
892     p_out = block_New( p_stream, i_out );
893     p_stream->p_libvlc->pf_memcpy( p_out->p_buffer, id->p_buffer_out, i_out );
894     p_out->i_length = p_buffer->i_length;
895     p_out->i_pts = p_buffer->i_dts;
896     p_out->i_dts = p_buffer->i_dts;
897     p_out->i_rate = p_buffer->i_rate;
898
899     switch ( id->ff_enc_c->coded_frame->pict_type )
900     {
901     case FF_I_TYPE:
902         p_out->i_flags |= BLOCK_FLAG_TYPE_I;
903         break;
904     case FF_P_TYPE:
905         p_out->i_flags |= BLOCK_FLAG_TYPE_P;
906         break;
907     case FF_B_TYPE:
908         p_out->i_flags |= BLOCK_FLAG_TYPE_B;
909         break;
910     default:
911         break;
912     }
913
914     block_Release( p_buffer );
915
916     return p_out;
917 }
918
919 /*****************************************************************************
920  * AudioGetBuffer: Build an alternate audio buffer
921  *****************************************************************************/
922 static block_t *AudioGetBuffer( sout_stream_t *p_stream, sout_stream_id_t *id,
923                                 block_t *p_buffer )
924 {
925     int i_out;
926     block_t *p_out;
927
928     i_out = avcodec_encode_audio( id->ff_enc_c, id->p_buffer_out,
929                                   2 * AVCODEC_MAX_AUDIO_FRAME_SIZE,
930                                   id->p_samples );
931
932     if ( i_out <= 0 )
933         return NULL;
934
935     p_out = block_New( p_stream, i_out );
936     p_stream->p_libvlc->pf_memcpy( p_out->p_buffer, id->p_buffer_out, i_out );
937     p_out->i_length = p_buffer->i_length;
938     p_out->i_pts = p_buffer->i_dts;
939     p_out->i_dts = p_buffer->i_dts;
940     p_out->i_rate = p_buffer->i_rate;
941
942     block_Release( p_buffer );
943
944     return p_out;
945 }