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