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