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