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