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