]> git.sesse.net Git - vlc/blob - modules/stream_out/switcher.c
* modules/access/file.c, directory.c: bug and memory leak fixes
[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 <charset.h>
36 #include <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 AVCODEC_MAX_VIDEO_FRAME_SIZE (3*1024*1024)
55 #define MAX_THRESHOLD 99999999
56
57 /*****************************************************************************
58  * Local prototypes
59  *****************************************************************************/
60 static int      Open    ( vlc_object_t * );
61 static void     Close   ( vlc_object_t * );
62
63 static sout_stream_id_t *Add( sout_stream_t *, es_format_t * );
64 static int Del( sout_stream_t *, sout_stream_id_t * );
65 static int Send( sout_stream_t *, sout_stream_id_t *, block_t * );
66
67 static mtime_t Process( sout_stream_t *p_stream, sout_stream_id_t *id,
68                         mtime_t i_max_dts );
69 static int UnpackFromFile( sout_stream_t *p_stream, const char *psz_file,
70                            int i_width, int i_height,
71                            picture_t *p_pic );
72 static void NetCommand( sout_stream_t *p_stream );
73 static mtime_t VideoCommand( sout_stream_t *p_stream, sout_stream_id_t *id );
74 static block_t *VideoGetBuffer( sout_stream_t *p_stream, sout_stream_id_t *id,
75                                 block_t *p_buffer );
76 static block_t *AudioGetBuffer( sout_stream_t *p_stream, sout_stream_id_t *id,
77                                 block_t *p_buffer );
78
79 /*****************************************************************************
80  * Module descriptor
81  *****************************************************************************/
82 #define FILES_TEXT N_("Files")
83 #define FILES_LONGTEXT N_( \
84     "Full paths of the files separated by colons." )
85 #define SIZES_TEXT N_("Sizes")
86 #define SIZES_LONGTEXT N_( \
87     "List of sizes separated by colons (720x576:480x576)." )
88 #define RATIO_TEXT N_("Aspect ratio")
89 #define RATIO_LONGTEXT N_( \
90     "Aspect ratio (4:3, 16:9)." )
91 #define PORT_TEXT N_("Command UDP port")
92 #define PORT_LONGTEXT N_( \
93     "UDP port to listen to for commands." )
94 #define COMMAND_TEXT N_("Command")
95 #define COMMAND_LONGTEXT N_( \
96     "Initial command to execute." )
97 #define GOP_TEXT N_("GOP size")
98 #define GOP_LONGTEXT N_( \
99     "Number of P frames between two I frames." )
100 #define QSCALE_TEXT N_("Quantizer scale")
101 #define QSCALE_LONGTEXT N_( \
102     "Fixed quantizer scale to use." )
103 #define AUDIO_TEXT N_("Mute audio")
104 #define AUDIO_LONGTEXT N_( \
105     "Mute audio when command is not 0." )
106
107 vlc_module_begin();
108     set_description( _("MPEG2 video switcher stream output") );
109     set_capability( "sout stream", 50 );
110     add_shortcut( "switcher" );
111     set_callbacks( Open, Close );
112
113     add_string( SOUT_CFG_PREFIX "files", "", NULL, FILES_TEXT,
114                 FILES_LONGTEXT, VLC_FALSE );
115     add_string( SOUT_CFG_PREFIX "sizes", "", NULL, SIZES_TEXT,
116                 SIZES_LONGTEXT, VLC_FALSE );
117     add_string( SOUT_CFG_PREFIX "aspect-ratio", "4:3", NULL, RATIO_TEXT,
118                 RATIO_LONGTEXT, VLC_FALSE );
119     add_integer( SOUT_CFG_PREFIX "port", 5001, NULL,
120                  PORT_TEXT, PORT_LONGTEXT, VLC_TRUE );
121     add_integer( SOUT_CFG_PREFIX "command", 0, NULL,
122                  COMMAND_TEXT, COMMAND_LONGTEXT, VLC_TRUE );
123     add_integer( SOUT_CFG_PREFIX "gop", 8, NULL,
124                  GOP_TEXT, GOP_LONGTEXT, VLC_TRUE );
125     add_integer( SOUT_CFG_PREFIX "qscale", 5, NULL,
126                  QSCALE_TEXT, QSCALE_LONGTEXT, VLC_TRUE );
127     add_bool( SOUT_CFG_PREFIX "mute-audio", 1, NULL,
128               AUDIO_TEXT, AUDIO_LONGTEXT, VLC_TRUE );
129 vlc_module_end();
130
131 static const char *ppsz_sout_options[] = {
132     "files", "sizes", "aspect-ratio", "port", "command", "gop", "qscale",
133     "mute-audio", NULL
134 };
135
136 struct sout_stream_sys_t
137 {
138     sout_stream_t   *p_out;
139     int             i_gop;
140     int             i_qscale;
141     int             i_aspect;
142     sout_stream_id_t *pp_audio_ids[MAX_AUDIO];
143     vlc_bool_t      b_audio;
144
145     /* Pictures */
146     picture_t       p_pictures[MAX_PICTURES];
147     int             i_nb_pictures;
148
149     /* Command */
150     int             i_fd;
151     int             i_cmd, i_old_cmd;
152 };
153
154 struct sout_stream_id_t
155 {
156     void            *id;
157     vlc_bool_t      b_switcher_video;
158     vlc_bool_t      b_switcher_audio;
159     es_format_t     f_src;
160     block_t         *p_queued;
161
162     /* ffmpeg part */
163     AVCodec         *ff_enc;
164     AVCodecContext  *ff_enc_c;
165     AVFrame         *p_frame;
166     char            *p_buffer_out;
167     int             i_nb_pred;
168     int16_t         *p_samples;
169 };
170
171 /*****************************************************************************
172  * Open:
173  *****************************************************************************/
174 static int Open( vlc_object_t *p_this )
175 {
176     sout_stream_t     *p_stream = (sout_stream_t*)p_this;
177     sout_stream_sys_t *p_sys;
178     vlc_value_t       val;
179     char              *psz_files, *psz_sizes;
180     int               i_height = 0, i_width = 0;
181
182     p_sys = malloc( sizeof(sout_stream_sys_t) );
183     memset( p_sys, 0, sizeof(sout_stream_sys_t) );
184
185     p_sys->p_out = sout_StreamNew( p_stream->p_sout, p_stream->psz_next );
186     if( !p_sys->p_out )
187     {
188         msg_Err( p_stream, "cannot create chain" );
189         free( p_sys );
190         return VLC_EGENERIC;
191     }
192
193     sout_CfgParse( p_stream, SOUT_CFG_PREFIX, ppsz_sout_options,
194                    p_stream->p_cfg );
195
196     var_Get( p_stream, SOUT_CFG_PREFIX "files", &val );
197     psz_files = val.psz_string;
198     var_Get( p_stream, SOUT_CFG_PREFIX "sizes", &val );
199     psz_sizes = val.psz_string;
200
201     p_sys->i_nb_pictures = 0;
202     while ( psz_files && *psz_files )
203     {
204         char * psz_file = psz_files;
205         char * psz_size = psz_sizes;
206
207         while ( *psz_files && *psz_files != ':' )
208             psz_files++;
209         if ( *psz_files == ':' )
210            *psz_files++ = '\0';
211
212         if ( *psz_sizes )
213         {
214             while ( *psz_sizes && *psz_sizes != ':' )
215                 psz_sizes++;
216             if ( *psz_sizes == ':' )
217                 *psz_sizes++ = '\0';
218             if ( sscanf( psz_size, "%dx%d", &i_width, &i_height ) != 2 )
219             {
220                 msg_Err( p_stream, "bad size %s for file %s", psz_size,
221                          psz_file );
222                 free( p_sys );
223                 return VLC_EGENERIC;
224             }
225         }
226
227         if ( UnpackFromFile( p_stream, psz_file, i_width, i_height,
228                              &p_sys->p_pictures[p_sys->i_nb_pictures] ) < 0 )
229         {
230             free( p_sys );
231             return VLC_EGENERIC;
232         }
233         p_sys->i_nb_pictures++;
234     }
235
236     var_Get( p_stream, SOUT_CFG_PREFIX "aspect-ratio", &val );
237     if ( val.psz_string )
238     {
239         char *psz_parser = strchr( val.psz_string, ':' );
240
241         if( psz_parser )
242         {
243             *psz_parser++ = '\0';
244             p_sys->i_aspect = atoi( val.psz_string ) * VOUT_ASPECT_FACTOR
245                 / atoi( psz_parser );
246         }
247         else
248         {
249             msg_Warn( p_stream, "bad aspect ratio %s", val.psz_string );
250             p_sys->i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;
251         }
252
253         free( val.psz_string );
254     }
255     else
256     {
257         p_sys->i_aspect = 4 * VOUT_ASPECT_FACTOR / 3;
258     }
259
260     var_Get( p_stream, SOUT_CFG_PREFIX "port", &val );
261     p_sys->i_fd = net_OpenUDP( p_stream, NULL, val.i_int, NULL, 0 );
262     if ( p_sys->i_fd < 0 )
263     {
264         free( p_sys );
265         return VLC_EGENERIC;
266     }
267
268     var_Get( p_stream, SOUT_CFG_PREFIX "command", &val );
269     p_sys->i_cmd = val.i_int;
270     p_sys->i_old_cmd = 0;
271
272     var_Get( p_stream, SOUT_CFG_PREFIX "gop", &val );
273     p_sys->i_gop = val.i_int;
274
275     var_Get( p_stream, SOUT_CFG_PREFIX "qscale", &val );
276     p_sys->i_qscale = val.i_int;
277
278     var_Get( p_stream, SOUT_CFG_PREFIX "mute-audio", &val );
279     p_sys->b_audio = val.b_bool;
280
281     p_stream->pf_add    = Add;
282     p_stream->pf_del    = Del;
283     p_stream->pf_send   = Send;
284     p_stream->p_sys     = p_sys;
285
286     avcodec_init();
287     avcodec_register_all();
288
289     return VLC_SUCCESS;
290 }
291
292 /*****************************************************************************
293  * Close:
294  *****************************************************************************/
295 static void Close( vlc_object_t * p_this )
296 {
297     sout_stream_t       *p_stream = (sout_stream_t *)p_this;
298     sout_stream_sys_t   *p_sys = p_stream->p_sys;
299
300     sout_StreamDelete( p_sys->p_out );
301
302     free( p_sys );
303 }
304
305 /*****************************************************************************
306  * Add: Add an input elementary stream
307  *****************************************************************************/
308 static sout_stream_id_t *Add( sout_stream_t *p_stream, es_format_t *p_fmt )
309 {
310     sout_stream_sys_t   *p_sys = p_stream->p_sys;
311     sout_stream_id_t    *id;
312
313     id = malloc( sizeof( sout_stream_id_t ) );
314     memset( id, 0, sizeof( sout_stream_id_t ) );
315     id->id = NULL;
316
317     if ( p_fmt->i_cat == VIDEO_ES
318             && (p_fmt->i_codec == VLC_FOURCC('m', 'p', 'g', 'v')
319                  || p_fmt->i_codec == VLC_FOURCC('f', 'a', 'k', 'e')) )
320     {
321         id->b_switcher_video = VLC_TRUE;
322         p_fmt->i_codec = VLC_FOURCC('m', 'p', 'g', 'v');
323         msg_Dbg( p_stream,
324                  "creating video switcher for fcc=`%4.4s' cmd:%d",
325                  (char*)&p_fmt->i_codec, p_sys->i_cmd );
326     }
327     else if ( p_fmt->i_cat == AUDIO_ES
328                && p_fmt->i_codec == VLC_FOURCC('m', 'p', 'g', 'a')
329                && p_sys->b_audio )
330     {
331         int i_ff_codec = CODEC_ID_MP2;
332         int i;
333
334         id->b_switcher_audio = VLC_TRUE;
335         msg_Dbg( p_stream,
336                  "creating audio switcher for fcc=`%4.4s' cmd:%d",
337                  (char*)&p_fmt->i_codec, p_sys->i_cmd );
338
339         /* Allocate the encoder right now. */
340         if( i_ff_codec == 0 )
341         {
342             msg_Err( p_stream, "cannot find encoder" );
343             return NULL;
344         }
345
346         id->ff_enc = avcodec_find_encoder( i_ff_codec );
347         if( !id->ff_enc )
348         {
349             msg_Err( p_stream, "cannot find encoder (avcodec)" );
350             return NULL;
351         }
352
353         id->ff_enc_c = avcodec_alloc_context();
354
355         /* Set CPU capabilities */
356         id->ff_enc_c->dsp_mask = 0;
357         if( !(p_stream->p_libvlc->i_cpu & CPU_CAPABILITY_MMX) )
358         {
359             id->ff_enc_c->dsp_mask |= FF_MM_MMX;
360         }
361         if( !(p_stream->p_libvlc->i_cpu & CPU_CAPABILITY_MMXEXT) )
362         {
363             id->ff_enc_c->dsp_mask |= FF_MM_MMXEXT;
364         }
365         if( !(p_stream->p_libvlc->i_cpu & CPU_CAPABILITY_3DNOW) )
366         {
367             id->ff_enc_c->dsp_mask |= FF_MM_3DNOW;
368         }
369         if( !(p_stream->p_libvlc->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[10];
654     int i_len = net_ReadNonBlock( p_stream, p_sys->i_fd, NULL, psz_buffer,
655                                   sizeof( psz_buffer ), 0 );
656
657     if ( i_len > 0 )
658     {
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->i_cpu & CPU_CAPABILITY_MMX) )
731         {
732             id->ff_enc_c->dsp_mask |= FF_MM_MMX;
733         }
734         if( !(p_stream->p_libvlc->i_cpu & CPU_CAPABILITY_MMXEXT) )
735         {
736             id->ff_enc_c->dsp_mask |= FF_MM_MMXEXT;
737         }
738         if( !(p_stream->p_libvlc->i_cpu & CPU_CAPABILITY_3DNOW) )
739         {
740             id->ff_enc_c->dsp_mask |= FF_MM_3DNOW;
741         }
742         if( !(p_stream->p_libvlc->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( AVCODEC_MAX_VIDEO_FRAME_SIZE );
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                                   AVCODEC_MAX_VIDEO_FRAME_SIZE,
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_vlc->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_vlc->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_vlc->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_vlc->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_vlc->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 }
945