]> git.sesse.net Git - vlc/blob - modules/stream_out/transcode/video.c
transcode: initialize filters properly
[vlc] / modules / stream_out / transcode / video.c
1 /*****************************************************************************
2  * video.c: transcoding stream output module (video)
3  *****************************************************************************
4  * Copyright (C) 2003-2009 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gildas Bazin <gbazin@videolan.org>
9  *          Jean-Paul Saman <jpsaman #_at_# m2x dot nl>
10  *          Antoine Cellerier <dionoea at videolan dot org>
11  *
12  * This program is free software; you can redistribute it and/or modify it
13  * under the terms of the GNU Lesser General Public License as published by
14  * the Free Software Foundation; either version 2.1 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20  * GNU Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public License
23  * along with this program; if not, write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30
31 #include "transcode.h"
32
33 #include <vlc_meta.h>
34 #include <vlc_spu.h>
35 #include <vlc_modules.h>
36
37 #define ENC_FRAMERATE (25 * 1000)
38 #define ENC_FRAMERATE_BASE 1000
39
40 struct decoder_owner_sys_t
41 {
42     sout_stream_sys_t *p_sys;
43 };
44
45 static void video_del_buffer_decoder( decoder_t *p_decoder, picture_t *p_pic )
46 {
47     VLC_UNUSED(p_decoder);
48     picture_Release( p_pic );
49 }
50
51 static void video_link_picture_decoder( decoder_t *p_dec, picture_t *p_pic )
52 {
53     VLC_UNUSED(p_dec);
54     picture_Hold( p_pic );
55 }
56
57 static void video_unlink_picture_decoder( decoder_t *p_dec, picture_t *p_pic )
58 {
59     VLC_UNUSED(p_dec);
60     picture_Release( p_pic );
61 }
62
63 static picture_t *video_new_buffer_decoder( decoder_t *p_dec )
64 {
65     p_dec->fmt_out.video.i_chroma = p_dec->fmt_out.i_codec;
66     return picture_NewFromFormat( &p_dec->fmt_out.video );
67 }
68
69 static picture_t *video_new_buffer_encoder( encoder_t *p_enc )
70 {
71     p_enc->fmt_in.video.i_chroma = p_enc->fmt_in.i_codec;
72     return picture_NewFromFormat( &p_enc->fmt_in.video );
73 }
74
75 static picture_t *transcode_video_filter_buffer_new( filter_t *p_filter )
76 {
77     p_filter->fmt_out.video.i_chroma = p_filter->fmt_out.i_codec;
78     return picture_NewFromFormat( &p_filter->fmt_out.video );
79 }
80 static void transcode_video_filter_buffer_del( filter_t *p_filter, picture_t *p_pic )
81 {
82     VLC_UNUSED(p_filter);
83     picture_Release( p_pic );
84 }
85
86 static int transcode_video_filter_allocation_init( filter_t *p_filter,
87                                                    void *p_data )
88 {
89     VLC_UNUSED(p_data);
90     p_filter->pf_video_buffer_new = transcode_video_filter_buffer_new;
91     p_filter->pf_video_buffer_del = transcode_video_filter_buffer_del;
92     return VLC_SUCCESS;
93 }
94
95 static void transcode_video_filter_allocation_clear( filter_t *p_filter )
96 {
97     VLC_UNUSED(p_filter);
98 }
99
100 static void* EncoderThread( void *obj )
101 {
102     sout_stream_sys_t *p_sys = (sout_stream_sys_t*)obj;
103     sout_stream_id_t *id = p_sys->id_video;
104     picture_t *p_pic = NULL;
105     int canc = vlc_savecancel ();
106     block_t *p_block = NULL;
107
108     for( ;; )
109     {
110
111         vlc_mutex_lock( &p_sys->lock_out );
112         while( !p_sys->b_abort &&
113                (p_pic = picture_fifo_Pop( p_sys->pp_pics )) == NULL )
114             vlc_cond_wait( &p_sys->cond, &p_sys->lock_out );
115
116         if( p_sys->b_abort && !p_pic )
117         {
118             vlc_mutex_unlock( &p_sys->lock_out );
119             break;
120         }
121         vlc_mutex_unlock( &p_sys->lock_out );
122
123         if( p_pic )
124         {
125             p_block = id->p_encoder->pf_encode_video( id->p_encoder, p_pic );
126
127             vlc_mutex_lock( &p_sys->lock_out );
128             block_ChainAppend( &p_sys->p_buffers, p_block );
129
130             vlc_mutex_unlock( &p_sys->lock_out );
131             picture_Release( p_pic );
132         }
133
134         vlc_mutex_lock( &p_sys->lock_out );
135         if( p_sys->b_abort )
136         {
137             vlc_mutex_unlock( &p_sys->lock_out );
138             break;
139         }
140             vlc_mutex_unlock( &p_sys->lock_out );
141     }
142
143     /*Encode what we have in the buffer on closing*/
144     vlc_mutex_lock( &p_sys->lock_out );
145     while( (p_pic = picture_fifo_Pop( p_sys->pp_pics )) != NULL )
146     {
147         p_block = id->p_encoder->pf_encode_video( id->p_encoder, p_pic );
148
149         block_ChainAppend( &p_sys->p_buffers, p_block );
150
151         picture_Release( p_pic );
152     }
153
154     /*Now flush encoder*/
155     do {
156        p_block = id->p_encoder->pf_encode_video(id->p_encoder, NULL );
157        block_ChainAppend( &p_sys->p_buffers, p_block );
158     } while( p_block );
159
160     vlc_mutex_unlock( &p_sys->lock_out );
161
162
163     vlc_restorecancel (canc);
164     return NULL;
165 }
166
167 int transcode_video_new( sout_stream_t *p_stream, sout_stream_id_t *id )
168 {
169     sout_stream_sys_t *p_sys = p_stream->p_sys;
170
171     /* Open decoder
172      * Initialization of decoder structures
173      */
174     id->p_decoder->fmt_out = id->p_decoder->fmt_in;
175     id->p_decoder->fmt_out.i_extra = 0;
176     id->p_decoder->fmt_out.p_extra = 0;
177     id->p_decoder->pf_decode_video = NULL;
178     id->p_decoder->pf_get_cc = NULL;
179     id->p_decoder->pf_get_cc = 0;
180     id->p_decoder->pf_vout_buffer_new = video_new_buffer_decoder;
181     id->p_decoder->pf_vout_buffer_del = video_del_buffer_decoder;
182     id->p_decoder->pf_picture_link    = video_link_picture_decoder;
183     id->p_decoder->pf_picture_unlink  = video_unlink_picture_decoder;
184     id->p_decoder->p_owner = malloc( sizeof(decoder_owner_sys_t) );
185     if( !id->p_decoder->p_owner )
186         return VLC_EGENERIC;
187
188     id->p_decoder->p_owner->p_sys = p_sys;
189     /* id->p_decoder->p_cfg = p_sys->p_video_cfg; */
190
191     id->p_decoder->p_module =
192         module_need( id->p_decoder, "decoder", "$codec", false );
193
194     if( !id->p_decoder->p_module )
195     {
196         msg_Err( p_stream, "cannot find video decoder" );
197         free( id->p_decoder->p_owner );
198         return VLC_EGENERIC;
199     }
200
201     /*
202      * Open encoder.
203      * Because some info about the decoded input will only be available
204      * once the first frame is decoded, we actually only test the availability
205      * of the encoder here.
206      */
207
208     /* Initialization of encoder format structures */
209     es_format_Init( &id->p_encoder->fmt_in, id->p_decoder->fmt_in.i_cat,
210                     id->p_decoder->fmt_out.i_codec );
211     id->p_encoder->fmt_in.video.i_chroma = id->p_decoder->fmt_out.i_codec;
212
213     /* The dimensions will be set properly later on.
214      * Just put sensible values so we can test an encoder is available. */
215     id->p_encoder->fmt_in.video.i_width =
216         id->p_encoder->fmt_out.video.i_width
217           ? id->p_encoder->fmt_out.video.i_width
218           : id->p_decoder->fmt_in.video.i_width
219             ? id->p_decoder->fmt_in.video.i_width : 16;
220     id->p_encoder->fmt_in.video.i_height =
221         id->p_encoder->fmt_out.video.i_height
222           ? id->p_encoder->fmt_out.video.i_height
223           : id->p_decoder->fmt_in.video.i_height
224             ? id->p_decoder->fmt_in.video.i_height : 16;
225     id->p_encoder->fmt_in.video.i_visible_width =
226         id->p_encoder->fmt_out.video.i_visible_width
227           ? id->p_encoder->fmt_out.video.i_visible_width
228           : id->p_decoder->fmt_in.video.i_visible_width
229             ? id->p_decoder->fmt_in.video.i_visible_width : id->p_encoder->fmt_in.video.i_width;
230     id->p_encoder->fmt_in.video.i_visible_height =
231         id->p_encoder->fmt_out.video.i_visible_height
232           ? id->p_encoder->fmt_out.video.i_visible_height
233           : id->p_decoder->fmt_in.video.i_visible_height
234             ? id->p_decoder->fmt_in.video.i_visible_height : id->p_encoder->fmt_in.video.i_height;
235     id->p_encoder->fmt_in.video.i_frame_rate = id->p_decoder->fmt_out.video.i_frame_rate;
236     id->p_encoder->fmt_in.video.i_frame_rate_base = id->p_decoder->fmt_out.video.i_frame_rate_base;
237
238     id->p_encoder->i_threads = p_sys->i_threads;
239     id->p_encoder->p_cfg = p_sys->p_video_cfg;
240
241     id->p_encoder->p_module =
242         module_need( id->p_encoder, "encoder", p_sys->psz_venc, true );
243     if( !id->p_encoder->p_module )
244     {
245         msg_Err( p_stream, "cannot find video encoder (module:%s fourcc:%4.4s). Take a look few lines earlier to see possible reason.",
246                  p_sys->psz_venc ? p_sys->psz_venc : "any",
247                  (char *)&p_sys->i_vcodec );
248         module_unneed( id->p_decoder, id->p_decoder->p_module );
249         id->p_decoder->p_module = 0;
250         free( id->p_decoder->p_owner );
251         return VLC_EGENERIC;
252     }
253
254     /* Close the encoder.
255      * We'll open it only when we have the first frame. */
256     module_unneed( id->p_encoder, id->p_encoder->p_module );
257     if( id->p_encoder->fmt_out.p_extra )
258     {
259         free( id->p_encoder->fmt_out.p_extra );
260         id->p_encoder->fmt_out.p_extra = NULL;
261         id->p_encoder->fmt_out.i_extra = 0;
262     }
263     id->p_encoder->p_module = NULL;
264
265     if( p_sys->i_threads >= 1 )
266     {
267         int i_priority = p_sys->b_high_priority ? VLC_THREAD_PRIORITY_OUTPUT :
268                            VLC_THREAD_PRIORITY_VIDEO;
269         p_sys->id_video = id;
270         vlc_mutex_init( &p_sys->lock_out );
271         vlc_cond_init( &p_sys->cond );
272         p_sys->pp_pics = picture_fifo_New();
273         if( p_sys->pp_pics == NULL )
274         {
275             msg_Err( p_stream, "cannot create picture fifo" );
276             vlc_mutex_destroy( &p_sys->lock_out );
277             vlc_cond_destroy( &p_sys->cond );
278             module_unneed( id->p_decoder, id->p_decoder->p_module );
279             id->p_decoder->p_module = NULL;
280             free( id->p_decoder->p_owner );
281             return VLC_ENOMEM;
282         }
283         p_sys->p_buffers = NULL;
284         p_sys->b_abort = false;
285         if( vlc_clone( &p_sys->thread, EncoderThread, p_sys, i_priority ) )
286         {
287             msg_Err( p_stream, "cannot spawn encoder thread" );
288             vlc_mutex_destroy( &p_sys->lock_out );
289             vlc_cond_destroy( &p_sys->cond );
290             picture_fifo_Delete( p_sys->pp_pics );
291             module_unneed( id->p_decoder, id->p_decoder->p_module );
292             id->p_decoder->p_module = NULL;
293             free( id->p_decoder->p_owner );
294             return VLC_EGENERIC;
295         }
296     }
297     return VLC_SUCCESS;
298 }
299
300 static void transcode_video_filter_init( sout_stream_t *p_stream,
301                                          sout_stream_id_t *id )
302 {
303     es_format_t *p_fmt_out = &id->p_decoder->fmt_out;
304     id->p_encoder->fmt_in.video.i_chroma = id->p_encoder->fmt_in.i_codec;
305
306     id->p_f_chain = filter_chain_New( p_stream, "video filter2",
307                                       false,
308                                       transcode_video_filter_allocation_init,
309                                       transcode_video_filter_allocation_clear,
310                                       p_stream->p_sys );
311     filter_chain_Reset( id->p_f_chain, p_fmt_out, p_fmt_out );
312
313     /* Deinterlace */
314     if( p_stream->p_sys->b_deinterlace )
315     {
316         filter_chain_AppendFilter( id->p_f_chain,
317                                    p_stream->p_sys->psz_deinterlace,
318                                    p_stream->p_sys->p_deinterlace_cfg,
319                                    &id->p_decoder->fmt_out,
320                                    &id->p_decoder->fmt_out );
321
322         p_fmt_out = filter_chain_GetFmtOut( id->p_f_chain );
323     }
324
325     /* Check that we have visible_width/height*/
326     if( !p_fmt_out->video.i_visible_height )
327         p_fmt_out->video.i_visible_height = p_fmt_out->video.i_height;
328     if( !p_fmt_out->video.i_visible_width )
329         p_fmt_out->video.i_visible_width = p_fmt_out->video.i_width;
330
331     if( p_stream->p_sys->psz_vf2 )
332     {
333         id->p_uf_chain = filter_chain_New( p_stream, "video filter2",
334                                           true,
335                            transcode_video_filter_allocation_init,
336                            transcode_video_filter_allocation_clear,
337                            p_stream->p_sys );
338         filter_chain_Reset( id->p_uf_chain, p_fmt_out,
339                             &id->p_encoder->fmt_in );
340         filter_chain_AppendFromString( id->p_uf_chain, p_stream->p_sys->psz_vf2 );
341         p_fmt_out = filter_chain_GetFmtOut( id->p_uf_chain );
342         es_format_Copy( &id->p_encoder->fmt_in, p_fmt_out );
343         id->p_encoder->fmt_out.video.i_width =
344             id->p_encoder->fmt_in.video.i_width;
345         id->p_encoder->fmt_out.video.i_height =
346             id->p_encoder->fmt_in.video.i_height;
347         id->p_encoder->fmt_out.video.i_sar_num =
348             id->p_encoder->fmt_in.video.i_sar_num;
349         id->p_encoder->fmt_out.video.i_sar_den =
350             id->p_encoder->fmt_in.video.i_sar_den;
351     }
352
353 }
354
355 /* Take care of the scaling and chroma conversions. */
356 static void conversion_video_filter_append( sout_stream_id_t *id )
357 {
358     const es_format_t *p_fmt_out = &id->p_decoder->fmt_out;
359     if( id->p_f_chain )
360         p_fmt_out = filter_chain_GetFmtOut( id->p_f_chain );
361     if( id->p_uf_chain )
362         p_fmt_out = filter_chain_GetFmtOut( id->p_uf_chain );
363
364     if( ( p_fmt_out->video.i_chroma != id->p_encoder->fmt_in.video.i_chroma ) ||
365         ( p_fmt_out->video.i_width != id->p_encoder->fmt_in.video.i_width ) ||
366         ( p_fmt_out->video.i_height != id->p_encoder->fmt_in.video.i_height ) )
367     {
368         filter_chain_AppendFilter( id->p_f_chain,
369                                    NULL, NULL,
370                                    p_fmt_out,
371                                    &id->p_encoder->fmt_in );
372     }
373 }
374
375 static void transcode_video_encoder_init( sout_stream_t *p_stream,
376                                           sout_stream_id_t *id )
377 {
378     sout_stream_sys_t *p_sys = p_stream->p_sys;
379
380     const es_format_t *p_fmt_out = &id->p_decoder->fmt_out;
381     if( id->p_f_chain ) {
382         p_fmt_out = filter_chain_GetFmtOut( id->p_f_chain );
383     }
384     if( id->p_uf_chain ) {
385         p_fmt_out = filter_chain_GetFmtOut( id->p_uf_chain );
386     }
387
388     /* Calculate scaling
389      * width/height of source */
390     int i_src_visible_width = p_fmt_out->video.i_visible_width;
391     int i_src_visible_height = p_fmt_out->video.i_visible_height;
392
393     if (i_src_visible_width == 0)
394         i_src_visible_width = p_fmt_out->video.i_width;
395     if (i_src_visible_height == 0)
396         i_src_visible_height = p_fmt_out->video.i_height;
397
398
399     /* with/height scaling */
400     float f_scale_width = 1;
401     float f_scale_height = 1;
402
403     /* aspect ratio */
404     float f_aspect = (double)p_fmt_out->video.i_sar_num *
405                      p_fmt_out->video.i_width /
406                      p_fmt_out->video.i_sar_den /
407                      p_fmt_out->video.i_height;
408
409     msg_Dbg( p_stream, "decoder aspect is %f:1", f_aspect );
410
411     /* Change f_aspect from source frame to source pixel */
412     f_aspect = f_aspect * i_src_visible_height / i_src_visible_width;
413     msg_Dbg( p_stream, "source pixel aspect is %f:1", f_aspect );
414
415     /* Calculate scaling factor for specified parameters */
416     if( id->p_encoder->fmt_out.video.i_width <= 0 &&
417         id->p_encoder->fmt_out.video.i_height <= 0 && p_sys->f_scale )
418     {
419         /* Global scaling. Make sure width will remain a factor of 16 */
420         float f_real_scale;
421         int  i_new_height;
422         int i_new_width = i_src_visible_width * p_sys->f_scale;
423
424         if( i_new_width % 16 <= 7 && i_new_width >= 16 )
425             i_new_width -= i_new_width % 16;
426         else
427             i_new_width += 16 - i_new_width % 16;
428
429         f_real_scale = (float)( i_new_width ) / (float) i_src_visible_width;
430
431         i_new_height = __MAX( 16, i_src_visible_height * (float)f_real_scale );
432
433         f_scale_width = f_real_scale;
434         f_scale_height = (float) i_new_height / (float) i_src_visible_height;
435     }
436     else if( id->p_encoder->fmt_out.video.i_width > 0 &&
437              id->p_encoder->fmt_out.video.i_height <= 0 )
438     {
439         /* Only width specified */
440         f_scale_width = (float)id->p_encoder->fmt_out.video.i_width/i_src_visible_width;
441         f_scale_height = f_scale_width;
442     }
443     else if( id->p_encoder->fmt_out.video.i_width <= 0 &&
444              id->p_encoder->fmt_out.video.i_height > 0 )
445     {
446          /* Only height specified */
447          f_scale_height = (float)id->p_encoder->fmt_out.video.i_height/i_src_visible_height;
448          f_scale_width = f_scale_height;
449      }
450      else if( id->p_encoder->fmt_out.video.i_width > 0 &&
451               id->p_encoder->fmt_out.video.i_height > 0 )
452      {
453          /* Width and height specified */
454          f_scale_width = (float)id->p_encoder->fmt_out.video.i_width/i_src_visible_width;
455          f_scale_height = (float)id->p_encoder->fmt_out.video.i_height/i_src_visible_height;
456      }
457
458      /* check maxwidth and maxheight */
459      if( p_sys->i_maxwidth && f_scale_width > (float)p_sys->i_maxwidth /
460                                                      i_src_visible_width )
461      {
462          f_scale_width = (float)p_sys->i_maxwidth / i_src_visible_width;
463      }
464
465      if( p_sys->i_maxheight && f_scale_height > (float)p_sys->i_maxheight /
466                                                        i_src_visible_height )
467      {
468          f_scale_height = (float)p_sys->i_maxheight / i_src_visible_height;
469      }
470
471
472      /* Change aspect ratio from source pixel to scaled pixel */
473      f_aspect = f_aspect * f_scale_height / f_scale_width;
474      msg_Dbg( p_stream, "scaled pixel aspect is %f:1", f_aspect );
475
476      /* f_scale_width and f_scale_height are now final */
477      /* Calculate width, height from scaling
478       * Make sure its multiple of 2
479       */
480      /* width/height of output stream */
481      int i_dst_visible_width =  2 * (int)(f_scale_width*i_src_visible_width/2+0.5);
482      int i_dst_visible_height = 2 * (int)(f_scale_height*i_src_visible_height/2+0.5);
483      int i_dst_width =  2 * (int)(f_scale_width*p_fmt_out->video.i_width/2+0.5);
484      int i_dst_height = 2 * (int)(f_scale_height*p_fmt_out->video.i_height/2+0.5);
485
486      /* Change aspect ratio from scaled pixel to output frame */
487      f_aspect = f_aspect * i_dst_visible_width / i_dst_visible_height;
488
489      /* Store calculated values */
490      id->p_encoder->fmt_out.video.i_width = i_dst_width;
491      id->p_encoder->fmt_out.video.i_visible_width = i_dst_visible_width;
492      id->p_encoder->fmt_out.video.i_height = i_dst_height;
493      id->p_encoder->fmt_out.video.i_visible_height = i_dst_visible_height;
494
495      id->p_encoder->fmt_in.video.i_width = i_dst_width;
496      id->p_encoder->fmt_in.video.i_visible_width = i_dst_visible_width;
497      id->p_encoder->fmt_in.video.i_height = i_dst_height;
498      id->p_encoder->fmt_in.video.i_visible_height = i_dst_visible_height;
499
500      msg_Dbg( p_stream, "source %ix%i, destination %ix%i",
501          i_src_visible_width, i_src_visible_height,
502          i_dst_visible_width, i_dst_visible_height
503      );
504
505     /* Handle frame rate conversion */
506     if( !id->p_encoder->fmt_out.video.i_frame_rate ||
507         !id->p_encoder->fmt_out.video.i_frame_rate_base )
508     {
509         if( p_fmt_out->video.i_frame_rate &&
510             p_fmt_out->video.i_frame_rate_base )
511         {
512             id->p_encoder->fmt_out.video.i_frame_rate =
513                 p_fmt_out->video.i_frame_rate;
514             id->p_encoder->fmt_out.video.i_frame_rate_base =
515                 p_fmt_out->video.i_frame_rate_base;
516         }
517         else
518         {
519             /* Pick a sensible default value */
520             id->p_encoder->fmt_out.video.i_frame_rate = ENC_FRAMERATE;
521             id->p_encoder->fmt_out.video.i_frame_rate_base = ENC_FRAMERATE_BASE;
522         }
523     }
524
525     id->p_encoder->fmt_in.video.i_frame_rate =
526         id->p_encoder->fmt_out.video.i_frame_rate;
527     id->p_encoder->fmt_in.video.i_frame_rate_base =
528         id->p_encoder->fmt_out.video.i_frame_rate_base;
529
530     vlc_ureduce( &id->p_encoder->fmt_in.video.i_frame_rate,
531         &id->p_encoder->fmt_in.video.i_frame_rate_base,
532         id->p_encoder->fmt_in.video.i_frame_rate,
533         id->p_encoder->fmt_in.video.i_frame_rate_base,
534         0 );
535      msg_Dbg( p_stream, "source fps %d/%d, destination %d/%d",
536         id->p_decoder->fmt_out.video.i_frame_rate,
537         id->p_decoder->fmt_out.video.i_frame_rate_base,
538         id->p_encoder->fmt_in.video.i_frame_rate,
539         id->p_encoder->fmt_in.video.i_frame_rate_base );
540
541     id->i_output_frame_interval = id->p_encoder->fmt_out.video.i_frame_rate_base * CLOCK_FREQ / id->p_encoder->fmt_out.video.i_frame_rate;
542     id->i_input_frame_interval = id->p_decoder->fmt_out.video.i_frame_rate_base * CLOCK_FREQ / id->p_decoder->fmt_out.video.i_frame_rate;
543     msg_Info( p_stream, "input interval %d (base %d)  output interval %d (base %d)", id->i_input_frame_interval, id->p_decoder->fmt_out.video.i_frame_rate_base,
544                         id->i_output_frame_interval, id->p_encoder->fmt_in.video.i_frame_rate_base );
545
546     date_Init( &id->interpolated_pts,
547                id->p_decoder->fmt_out.video.i_frame_rate,
548                1 );
549     date_Init( &id->next_output_pts,
550                id->p_encoder->fmt_in.video.i_frame_rate,
551                1 );
552
553     /* Check whether a particular aspect ratio was requested */
554     if( id->p_encoder->fmt_out.video.i_sar_num <= 0 ||
555         id->p_encoder->fmt_out.video.i_sar_den <= 0 )
556     {
557         vlc_ureduce( &id->p_encoder->fmt_out.video.i_sar_num,
558                      &id->p_encoder->fmt_out.video.i_sar_den,
559                      (uint64_t)p_fmt_out->video.i_sar_num * i_src_visible_width  * i_dst_visible_height,
560                      (uint64_t)p_fmt_out->video.i_sar_den * i_src_visible_height * i_dst_visible_width,
561                      0 );
562     }
563     else
564     {
565         vlc_ureduce( &id->p_encoder->fmt_out.video.i_sar_num,
566                      &id->p_encoder->fmt_out.video.i_sar_den,
567                      id->p_encoder->fmt_out.video.i_sar_num,
568                      id->p_encoder->fmt_out.video.i_sar_den,
569                      0 );
570     }
571
572     id->p_encoder->fmt_in.video.i_sar_num =
573         id->p_encoder->fmt_out.video.i_sar_num;
574     id->p_encoder->fmt_in.video.i_sar_den =
575         id->p_encoder->fmt_out.video.i_sar_den;
576
577     msg_Dbg( p_stream, "encoder aspect is %i:%i",
578              id->p_encoder->fmt_out.video.i_sar_num * id->p_encoder->fmt_out.video.i_width,
579              id->p_encoder->fmt_out.video.i_sar_den * id->p_encoder->fmt_out.video.i_height );
580
581 }
582
583 static int transcode_video_encoder_open( sout_stream_t *p_stream,
584                                          sout_stream_id_t *id )
585 {
586     sout_stream_sys_t *p_sys = p_stream->p_sys;
587
588
589     msg_Dbg( p_stream, "destination (after video filters) %ix%i",
590              id->p_encoder->fmt_in.video.i_width,
591              id->p_encoder->fmt_in.video.i_height );
592
593     id->p_encoder->p_module =
594         module_need( id->p_encoder, "encoder", p_sys->psz_venc, true );
595     if( !id->p_encoder->p_module )
596     {
597         msg_Err( p_stream, "cannot find video encoder (module:%s fourcc:%4.4s)",
598                  p_sys->psz_venc ? p_sys->psz_venc : "any",
599                  (char *)&p_sys->i_vcodec );
600         return VLC_EGENERIC;
601     }
602
603     id->p_encoder->fmt_in.video.i_chroma = id->p_encoder->fmt_in.i_codec;
604
605     /*  */
606     id->p_encoder->fmt_out.i_codec =
607         vlc_fourcc_GetCodec( VIDEO_ES, id->p_encoder->fmt_out.i_codec );
608
609     id->id = sout_StreamIdAdd( p_stream->p_next, &id->p_encoder->fmt_out );
610     if( !id->id )
611     {
612         msg_Err( p_stream, "cannot add this stream" );
613         return VLC_EGENERIC;
614     }
615
616     return VLC_SUCCESS;
617 }
618
619 void transcode_video_close( sout_stream_t *p_stream,
620                                    sout_stream_id_t *id )
621 {
622     if( p_stream->p_sys->i_threads >= 1 )
623     {
624         vlc_mutex_lock( &p_stream->p_sys->lock_out );
625         p_stream->p_sys->b_abort = true;
626         vlc_cond_signal( &p_stream->p_sys->cond );
627         vlc_mutex_unlock( &p_stream->p_sys->lock_out );
628
629         vlc_join( p_stream->p_sys->thread, NULL );
630         vlc_mutex_destroy( &p_stream->p_sys->lock_out );
631         vlc_cond_destroy( &p_stream->p_sys->cond );
632
633         picture_fifo_Delete( p_stream->p_sys->pp_pics );
634         block_ChainRelease( p_stream->p_sys->p_buffers );
635         p_stream->p_sys->pp_pics = NULL;
636     }
637
638     /* Close decoder */
639     if( id->p_decoder->p_module )
640         module_unneed( id->p_decoder, id->p_decoder->p_module );
641     if( id->p_decoder->p_description )
642         vlc_meta_Delete( id->p_decoder->p_description );
643
644     free( id->p_decoder->p_owner );
645
646     /* Close encoder */
647     if( id->p_encoder->p_module )
648         module_unneed( id->p_encoder, id->p_encoder->p_module );
649
650     /* Close filters */
651     if( id->p_f_chain )
652         filter_chain_Delete( id->p_f_chain );
653     if( id->p_uf_chain )
654         filter_chain_Delete( id->p_uf_chain );
655 }
656
657 static void OutputFrame( sout_stream_sys_t *p_sys, picture_t *p_pic, sout_stream_t *p_stream, sout_stream_id_t *id, block_t **out )
658 {
659
660     picture_t *p_pic2 = NULL;
661     bool b_need_duplicate=false;
662     /* If input pts + input_frame_interval is lower than next_output_pts - output_frame_interval
663      * Then the future input frame should fit better and we can drop this one 
664      *
665      * Duplication need is checked in OutputFrame */
666     if( ( p_pic->date + (mtime_t)id->i_input_frame_interval ) <
667         ( date_Get( &id->next_output_pts ) ) )
668     {
669 #if 0
670         msg_Dbg( p_stream, "dropping frame (%"PRId64" + %"PRId64" vs %"PRId64")",
671                  p_pic->date, id->i_input_frame_interval, date_Get(&id->next_output_pts) );
672 #endif
673         picture_Release( p_pic );
674         return;
675     }
676
677     /*
678      * Encoding
679      */
680     /* Check if we have a subpicture to overlay */
681     if( p_sys->p_spu )
682     {
683         video_format_t fmt = id->p_encoder->fmt_in.video;
684         if( fmt.i_visible_width <= 0 || fmt.i_visible_height <= 0 )
685         {
686             fmt.i_visible_width  = fmt.i_width;
687             fmt.i_visible_height = fmt.i_height;
688             fmt.i_x_offset       = 0;
689             fmt.i_y_offset       = 0;
690         }
691
692         subpicture_t *p_subpic = spu_Render( p_sys->p_spu, NULL, &fmt, &fmt,
693                                              p_pic->date, p_pic->date, false );
694
695         /* Overlay subpicture */
696         if( p_subpic )
697         {
698             if( picture_IsReferenced( p_pic ) && !filter_chain_GetLength( id->p_f_chain ) )
699             {
700                 /* We can't modify the picture, we need to duplicate it,
701                  * in this point the picture is already p_encoder->fmt.in format*/
702                 picture_t *p_tmp = video_new_buffer_encoder( id->p_encoder );
703                 if( likely( p_tmp ) )
704                 {
705                     picture_Copy( p_tmp, p_pic );
706                     picture_Release( p_pic );
707                     p_pic = p_tmp;
708                 }
709             }
710             if( unlikely( !p_sys->p_spu_blend ) )
711                 p_sys->p_spu_blend = filter_NewBlend( VLC_OBJECT( p_sys->p_spu ), &fmt );
712             if( likely( p_sys->p_spu_blend ) )
713                 picture_BlendSubpicture( p_pic, p_sys->p_spu_blend, p_subpic );
714             subpicture_Delete( p_subpic );
715         }
716     }
717     /*This pts is handled, increase clock to next one*/
718     date_Increment( &id->next_output_pts, id->p_encoder->fmt_in.video.i_frame_rate_base );
719
720     if( p_sys->i_threads == 0 )
721     {
722         block_t *p_block;
723
724         p_block = id->p_encoder->pf_encode_video( id->p_encoder, p_pic );
725         block_ChainAppend( out, p_block );
726     }
727
728     /* we need to duplicate while next_output_pts + output_frame_interval < input_pts (next input pts)*/
729     b_need_duplicate = ( date_Get( &id->next_output_pts ) + id->i_output_frame_interval ) <
730                        ( date_Get( &id->interpolated_pts ) );
731
732     if( p_sys->i_threads )
733     {
734         if( p_sys->b_master_sync )
735         {
736             p_pic2 = video_new_buffer_encoder( id->p_encoder );
737             if( likely( p_pic2 != NULL ) )
738                 picture_Copy( p_pic2, p_pic );
739         }
740         vlc_mutex_lock( &p_sys->lock_out );
741         picture_fifo_Push( p_sys->pp_pics, p_pic );
742         vlc_cond_signal( &p_sys->cond );
743         vlc_mutex_unlock( &p_sys->lock_out );
744     }
745
746     while( (p_sys->b_master_sync && b_need_duplicate ))
747     {
748         if( p_sys->i_threads >= 1 )
749         {
750             picture_t *p_tmp = NULL;
751             /* We can't modify the picture, we need to duplicate it */
752             p_tmp = video_new_buffer_encoder( id->p_encoder );
753             if( likely( p_tmp != NULL ) )
754             {
755                 picture_Copy( p_tmp, p_pic2 );
756                 p_tmp->date = date_Get( &id->next_output_pts );
757                 vlc_mutex_lock( &p_sys->lock_out );
758                 picture_fifo_Push( p_sys->pp_pics, p_tmp );
759                 vlc_cond_signal( &p_sys->cond );
760                 vlc_mutex_unlock( &p_sys->lock_out );
761             }
762         }
763         else
764         {
765             block_t *p_block;
766             p_pic->date = date_Get( &id->next_output_pts );
767             p_block = id->p_encoder->pf_encode_video(id->p_encoder, p_pic);
768             block_ChainAppend( out, p_block );
769         }
770 #if 0
771         msg_Dbg( p_stream, "duplicated frame");
772 #endif
773         date_Increment( &id->next_output_pts, id->p_encoder->fmt_in.video.i_frame_rate_base );
774         b_need_duplicate = ( date_Get( &id->next_output_pts ) + id->i_output_frame_interval ) <
775                            ( date_Get( &id->interpolated_pts ) );
776     }
777
778     if( p_sys->i_threads && p_pic2 )
779         picture_Release( p_pic2 );
780     else if ( p_sys->i_threads == 0 )
781         picture_Release( p_pic );
782 }
783
784 int transcode_video_process( sout_stream_t *p_stream, sout_stream_id_t *id,
785                                     block_t *in, block_t **out )
786 {
787     sout_stream_sys_t *p_sys = p_stream->p_sys;
788     picture_t *p_pic = NULL;
789     *out = NULL;
790
791     if( unlikely( in == NULL ) )
792     {
793         if( p_sys->i_threads == 0 )
794         {
795             block_t *p_block;
796             do {
797                 p_block = id->p_encoder->pf_encode_video(id->p_encoder, NULL );
798                 block_ChainAppend( out, p_block );
799             } while( p_block );
800         }
801         else
802         {
803             msg_Dbg( p_stream, "Flushing thread and waiting that");
804             vlc_mutex_lock( &p_stream->p_sys->lock_out );
805             p_stream->p_sys->b_abort = true;
806             vlc_cond_signal( &p_stream->p_sys->cond );
807             vlc_mutex_unlock( &p_stream->p_sys->lock_out );
808
809             vlc_join( p_stream->p_sys->thread, NULL );
810             vlc_mutex_lock( &p_sys->lock_out );
811             *out = p_sys->p_buffers;
812             p_sys->p_buffers = NULL;
813             vlc_mutex_unlock( &p_sys->lock_out );
814
815             msg_Dbg( p_stream, "Flushing done");
816         }
817         return VLC_SUCCESS;
818     }
819
820
821     while( (p_pic = id->p_decoder->pf_decode_video( id->p_decoder, &in )) )
822     {
823
824         if( p_stream->p_sout->i_out_pace_nocontrol && p_sys->b_hurry_up )
825         {
826             mtime_t current_date = mdate();
827             if( unlikely( (current_date - 50000) > p_pic->date ) )
828             {
829                 msg_Dbg( p_stream, "late picture skipped (%"PRId64")",
830                          current_date - 50000 - p_pic->date );
831                 picture_Release( p_pic );
832                 continue;
833             }
834         }
835
836         if( unlikely (
837              id->p_encoder->p_module &&
838              !video_format_IsSimilar( &p_sys->fmt_input_video, &id->p_decoder->fmt_out.video )
839             )
840           )
841         {
842             msg_Info( p_stream, "aspect-ratio changed, reiniting. %i -> %i : %i -> %i.",
843                         p_sys->fmt_input_video.i_sar_num, id->p_decoder->fmt_out.video.i_sar_num,
844                         p_sys->fmt_input_video.i_sar_den, id->p_decoder->fmt_out.video.i_sar_den
845                     );
846             /* Close filters */
847             if( id->p_f_chain )
848                 filter_chain_Delete( id->p_f_chain );
849             id->p_f_chain = NULL;
850             if( id->p_uf_chain )
851                 filter_chain_Delete( id->p_uf_chain );
852             id->p_uf_chain = NULL;
853
854             /* Reinitialize filters */
855             id->p_encoder->fmt_out.video.i_width  = p_sys->i_width & ~1;
856             id->p_encoder->fmt_out.video.i_height = p_sys->i_height & ~1;
857             id->p_encoder->fmt_out.video.i_sar_num = id->p_encoder->fmt_out.video.i_sar_den = 0;
858
859             transcode_video_filter_init( p_stream, id );
860             transcode_video_encoder_init( p_stream, id );
861             conversion_video_filter_append( id );
862             memcpy( &p_sys->fmt_input_video, &id->p_decoder->fmt_out.video, sizeof(video_format_t));
863         }
864
865
866         if( unlikely( !id->p_encoder->p_module ) )
867         {
868             if( id->p_f_chain )
869                 filter_chain_Delete( id->p_f_chain );
870             if( id->p_uf_chain )
871                 filter_chain_Delete( id->p_uf_chain );
872             id->p_f_chain = id->p_uf_chain = NULL;
873
874             transcode_video_filter_init( p_stream, id );
875             transcode_video_encoder_init( p_stream, id );
876             conversion_video_filter_append( id );
877             memcpy( &p_sys->fmt_input_video, &id->p_decoder->fmt_out.video, sizeof(video_format_t));
878
879             if( transcode_video_encoder_open( p_stream, id ) != VLC_SUCCESS )
880             {
881                 picture_Release( p_pic );
882                 transcode_video_close( p_stream, id );
883                 id->b_transcode = false;
884                 return VLC_EGENERIC;
885             }
886         }
887
888         /*Input lipsync and drop check */
889         if( p_sys->b_master_sync )
890         {
891             /* How much audio has drifted */
892             mtime_t i_master_drift = p_sys->i_master_drift;
893
894             /* This is the pts input should have now with constant frame rate */
895             mtime_t i_pts = date_Get( &id->interpolated_pts );
896
897             /* How much input pts has drifted */
898             mtime_t i_video_drift = p_pic->date - i_pts;
899
900             /* Check that we are having lipsync with input here */
901             if( unlikely ( ( (i_video_drift - i_master_drift ) > MASTER_SYNC_MAX_DRIFT
902                           || (i_video_drift + i_master_drift ) < -MASTER_SYNC_MAX_DRIFT ) ) )
903             {
904                 msg_Warn( p_stream,
905                     "video drift too big, resetting sync %"PRId64" to %"PRId64,
906                     (i_video_drift + i_master_drift),
907                     p_pic->date
908                     );
909                 date_Set( &id->interpolated_pts, p_pic->date );
910                 date_Set( &id->next_output_pts, p_pic->date );
911                 i_pts = date_Get( &id->interpolated_pts );
912             }
913
914             /* Set the pts of the frame being encoded */
915             p_pic->date = i_pts;
916
917             /* now take next input pts, pts dates are only enabled if p_module is set*/
918             date_Increment( &id->interpolated_pts, id->p_decoder->fmt_out.video.i_frame_rate_base );
919
920
921             /* If input pts + input_frame_interval is lower than next_output_pts - output_frame_interval
922              * Then the future input frame should fit better and we can drop this one 
923              *
924              * Duplication need is checked in OutputFrame */
925             if( ( p_pic->date + (mtime_t)id->i_input_frame_interval ) <
926                 ( date_Get( &id->next_output_pts ) ) )
927             {
928 #if 0
929                 msg_Dbg( p_stream, "dropping frame (%"PRId64" + %"PRId64" vs %"PRId64")",
930                          p_pic->date, id->i_input_frame_interval, date_Get(&id->next_output_pts) );
931 #endif
932                 picture_Release( p_pic );
933                 continue;
934             }
935 #if 0
936             msg_Dbg( p_stream, "not dropping frame");
937 #endif
938
939             /* input calculated pts isn't necessary what pts output should be, so use output pts*/
940             p_pic->date = date_Get( &id->next_output_pts );
941
942
943         }
944
945         /* Run the filter and output chains; first with the picture,
946          * and then with NULL as many times as we need until they
947          * stop outputting frames.
948          */
949         for ( ;; ) {
950             picture_t *p_filtered_pic = p_pic;
951
952             /* Run filter chain */
953             if( id->p_f_chain )
954                 p_filtered_pic = filter_chain_VideoFilter( id->p_f_chain, p_filtered_pic );
955             if( !p_filtered_pic )
956                 break;
957
958             for ( ;; ) {
959                 picture_t *p_user_filtered_pic = p_filtered_pic;
960
961                 /* Run user specified filter chain */
962                 if( id->p_uf_chain )
963                     p_user_filtered_pic = filter_chain_VideoFilter( id->p_uf_chain, p_user_filtered_pic );
964                 if( !p_user_filtered_pic )
965                     break;
966
967                 OutputFrame( p_sys, p_user_filtered_pic, p_stream, id, out );
968
969                 p_filtered_pic = NULL;
970             }
971
972             p_pic = NULL;
973         }
974     }
975
976     if( p_sys->i_threads >= 1 )
977     {
978         /* Pick up any return data the encoder thread wants to output. */
979         vlc_mutex_lock( &p_sys->lock_out );
980         *out = p_sys->p_buffers;
981         p_sys->p_buffers = NULL;
982         vlc_mutex_unlock( &p_sys->lock_out );
983     }
984
985     return VLC_SUCCESS;
986 }
987
988 bool transcode_video_add( sout_stream_t *p_stream, es_format_t *p_fmt,
989                                 sout_stream_id_t *id )
990 {
991     sout_stream_sys_t *p_sys = p_stream->p_sys;
992
993     msg_Dbg( p_stream,
994              "creating video transcoding from fcc=`%4.4s' to fcc=`%4.4s'",
995              (char*)&p_fmt->i_codec, (char*)&p_sys->i_vcodec );
996
997     /* Complete destination format */
998     id->p_encoder->fmt_out.i_codec = p_sys->i_vcodec;
999     id->p_encoder->fmt_out.video.i_width  = p_sys->i_width & ~1;
1000     id->p_encoder->fmt_out.video.i_height = p_sys->i_height & ~1;
1001     id->p_encoder->fmt_out.i_bitrate = p_sys->i_vbitrate;
1002
1003     /* Build decoder -> filter -> encoder chain */
1004     if( transcode_video_new( p_stream, id ) )
1005     {
1006         msg_Err( p_stream, "cannot create video chain" );
1007         return false;
1008     }
1009
1010     /* Stream will be added later on because we don't know
1011      * all the characteristics of the decoded stream yet */
1012     id->b_transcode = true;
1013
1014     if( p_sys->f_fps > 0 )
1015     {
1016         id->p_encoder->fmt_out.video.i_frame_rate = (p_sys->f_fps * ENC_FRAMERATE_BASE);
1017         id->p_encoder->fmt_out.video.i_frame_rate_base = ENC_FRAMERATE_BASE;
1018     }
1019
1020     return true;
1021 }
1022