]> git.sesse.net Git - vlc/blob - modules/stream_out/switcher.c
* modules/stream_out/switcher.c: Added --sout-switcher-aspect-ratio option.
[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     AVRational      sample_aspect_ratio;
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->sample_aspect_ratio.num = atoi( val.psz_string );
237             p_sys->sample_aspect_ratio.den = atoi( psz_parser );
238         }
239         else
240         {
241             msg_Warn( p_stream, "bad aspect ratio %s", val.psz_string );
242             p_sys->sample_aspect_ratio.num = 4;
243             p_sys->sample_aspect_ratio.den = 3;
244         }
245
246         free( val.psz_string );
247     }
248     else
249     {
250         p_sys->sample_aspect_ratio.num = 4;
251         p_sys->sample_aspect_ratio.den = 3;
252     }
253
254     var_Get( p_stream, SOUT_CFG_PREFIX "port", &val );
255     p_sys->i_fd = net_OpenUDP( p_stream, NULL, val.i_int, NULL, 0 );
256     if ( p_sys->i_fd < 0 )
257     {
258         free( p_sys );
259         return VLC_EGENERIC;
260     }
261
262     var_Get( p_stream, SOUT_CFG_PREFIX "command", &val );
263     p_sys->i_cmd = val.i_int;
264     p_sys->i_old_cmd = 0;
265
266     var_Get( p_stream, SOUT_CFG_PREFIX "gop", &val );
267     p_sys->i_gop = val.i_int;
268
269     var_Get( p_stream, SOUT_CFG_PREFIX "qscale", &val );
270     p_sys->i_qscale = val.i_int;
271
272     p_stream->pf_add    = Add;
273     p_stream->pf_del    = Del;
274     p_stream->pf_send   = Send;
275     p_stream->p_sys     = p_sys;
276
277     avcodec_init();
278     avcodec_register_all();
279
280     return VLC_SUCCESS;
281 }
282
283 /*****************************************************************************
284  * Close:
285  *****************************************************************************/
286 static void Close( vlc_object_t * p_this )
287 {
288     sout_stream_t       *p_stream = (sout_stream_t *)p_this;
289     sout_stream_sys_t   *p_sys = p_stream->p_sys;
290
291     sout_StreamDelete( p_sys->p_out );
292
293     free( p_sys );
294 }
295
296 /*****************************************************************************
297  * Add: Add an input elementary stream
298  *****************************************************************************/
299 static sout_stream_id_t *Add( sout_stream_t *p_stream, es_format_t *p_fmt )
300 {
301     sout_stream_sys_t   *p_sys = p_stream->p_sys;
302     sout_stream_id_t    *id;
303
304     id = malloc( sizeof( sout_stream_id_t ) );
305     memset( id, 0, sizeof( sout_stream_id_t ) );
306     id->id = NULL;
307
308     if ( p_fmt->i_cat == VIDEO_ES
309             && (p_fmt->i_codec == VLC_FOURCC('m', 'p', 'g', 'v')
310                  || p_fmt->i_codec == VLC_FOURCC('f', 'a', 'k', 'e')) )
311     {
312         id->b_switcher_video = VLC_TRUE;
313         p_fmt->i_codec = VLC_FOURCC('m', 'p', 'g', 'v');
314         msg_Dbg( p_stream,
315                  "creating video switcher for fcc=`%4.4s'",
316                  (char*)&p_fmt->i_codec );
317     }
318     else if ( p_fmt->i_cat == AUDIO_ES
319                && p_fmt->i_codec == VLC_FOURCC('m', 'p', 'g', 'a') )
320     {
321         int i_ff_codec = CODEC_ID_MP2;
322         int i;
323
324         id->b_switcher_audio = VLC_TRUE;
325         msg_Dbg( p_stream,
326                  "creating audio switcher for fcc=`%4.4s'",
327                  (char*)&p_fmt->i_codec );
328
329         /* Allocate the encoder right now. */
330         if( i_ff_codec == 0 )
331         {
332             msg_Err( p_stream, "cannot find encoder" );
333             return NULL;
334         }
335
336         id->ff_enc = avcodec_find_encoder( i_ff_codec );
337         if( !id->ff_enc )
338         {
339             msg_Err( p_stream, "cannot find encoder (avcodec)" );
340             return NULL;
341         }
342
343         id->ff_enc_c = avcodec_alloc_context();
344
345         /* Set CPU capabilities */
346         id->ff_enc_c->dsp_mask = 0;
347         if( !(p_stream->p_libvlc->i_cpu & CPU_CAPABILITY_MMX) )
348         {
349             id->ff_enc_c->dsp_mask |= FF_MM_MMX;
350         }
351         if( !(p_stream->p_libvlc->i_cpu & CPU_CAPABILITY_MMXEXT) )
352         {
353             id->ff_enc_c->dsp_mask |= FF_MM_MMXEXT;
354         }
355         if( !(p_stream->p_libvlc->i_cpu & CPU_CAPABILITY_3DNOW) )
356         {
357             id->ff_enc_c->dsp_mask |= FF_MM_3DNOW;
358         }
359         if( !(p_stream->p_libvlc->i_cpu & CPU_CAPABILITY_SSE) )
360         {
361             id->ff_enc_c->dsp_mask |= FF_MM_SSE;
362             id->ff_enc_c->dsp_mask |= FF_MM_SSE2;
363         }
364
365         id->ff_enc_c->sample_rate = p_fmt->audio.i_rate;
366         id->ff_enc_c->channels    = p_fmt->audio.i_channels;
367         id->ff_enc_c->bit_rate    = p_fmt->i_bitrate;
368
369         if( avcodec_open( id->ff_enc_c, id->ff_enc ) )
370         {
371             msg_Err( p_stream, "cannot open encoder" );
372             return NULL;
373         }
374
375         id->p_buffer_out = malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * 2 );
376         id->p_samples = malloc( id->ff_enc_c->frame_size
377                                  * p_fmt->audio.i_channels * sizeof(int16_t) );
378         memset( id->p_samples, 0,
379                 id->ff_enc_c->frame_size * p_fmt->audio.i_channels
380                  * sizeof(int16_t) );
381
382         for ( i = 0; i < MAX_AUDIO; i++ )
383         {
384             if ( p_sys->pp_audio_ids[i] == NULL )
385             {
386                 p_sys->pp_audio_ids[i] = id;
387                 break;
388             }
389         }
390         if ( i == MAX_AUDIO )
391         {
392             msg_Err( p_stream, "too many audio streams !" );
393             free( id );
394             return NULL;
395         }
396     }
397     else
398     {
399         msg_Dbg( p_stream, "do not know what to do when switching (fcc=`%4.4s')",
400                  (char*)&p_fmt->i_codec );
401     }
402
403     /* src format */
404     memcpy( &id->f_src, p_fmt, sizeof( es_format_t ) );
405
406     /* open output stream */
407     id->id = p_sys->p_out->pf_add( p_sys->p_out, p_fmt );
408
409     if ( id->id == NULL )
410     {
411         free( id );
412         return NULL;
413     }
414
415     return id;
416 }
417
418 /*****************************************************************************
419  * Del: Del an elementary stream
420  *****************************************************************************/
421 static int Del( sout_stream_t *p_stream, sout_stream_id_t *id )
422 {
423     sout_stream_sys_t   *p_sys = p_stream->p_sys;
424
425     if ( id->b_switcher_audio )
426     {
427         int i;
428         for ( i = 0; i < MAX_AUDIO; i++ )
429         {
430             if ( p_sys->pp_audio_ids[i] == id )
431             {
432                 p_sys->pp_audio_ids[i] = NULL;
433                 break;
434             }
435         }
436     }
437
438     if ( id->ff_enc )
439     {
440         avcodec_close( id->ff_enc_c );
441         av_free( id->ff_enc_c );
442         av_free( id->p_frame );
443         free( id->p_buffer_out );
444     }
445
446     if ( id->id )
447     {
448         p_sys->p_out->pf_del( p_sys->p_out, id->id );
449     }
450     free( id );
451
452     return VLC_SUCCESS;
453 }
454
455 /*****************************************************************************
456  * Send: Process an input packet
457  *****************************************************************************/
458 static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
459                  block_t *p_buffer )
460 {
461     sout_stream_sys_t *p_sys = p_stream->p_sys;
462
463     if ( !id->id )
464     {
465         block_Release( p_buffer );
466         return VLC_EGENERIC;
467     }
468
469     if ( !id->b_switcher_video && !id->b_switcher_audio )
470     {
471         return p_sys->p_out->pf_send( p_sys->p_out, id->id, p_buffer );
472     }
473
474     block_ChainAppend( &id->p_queued, p_buffer );
475
476     if ( id->b_switcher_video )
477     {
478         /* Check for commands for every video frame. */
479         NetCommand( p_stream );
480
481         while ( id->p_queued != NULL )
482         {
483             mtime_t i_dts = 0;
484             int i;
485
486             if ( p_sys->i_old_cmd != p_sys->i_cmd )
487             {
488                 i_dts = VideoCommand( p_stream, id );
489             }
490
491             i_dts = Process( p_stream, id, i_dts );
492
493             for ( i = 0; i < MAX_AUDIO; i++ )
494             {
495                 if ( p_sys->pp_audio_ids[i] != NULL )
496                     Process( p_stream, p_sys->pp_audio_ids[i], i_dts );
497             }
498         }
499     }
500
501     return VLC_SUCCESS;
502 }
503
504 /*****************************************************************************
505  * Process: Process and dispatch buffers
506  *****************************************************************************/
507 static mtime_t Process( sout_stream_t *p_stream, sout_stream_id_t *id,
508                         mtime_t i_max_dts )
509 {
510     sout_stream_sys_t *p_sys = p_stream->p_sys;
511     mtime_t i_dts = 0;
512     block_t *p_blocks = NULL;
513     block_t *p_blocks_out = NULL;
514
515     /* Find out the blocks we need. */
516     while ( id->p_queued != NULL
517              && (!i_max_dts || id->p_queued->i_dts <= i_max_dts) )
518     {
519         block_t *p_next = id->p_queued->p_next;
520         id->p_queued->p_next = NULL;
521         i_dts = id->p_queued->i_dts;
522         block_ChainAppend( &p_blocks, id->p_queued );
523         id->p_queued = p_next;
524     }
525
526     if ( p_sys->i_old_cmd == 0 )
527     {
528         /* Full forward */
529         if ( p_blocks != NULL )
530             p_sys->p_out->pf_send( p_sys->p_out, id->id, p_blocks );
531         return i_dts;
532     }
533
534     if ( p_sys->i_old_cmd == -1 )
535     {
536         /* No output at all */
537         while ( p_blocks != NULL )
538         {
539             block_t * p_next = p_blocks->p_next;
540             block_Release( p_blocks );
541             p_blocks = p_next;
542         }
543         return i_dts;
544     }
545
546     while ( p_blocks != NULL )
547     {
548         block_t * p_next = p_blocks->p_next;
549         block_t * p_out;
550
551         if ( id->b_switcher_video )
552         {
553             p_out = VideoGetBuffer( p_stream, id, p_blocks );
554         }
555         else
556         {
557             p_out = AudioGetBuffer( p_stream, id, p_blocks );
558         }
559         p_blocks = p_next;
560         if ( p_out != NULL )
561         {
562             block_ChainAppend( &p_blocks_out, p_out );
563         }
564     }
565
566     if ( p_blocks_out != NULL )
567         p_sys->p_out->pf_send( p_sys->p_out, id->id, p_blocks_out );
568     return i_dts;
569 }
570
571 /*****************************************************************************
572  * UnpackFromFile: Read a YUV picture and store it in our format
573  *****************************************************************************/
574 static int UnpackFromFile( sout_stream_t *p_stream, const char *psz_file,
575                            int i_width, int i_height,
576                            picture_t *p_pic )
577 {
578     int i, j;
579     FILE *p_file = fopen( psz_file, "r" );
580
581     if ( p_file == NULL )
582     {
583         msg_Err( p_stream, "file %s not found", psz_file );
584         return -1;
585     }
586
587     vout_InitPicture( VLC_OBJECT(p_stream), p_pic, VLC_FOURCC('I','4','2','0'),
588                       i_width, i_height,
589                       i_width * VOUT_ASPECT_FACTOR / i_height );
590     for ( i = 0; i < p_pic->i_planes; i++ )
591     {
592         p_pic->p[i].p_pixels = malloc( p_pic->p[i].i_lines *
593                                            p_pic->p[i].i_pitch );
594         memset( p_pic->p[i].p_pixels, 0, p_pic->p[i].i_lines *
595                     p_pic->p[i].i_pitch );
596     }
597
598     for ( i = 0; i < i_height; i++ )
599     {
600         int i_chroma;
601         uint8_t p_buffer[i_width * 2];
602         uint8_t *p_char = p_buffer;
603         uint8_t *p_y = &p_pic->p[0].p_pixels[i * p_pic->p[0].i_pitch];
604         uint8_t *p_u = &p_pic->p[1].p_pixels[i/2 * p_pic->p[1].i_pitch];
605         uint8_t *p_v = &p_pic->p[2].p_pixels[i/2 * p_pic->p[2].i_pitch];
606
607         if ( fread( p_buffer, 2, i_width, p_file ) != i_width )
608         {
609             msg_Err( p_stream, "premature end of file %s", psz_file );
610             fclose( p_file );
611             for ( i = 0; i < p_pic->i_planes; i++ )
612             {
613                 free( p_pic->p[i].p_pixels );
614             }
615             return -1;
616         }
617
618         i_chroma = 0;
619         for ( j = 0; j < i_width; j++ )
620         {
621             uint8_t **pp_chroma = i_chroma ? &p_v : &p_u;
622             i_chroma = !i_chroma;
623             if ( i & 1 )
624                 **pp_chroma = (**pp_chroma + *p_char + 1) / 2;
625             else
626                 **pp_chroma = *p_char;
627             (*pp_chroma)++;
628             p_char++;
629             *p_y++ = *p_char++;
630         }
631     }
632
633     fclose( p_file );
634     return 0;
635 }
636
637 /*****************************************************************************
638  * NetCommand: Get a command from the network
639  *****************************************************************************/
640 static void NetCommand( sout_stream_t *p_stream )
641 {
642     sout_stream_sys_t *p_sys = p_stream->p_sys;
643     char psz_buffer[10];
644     int i_len = net_ReadNonBlock( p_stream, p_sys->i_fd, NULL, psz_buffer,
645                                   sizeof( psz_buffer ), 0 );
646
647     if ( i_len > 0 )
648     {
649         int i_cmd = strtol( psz_buffer, NULL, 0 );
650         if ( i_cmd < -1 || i_cmd > p_sys->i_nb_pictures )
651         {
652             msg_Err( p_stream, "got a wrong command (%d)", i_cmd );
653             return;
654         }
655
656         p_sys->i_cmd = i_cmd;
657     }
658 }
659
660 /*****************************************************************************
661  * VideoCommand: Create/Delete a video encoder
662  *****************************************************************************/
663 static mtime_t VideoCommand( sout_stream_t *p_stream, sout_stream_id_t *id )
664 {
665     sout_stream_sys_t *p_sys = p_stream->p_sys;
666
667     if ( p_sys->i_cmd == 0 && !(id->p_queued->i_flags & BLOCK_FLAG_TYPE_I) )
668     {
669         mtime_t i_dts = id->p_queued->i_dts;
670         block_t *p_block = id->p_queued->p_next;
671
672         while ( p_block != NULL )
673         {
674             if ( p_block->i_flags & BLOCK_FLAG_TYPE_I )
675                 return i_dts;
676             i_dts = p_block->i_dts;
677             p_block = p_block->p_next;
678         }
679
680         return 0;
681     }
682
683     p_sys->i_old_cmd = p_sys->i_cmd;
684
685     if ( id->ff_enc )
686     {
687         avcodec_close( id->ff_enc_c );
688         av_free( id->ff_enc_c );
689         av_free( id->p_frame );
690         free( id->p_buffer_out );
691         id->ff_enc = NULL;
692     }
693
694     if ( p_sys->i_cmd > 0 )
695     {
696         /* Create a new encoder. */
697         int i_ff_codec = CODEC_ID_MPEG2VIDEO;
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
736         id->ff_enc_c->frame_rate    = 25; /* FIXME */
737         id->ff_enc_c->frame_rate_base = 1;
738         memcpy( &id->ff_enc_c->sample_aspect_ratio, &p_sys->sample_aspect_ratio,
739                 sizeof(AVRational) );
740
741         id->ff_enc_c->gop_size = 200;
742         id->ff_enc_c->max_b_frames = 0;
743
744         id->ff_enc_c->flags |= CODEC_FLAG_QSCALE
745                             | CODEC_FLAG_INPUT_PRESERVED
746                             | CODEC_FLAG_LOW_DELAY;
747
748         id->ff_enc_c->mb_decision = FF_MB_DECISION_SIMPLE;
749
750         if( avcodec_open( id->ff_enc_c, id->ff_enc ) )
751         {
752             msg_Err( p_stream, "cannot open encoder" );
753             return 0;
754         }
755
756         id->p_buffer_out = malloc( AVCODEC_MAX_VIDEO_FRAME_SIZE );
757         id->p_frame = avcodec_alloc_frame();
758         id->p_frame->linesize[0] = p_sys->p_pictures[p_sys->i_cmd-1].p[0].i_pitch;
759         id->p_frame->linesize[1] = p_sys->p_pictures[p_sys->i_cmd-1].p[1].i_pitch;
760         id->p_frame->linesize[2] = p_sys->p_pictures[p_sys->i_cmd-1].p[2].i_pitch;
761         id->p_frame->data[0] = p_sys->p_pictures[p_sys->i_cmd-1].p[0].p_pixels;
762         id->p_frame->data[1] = p_sys->p_pictures[p_sys->i_cmd-1].p[1].p_pixels;
763         id->p_frame->data[2] = p_sys->p_pictures[p_sys->i_cmd-1].p[2].p_pixels;
764
765         id->i_nb_pred = p_sys->i_gop;
766     }
767
768     return 0;
769 }
770
771 /*****************************************************************************
772  * VideoGetBuffer: Build an alternate video buffer
773  *****************************************************************************/
774 static block_t *VideoGetBuffer( sout_stream_t *p_stream, sout_stream_id_t *id,
775                                 block_t *p_buffer )
776 {
777     sout_stream_sys_t *p_sys = p_stream->p_sys;
778     int i_out;
779     block_t *p_out;
780
781     id->p_frame->quality = p_sys->i_qscale * powf(2.0, FF_LAMBDA_SHIFT + 7.0)
782                             / 139.0;
783     id->p_frame->interlaced_frame = 0;
784     id->p_frame->top_field_first = 1;
785     id->p_frame->pts = p_buffer->i_dts;
786
787     if ( id->i_nb_pred >= p_sys->i_gop )
788     {
789         id->p_frame->pict_type = FF_I_TYPE;
790 #if 0
791         id->p_frame->me_threshold = 0;
792         id->p_frame->mb_threshold = 0;
793 #endif
794         id->i_nb_pred = 0;
795     }
796     else
797     {
798         id->p_frame->pict_type = FF_P_TYPE;
799 #if 0
800         if ( id->p_frame->mb_type != NULL )
801         {
802             id->p_frame->me_threshold = MAX_THRESHOLD;
803             id->p_frame->mb_threshold = MAX_THRESHOLD;
804         }
805 #endif
806         id->i_nb_pred++;
807     }
808
809     i_out = avcodec_encode_video( id->ff_enc_c, id->p_buffer_out,
810                                   AVCODEC_MAX_VIDEO_FRAME_SIZE,
811                                   id->p_frame );
812
813     if ( i_out <= 0 )
814         return NULL;
815
816 #if 0
817     if ( id->p_frame->mb_type == NULL
818           && id->ff_enc_c->coded_frame->pict_type != FF_I_TYPE )
819     {
820         int mb_width = (id->ff_enc_c->width + 15) / 16;
821         int mb_height = (id->ff_enc_c->height + 15) / 16;
822         int h_chroma_shift, v_chroma_shift;
823         int i;
824         
825         avcodec_get_chroma_sub_sample( id->ff_enc_c->pix_fmt, &h_chroma_shift,
826                                        &v_chroma_shift );
827
828         id->p_frame->motion_subsample_log2
829             = id->ff_enc_c->coded_frame->motion_subsample_log2;
830         id->p_frame->mb_type = malloc( ((mb_width + 1) * (mb_height + 1) + 1)
831                                     * sizeof(uint32_t) );
832         p_stream->p_vlc->pf_memcpy( id->p_frame->mb_type,
833                                     id->ff_enc_c->coded_frame->mb_type,
834                                     (mb_width + 1) * mb_height
835                                       * sizeof(id->p_frame->mb_type[0]));
836         
837         for ( i = 0; i < 2; i++ )
838         {
839             int stride = ((16 * mb_width )
840                     >> id->ff_enc_c->coded_frame->motion_subsample_log2) + 1;
841             int height = ((16 * mb_height)
842                     >> id->ff_enc_c->coded_frame->motion_subsample_log2);
843             int b8_stride = mb_width * 2 + 1;
844
845             if ( id->ff_enc_c->coded_frame->motion_val[i] )
846             {
847                 id->p_frame->motion_val[i] = malloc( 2 * stride * height
848                                                 * sizeof(int16_t) );
849                 p_stream->p_vlc->pf_memcpy( id->p_frame->motion_val[i],
850                                      id->ff_enc_c->coded_frame->motion_val[i],
851                                      2 * stride * height * sizeof(int16_t) );
852             }
853             if ( id->ff_enc_c->coded_frame->ref_index[i] )
854             {
855                 id->p_frame->ref_index[i] = malloc( b8_stride * 2 * mb_height
856                                                * sizeof(int8_t) );
857                 p_stream->p_vlc->pf_memcpy( id->p_frame->ref_index[i],
858                                  id->ff_enc_c->coded_frame->ref_index[i],
859                                  b8_stride * 2 * mb_height * sizeof(int8_t));
860             }
861         }
862     }
863 #endif
864
865     p_out = block_New( p_stream, i_out );
866     p_stream->p_vlc->pf_memcpy( p_out->p_buffer, id->p_buffer_out, i_out );
867     p_out->i_length = p_buffer->i_length;
868     p_out->i_pts = p_buffer->i_dts;
869     p_out->i_dts = p_buffer->i_dts;
870
871     switch ( id->ff_enc_c->coded_frame->pict_type )
872     {
873     case FF_I_TYPE:
874         p_out->i_flags |= BLOCK_FLAG_TYPE_I;
875         break;
876     case FF_P_TYPE:
877         p_out->i_flags |= BLOCK_FLAG_TYPE_P;
878         break;
879     case FF_B_TYPE:
880         p_out->i_flags |= BLOCK_FLAG_TYPE_B;
881         break;
882     default:
883         break;
884     }
885
886     block_Release( p_buffer );
887
888     return p_out;
889 }
890
891 /*****************************************************************************
892  * AudioGetBuffer: Build an alternate audio buffer
893  *****************************************************************************/
894 static block_t *AudioGetBuffer( sout_stream_t *p_stream, sout_stream_id_t *id,
895                                 block_t *p_buffer )
896 {
897     int i_out;
898     block_t *p_out;
899
900     i_out = avcodec_encode_audio( id->ff_enc_c, id->p_buffer_out,
901                                   2 * AVCODEC_MAX_AUDIO_FRAME_SIZE,
902                                   id->p_samples );
903
904     if ( i_out <= 0 )
905         return NULL;
906
907     p_out = block_New( p_stream, i_out );
908     p_stream->p_vlc->pf_memcpy( p_out->p_buffer, id->p_buffer_out, i_out );
909     p_out->i_length = p_buffer->i_length;
910     p_out->i_pts = p_buffer->i_dts;
911     p_out->i_dts = p_buffer->i_dts;
912
913     block_Release( p_buffer );
914
915     return p_out;
916 }
917