More accurate decoder flush.
[vlc.git] / src / input / decoder.c
1 /*****************************************************************************
2  * decoder.c: Functions for the management of decoders
3  *****************************************************************************
4  * Copyright (C) 1999-2004 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Christophe Massiot <massiot@via.ecp.fr>
8  *          Gildas Bazin <gbazin@videolan.org>
9  *          Laurent Aimar <fenrir@via.ecp.fr>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32 #include <assert.h>
33
34 #include <vlc_common.h>
35
36 #include <vlc_block.h>
37 #include <vlc_vout.h>
38 #include <vlc_aout.h>
39 #include <vlc_sout.h>
40 #include <vlc_codec.h>
41 #include <vlc_osd.h>
42
43 #include <vlc_interface.h>
44 #include "audio_output/aout_internal.h"
45 #include "stream_output/stream_output.h"
46 #include "input_internal.h"
47 #include "input_clock.h"
48 #include "input_decoder.h"
49
50 #include "../video_output/vout_internal.h"
51
52 static decoder_t *CreateDecoder( input_thread_t *, es_format_t *, int, sout_instance_t *p_sout );
53 static void       DeleteDecoder( decoder_t * );
54
55 static void      *DecoderThread( vlc_object_t * );
56 static int        DecoderProcess( decoder_t * p_dec, block_t *p_block );
57 static void       DecoderOutputChangePause( decoder_t *p_dec, bool b_paused, mtime_t i_date );
58
59 /* Buffers allocation callbacks for the decoders */
60 static aout_buffer_t *aout_new_buffer( decoder_t *, int );
61 static void aout_del_buffer( decoder_t *, aout_buffer_t * );
62
63 static picture_t *vout_new_buffer( decoder_t * );
64 static void vout_del_buffer( decoder_t *, picture_t * );
65 static void vout_link_picture( decoder_t *, picture_t * );
66 static void vout_unlink_picture( decoder_t *, picture_t * );
67
68 static subpicture_t *spu_new_buffer( decoder_t * );
69 static void spu_del_buffer( decoder_t *, subpicture_t * );
70
71 static es_format_t null_es_format;
72
73 struct decoder_owner_sys_t
74 {
75     bool      b_own_thread;
76
77     int64_t         i_preroll_end;
78
79     input_thread_t  *p_input;
80     input_clock_t   *p_clock;
81     int             i_last_rate;
82
83     vout_thread_t   *p_spu_vout;
84     int              i_spu_channel;
85     int64_t          i_spu_order;
86
87     sout_instance_t         *p_sout;
88     sout_packetizer_input_t *p_sout_input;
89
90     /* Some decoders require already packetized data (ie. not truncated) */
91     decoder_t *p_packetizer;
92
93     /* Current format in use by the output */
94     video_format_t video;
95     audio_format_t audio;
96     es_format_t    sout;
97
98     /* fifo */
99     block_fifo_t *p_fifo;
100
101     /* Lock for communication with decoder thread */
102     vlc_mutex_t lock;
103     vlc_cond_t  wait;
104
105     /* -- These variables need locking on write(only) -- */
106     aout_instance_t *p_aout;
107     aout_input_t    *p_aout_input;
108
109     vout_thread_t   *p_vout;
110
111     /* -- Theses variables need locking on read *and* write -- */
112     /* */
113     /* Pause */
114     bool b_paused;
115     mtime_t i_pause_date;
116
117     /* Flushing */
118     bool b_flushing;
119
120     /* CC */
121     struct
122     {
123         bool b_supported;
124         bool pb_present[4];
125         decoder_t *pp_decoder[4];
126     } cc;
127
128     /* Delay */
129     mtime_t i_ts_delay;
130 };
131
132 /* */
133 static void DecoderUnsupportedCodec( decoder_t *p_dec, vlc_fourcc_t codec )
134 {
135     msg_Err( p_dec, "no suitable decoder module for fourcc `%4.4s'.\n"
136              "VLC probably does not support this sound or video format.",
137              (char*)&codec );
138     intf_UserFatal( p_dec, false, _("No suitable decoder module"), 
139                     _("VLC does not support the audio or video format \"%4.4s\". "
140                       "Unfortunately there is no way for you to fix this."), (char*)&codec );
141 }
142
143 /* decoder_GetInputAttachment:
144  */
145 input_attachment_t *decoder_GetInputAttachment( decoder_t *p_dec,
146                                                 const char *psz_name )
147 {
148     input_attachment_t *p_attachment;
149     if( input_Control( p_dec->p_owner->p_input, INPUT_GET_ATTACHMENT, &p_attachment, psz_name ) )
150         return NULL;
151     return p_attachment;
152 }
153 /* decoder_GetInputAttachments:
154  */
155 int decoder_GetInputAttachments( decoder_t *p_dec,
156                                  input_attachment_t ***ppp_attachment,
157                                  int *pi_attachment )
158 {
159     return input_Control( p_dec->p_owner->p_input, INPUT_GET_ATTACHMENTS,
160                           ppp_attachment, pi_attachment );
161 }
162 /* decoder_GetDisplayDate:
163  */
164 mtime_t decoder_GetDisplayDate( decoder_t *p_dec, mtime_t i_ts )
165 {
166     decoder_owner_sys_t *p_owner = p_dec->p_owner;
167
168     if( !p_owner->p_clock )
169         return i_ts;
170     return input_clock_GetTS( p_owner->p_clock, NULL, p_owner->p_input->i_pts_delay, i_ts );
171 }
172 /* decoder_GetDisplayRate:
173  */
174 int decoder_GetDisplayRate( decoder_t *p_dec )
175 {
176     decoder_owner_sys_t *p_owner = p_dec->p_owner;
177
178     if( !p_owner->p_clock )
179         return INPUT_RATE_DEFAULT;
180     return input_clock_GetRate( p_owner->p_clock );
181 }
182
183 /**
184  * Spawns a new decoder thread
185  *
186  * \param p_input the input thread
187  * \param p_es the es descriptor
188  * \return the spawned decoder object
189  */
190 decoder_t *input_DecoderNew( input_thread_t *p_input,
191                              es_format_t *fmt, input_clock_t *p_clock, sout_instance_t *p_sout  )
192 {
193     decoder_t   *p_dec = NULL;
194     vlc_value_t val;
195
196 #ifndef ENABLE_SOUT
197     (void)b_force_decoder;
198 #else
199     /* If we are in sout mode, search for packetizer module */
200     if( p_sout )
201     {
202         /* Create the decoder configuration structure */
203         p_dec = CreateDecoder( p_input, fmt, VLC_OBJECT_PACKETIZER, p_sout );
204         if( p_dec == NULL )
205         {
206             msg_Err( p_input, "could not create packetizer" );
207             intf_UserFatal( p_input, false, _("Streaming / Transcoding failed"),
208                             _("VLC could not open the packetizer module.") );
209             return NULL;
210         }
211     }
212     else
213 #endif
214     {
215         /* Create the decoder configuration structure */
216         p_dec = CreateDecoder( p_input, fmt, VLC_OBJECT_DECODER, p_sout );
217         if( p_dec == NULL )
218         {
219             msg_Err( p_input, "could not create decoder" );
220             intf_UserFatal( p_input, false, _("Streaming / Transcoding failed"),
221                             _("VLC could not open the decoder module.") );
222             return NULL;
223         }
224     }
225
226     if( !p_dec->p_module )
227     {
228         DecoderUnsupportedCodec( p_dec, fmt->i_codec );
229
230         DeleteDecoder( p_dec );
231         vlc_object_release( p_dec );
232         return NULL;
233     }
234
235     p_dec->p_owner->p_clock = p_clock;
236
237     if( p_sout && p_sout == p_input->p->p_sout && p_input->p->input.b_can_pace_control )
238     {
239         msg_Dbg( p_input, "stream out mode -> no decoder thread" );
240         p_dec->p_owner->b_own_thread = false;
241     }
242     else
243     {
244         var_Get( p_input, "minimize-threads", &val );
245         p_dec->p_owner->b_own_thread = !val.b_bool;
246     }
247
248     if( p_dec->p_owner->b_own_thread )
249     {
250         int i_priority;
251         if( fmt->i_cat == AUDIO_ES )
252             i_priority = VLC_THREAD_PRIORITY_AUDIO;
253         else
254             i_priority = VLC_THREAD_PRIORITY_VIDEO;
255
256         /* Spawn the decoder thread */
257         if( vlc_thread_create( p_dec, "decoder", DecoderThread,
258                                i_priority, false ) )
259         {
260             msg_Err( p_dec, "cannot spawn decoder thread" );
261             module_unneed( p_dec, p_dec->p_module );
262             DeleteDecoder( p_dec );
263             vlc_object_release( p_dec );
264             return NULL;
265         }
266     }
267
268     return p_dec;
269 }
270
271 /**
272  * Kills a decoder thread and waits until it's finished
273  *
274  * \param p_input the input thread
275  * \param p_es the es descriptor
276  * \return nothing
277  */
278 void input_DecoderDelete( decoder_t *p_dec )
279 {
280     decoder_owner_sys_t *p_owner = p_dec->p_owner;
281
282     vlc_object_kill( p_dec );
283
284     if( p_owner->b_own_thread )
285     {
286         /* Make sure we aren't paused anymore */
287         vlc_mutex_lock( &p_owner->lock );
288         if( p_owner->b_paused )
289         {
290             p_owner->b_paused = false;
291             vlc_cond_signal( &p_owner->wait );
292         }
293         vlc_mutex_unlock( &p_owner->lock );
294
295         /* Make sure the thread leaves the function by
296          * sending it an empty block. */
297         block_t *p_block = block_New( p_dec, 0 );
298         input_DecoderDecode( p_dec, p_block );
299
300         vlc_thread_join( p_dec );
301
302         /* Don't module_unneed() here because of the dll loader that wants
303          * close() in the same thread than open()/decode() */
304     }
305     else
306     {
307         /* Flush */
308         input_DecoderDecode( p_dec, NULL );
309
310         module_unneed( p_dec, p_dec->p_module );
311     }
312
313     /* */
314     if( p_dec->p_owner->cc.b_supported )
315     {
316         int i;
317         for( i = 0; i < 4; i++ )
318             input_DecoderSetCcState( p_dec, false, i );
319     }
320
321     /* Delete decoder configuration */
322     DeleteDecoder( p_dec );
323
324     /* Delete the decoder */
325     vlc_object_release( p_dec );
326 }
327
328 /**
329  * Put a block_t in the decoder's fifo.
330  *
331  * \param p_dec the decoder object
332  * \param p_block the data block
333  */
334 void input_DecoderDecode( decoder_t * p_dec, block_t *p_block )
335 {
336     decoder_owner_sys_t *p_owner = p_dec->p_owner;
337
338     if( p_owner->b_own_thread )
339     {
340         if( p_owner->p_input->p->b_out_pace_control )
341         {
342             /* FIXME !!!!! */
343             while( !p_dec->b_die && !p_dec->b_error &&
344                    block_FifoCount( p_owner->p_fifo ) > 10 )
345             {
346                 msleep( 1000 );
347             }
348         }
349         else if( block_FifoSize( p_owner->p_fifo ) > 50000000 /* 50 MB */ )
350         {
351             /* FIXME: ideally we would check the time amount of data
352              * in the fifo instead of its size. */
353             msg_Warn( p_dec, "decoder/packetizer fifo full (data not "
354                       "consumed quickly enough), resetting fifo!" );
355             block_FifoEmpty( p_owner->p_fifo );
356         }
357
358         block_FifoPut( p_owner->p_fifo, p_block );
359     }
360     else
361     {
362         if( p_dec->b_error || ( p_block && p_block->i_buffer <= 0 ) )
363         {
364             if( p_block )
365                 block_Release( p_block );
366         }
367         else
368         {
369             DecoderProcess( p_dec, p_block );
370         }
371     }
372 }
373
374 bool input_DecoderIsEmpty( decoder_t * p_dec )
375 {
376     if( p_dec->p_owner->b_own_thread &&
377         block_FifoCount( p_dec->p_owner->p_fifo ) > 0 )
378     {
379         return false;
380     }
381     return true;
382 }
383
384 void input_DecoderIsCcPresent( decoder_t *p_dec, bool pb_present[4] )
385 {
386     decoder_owner_sys_t *p_owner = p_dec->p_owner;
387     int i;
388
389     vlc_mutex_lock( &p_owner->lock );
390     for( i = 0; i < 4; i++ )
391         pb_present[i] =  p_owner->cc.pb_present[i];
392     vlc_mutex_unlock( &p_owner->lock );
393 }
394 int input_DecoderSetCcState( decoder_t *p_dec, bool b_decode, int i_channel )
395 {
396     decoder_owner_sys_t *p_owner = p_dec->p_owner;
397
398     //msg_Warn( p_dec, "input_DecoderSetCcState: %d @%d", b_decode, i_channel );
399
400     if( i_channel < 0 || i_channel >= 4 || !p_owner->cc.pb_present[i_channel] )
401         return VLC_EGENERIC;
402
403     if( b_decode )
404     {
405         static const vlc_fourcc_t fcc[4] = {
406             VLC_FOURCC('c', 'c', '1', ' '),
407             VLC_FOURCC('c', 'c', '2', ' '),
408             VLC_FOURCC('c', 'c', '3', ' '),
409             VLC_FOURCC('c', 'c', '4', ' '),
410         };
411         decoder_t *p_cc;
412         es_format_t fmt;
413
414         es_format_Init( &fmt, SPU_ES, fcc[i_channel] );
415         p_cc = CreateDecoder( p_owner->p_input, &fmt, VLC_OBJECT_DECODER, p_owner->p_sout );
416         if( !p_cc )
417         {
418             msg_Err( p_dec, "could not create decoder" );
419             intf_UserFatal( p_dec, false, _("Streaming / Transcoding failed"),
420                             _("VLC could not open the decoder module.") );
421             return VLC_EGENERIC;
422         }
423         else if( !p_cc->p_module )
424         {
425             DecoderUnsupportedCodec( p_dec, fcc[i_channel] );
426             DeleteDecoder( p_cc );
427             vlc_object_release( p_cc );
428             return VLC_EGENERIC;
429         }
430         p_cc->p_owner->p_clock = p_owner->p_clock;
431
432         vlc_mutex_lock( &p_owner->lock );
433         p_owner->cc.pp_decoder[i_channel] = p_cc;
434         vlc_mutex_unlock( &p_owner->lock );
435     }
436     else
437     {
438         decoder_t *p_cc;
439
440         vlc_mutex_lock( &p_owner->lock );
441         p_cc = p_owner->cc.pp_decoder[i_channel];
442         p_owner->cc.pp_decoder[i_channel] = NULL;
443         vlc_mutex_unlock( &p_owner->lock );
444
445         if( p_cc )
446         {
447             vlc_object_kill( p_cc );
448             module_unneed( p_cc, p_cc->p_module );
449             DeleteDecoder( p_cc );
450             vlc_object_release( p_cc );
451         }
452     }
453     return VLC_SUCCESS;
454 }
455 int input_DecoderGetCcState( decoder_t *p_dec, bool *pb_decode, int i_channel )
456 {
457     decoder_owner_sys_t *p_owner = p_dec->p_owner;
458
459     *pb_decode = false;
460     if( i_channel < 0 || i_channel >= 4 || !p_owner->cc.pb_present[i_channel] )
461         return VLC_EGENERIC;
462
463     vlc_mutex_lock( &p_owner->lock );
464     *pb_decode = p_owner->cc.pp_decoder[i_channel] != NULL;
465     vlc_mutex_unlock( &p_owner->lock );
466     return VLC_EGENERIC;
467 }
468
469 void input_DecoderChangePause( decoder_t *p_dec, bool b_paused, mtime_t i_date )
470 {
471     decoder_owner_sys_t *p_owner = p_dec->p_owner;
472
473     vlc_mutex_lock( &p_owner->lock );
474
475     assert( !p_owner->b_paused || !b_paused );
476     p_owner->b_paused = b_paused;
477     p_owner->i_pause_date = i_date;
478     if( p_owner->b_own_thread )
479         vlc_cond_signal( &p_owner->wait );
480
481     DecoderOutputChangePause( p_dec, b_paused, i_date );
482     vlc_mutex_unlock( &p_owner->lock );
483 }
484
485 void input_DecoderChangeDelay( decoder_t *p_dec, mtime_t i_delay )
486 {
487     decoder_owner_sys_t *p_owner = p_dec->p_owner;
488
489     vlc_mutex_lock( &p_owner->lock );
490     p_owner->i_ts_delay = i_delay;
491     vlc_mutex_unlock( &p_owner->lock );
492 }
493
494 void input_DecoderFlush( decoder_t *p_dec )
495 {
496     decoder_owner_sys_t *p_owner = p_dec->p_owner;
497     block_t *p_null;
498
499     if( p_owner->b_own_thread )
500     {
501         /* Empty the fifo */
502         block_FifoEmpty( p_owner->p_fifo );
503
504         /* Monitor for flush end */
505         vlc_mutex_lock( &p_owner->lock );
506         p_owner->b_flushing = true;
507         vlc_cond_signal( &p_owner->wait );
508         vlc_mutex_unlock( &p_owner->lock );
509     }
510
511     /* Send a special block */
512     p_null = block_New( p_dec, 128 );
513     if( !p_null )
514         return;
515     p_null->i_flags |= BLOCK_FLAG_DISCONTINUITY;
516     p_null->i_flags |= BLOCK_FLAG_CORE_FLUSH;
517     if( !p_dec->fmt_in.b_packetized )
518         p_null->i_flags |= BLOCK_FLAG_CORRUPTED;
519     memset( p_null->p_buffer, 0, p_null->i_buffer );
520
521     input_DecoderDecode( p_dec, p_null );
522
523     /* */
524     if( p_owner->b_own_thread )
525     {
526         vlc_mutex_lock( &p_owner->lock );
527         while( p_owner->b_flushing )
528             vlc_cond_wait( &p_owner->wait, &p_owner->lock );
529         vlc_mutex_unlock( &p_owner->lock );
530     }
531 }
532
533 /**
534  * Create a decoder object
535  *
536  * \param p_input the input thread
537  * \param p_es the es descriptor
538  * \param i_object_type Object type as define in include/vlc_objects.h
539  * \return the decoder object
540  */
541 static decoder_t * CreateDecoder( input_thread_t *p_input,
542                                   es_format_t *fmt, int i_object_type, sout_instance_t *p_sout )
543 {
544     decoder_t *p_dec;
545     decoder_owner_sys_t *p_owner;
546     int i;
547
548     p_dec = vlc_object_create( p_input, i_object_type );
549     if( p_dec == NULL )
550         return NULL;
551
552     p_dec->pf_decode_audio = NULL;
553     p_dec->pf_decode_video = NULL;
554     p_dec->pf_decode_sub = NULL;
555     p_dec->pf_get_cc = NULL;
556     p_dec->pf_packetize = NULL;
557
558     /* Initialize the decoder fifo */
559     p_dec->p_module = NULL;
560
561     memset( &null_es_format, 0, sizeof(es_format_t) );
562     es_format_Copy( &p_dec->fmt_in, fmt );
563     es_format_Copy( &p_dec->fmt_out, &null_es_format );
564
565     /* Allocate our private structure for the decoder */
566     p_dec->p_owner = p_owner = malloc( sizeof( decoder_owner_sys_t ) );
567     if( p_dec->p_owner == NULL )
568     {
569         vlc_object_release( p_dec );
570         return NULL;
571     }
572     p_dec->p_owner->b_own_thread = true;
573     p_dec->p_owner->i_preroll_end = -1;
574     p_dec->p_owner->i_last_rate = INPUT_RATE_DEFAULT;
575     p_dec->p_owner->p_input = p_input;
576     p_dec->p_owner->p_aout = NULL;
577     p_dec->p_owner->p_aout_input = NULL;
578     p_dec->p_owner->p_vout = NULL;
579     p_dec->p_owner->p_spu_vout = NULL;
580     p_dec->p_owner->i_spu_channel = 0;
581     p_dec->p_owner->i_spu_order = 0;
582     p_dec->p_owner->p_sout = p_sout;
583     p_dec->p_owner->p_sout_input = NULL;
584     p_dec->p_owner->p_packetizer = NULL;
585
586     /* decoder fifo */
587     if( ( p_dec->p_owner->p_fifo = block_FifoNew() ) == NULL )
588     {
589         free( p_dec->p_owner );
590         vlc_object_release( p_dec );
591         return NULL;
592     }
593
594     /* Set buffers allocation callbacks for the decoders */
595     p_dec->pf_aout_buffer_new = aout_new_buffer;
596     p_dec->pf_aout_buffer_del = aout_del_buffer;
597     p_dec->pf_vout_buffer_new = vout_new_buffer;
598     p_dec->pf_vout_buffer_del = vout_del_buffer;
599     p_dec->pf_picture_link    = vout_link_picture;
600     p_dec->pf_picture_unlink  = vout_unlink_picture;
601     p_dec->pf_spu_buffer_new  = spu_new_buffer;
602     p_dec->pf_spu_buffer_del  = spu_del_buffer;
603
604     vlc_object_attach( p_dec, p_input );
605
606     /* Find a suitable decoder/packetizer module */
607     if( i_object_type == VLC_OBJECT_DECODER )
608         p_dec->p_module = module_need( p_dec, "decoder", "$codec", 0 );
609     else
610         p_dec->p_module = module_need( p_dec, "packetizer", "$packetizer", 0 );
611
612     /* Check if decoder requires already packetized data */
613     if( i_object_type == VLC_OBJECT_DECODER &&
614         p_dec->b_need_packetized && !p_dec->fmt_in.b_packetized )
615     {
616         p_dec->p_owner->p_packetizer =
617             vlc_object_create( p_input, VLC_OBJECT_PACKETIZER );
618         if( p_dec->p_owner->p_packetizer )
619         {
620             es_format_Copy( &p_dec->p_owner->p_packetizer->fmt_in,
621                             &p_dec->fmt_in );
622
623             es_format_Copy( &p_dec->p_owner->p_packetizer->fmt_out,
624                             &null_es_format );
625
626             vlc_object_attach( p_dec->p_owner->p_packetizer, p_input );
627
628             p_dec->p_owner->p_packetizer->p_module =
629                 module_need( p_dec->p_owner->p_packetizer,
630                              "packetizer", "$packetizer", 0 );
631
632             if( !p_dec->p_owner->p_packetizer->p_module )
633             {
634                 es_format_Clean( &p_dec->p_owner->p_packetizer->fmt_in );
635                 vlc_object_detach( p_dec->p_owner->p_packetizer );
636                 vlc_object_release( p_dec->p_owner->p_packetizer );
637             }
638         }
639     }
640
641     /* Copy ourself the input replay gain */
642     if( fmt->i_cat == AUDIO_ES )
643     {
644         for( i = 0; i < AUDIO_REPLAY_GAIN_MAX; i++ )
645         {
646             if( !p_dec->fmt_out.audio_replay_gain.pb_peak[i] )
647             {
648                 p_dec->fmt_out.audio_replay_gain.pb_peak[i] = fmt->audio_replay_gain.pb_peak[i];
649                 p_dec->fmt_out.audio_replay_gain.pf_peak[i] = fmt->audio_replay_gain.pf_peak[i];
650             }
651             if( !p_dec->fmt_out.audio_replay_gain.pb_gain[i] )
652             {
653                 p_dec->fmt_out.audio_replay_gain.pb_gain[i] = fmt->audio_replay_gain.pb_gain[i];
654                 p_dec->fmt_out.audio_replay_gain.pf_gain[i] = fmt->audio_replay_gain.pf_gain[i];
655             }
656         }
657     }
658     /* */
659     p_owner->cc.b_supported = false;
660     if( i_object_type == VLC_OBJECT_DECODER )
661     {
662         if( p_owner->p_packetizer && p_owner->p_packetizer->pf_get_cc )
663             p_owner->cc.b_supported = true;
664         if( p_dec->pf_get_cc )
665             p_owner->cc.b_supported = true;
666     }
667
668     vlc_mutex_init( &p_owner->lock );
669     vlc_cond_init( &p_owner->wait );
670     p_owner->b_paused = false;
671     p_owner->i_pause_date = 0;
672     p_owner->b_flushing = false;
673     for( i = 0; i < 4; i++ )
674     {
675         p_owner->cc.pb_present[i] = false;
676         p_owner->cc.pp_decoder[i] = NULL;
677     }
678     p_owner->i_ts_delay = 0;
679     return p_dec;
680 }
681
682 /**
683  * The decoding main loop
684  *
685  * \param p_dec the decoder
686  */
687 static void *DecoderThread( vlc_object_t *p_this )
688 {
689     decoder_t *p_dec = (decoder_t *)p_this;
690     decoder_owner_sys_t *p_owner = p_dec->p_owner;
691
692     block_t *p_block;
693     int canc = vlc_savecancel();
694
695     /* The decoder's main loop */
696     while( vlc_object_alive( p_dec ) && !p_dec->b_error )
697     {
698         if( ( p_block = block_FifoGet( p_owner->p_fifo ) ) == NULL )
699         {
700             p_dec->b_error = true;
701             break;
702         }
703
704         if( DecoderProcess( p_dec, p_block ) != VLC_SUCCESS )
705             break;
706     }
707
708     while( vlc_object_alive( p_dec ) )
709     {
710         /* Trash all received PES packets */
711         p_block = block_FifoGet( p_owner->p_fifo );
712         if( p_block )
713             block_Release( p_block );
714     }
715
716     /* We do it here because of the dll loader that wants close() in the
717      * same thread than open()/decode() */
718     module_unneed( p_dec, p_dec->p_module );
719     vlc_restorecancel( canc );
720     return NULL;
721 }
722
723 static void DecoderWaitUnpause( decoder_t *p_dec, bool *pb_reject )
724 {
725     decoder_owner_sys_t *p_owner = p_dec->p_owner;
726
727     vlc_mutex_lock( &p_owner->lock );
728
729     while( p_owner->b_paused && !p_owner->b_flushing )
730         vlc_cond_wait( &p_owner->wait, &p_owner->lock );
731
732     if( pb_reject )
733         *pb_reject = p_owner->b_flushing;
734
735     vlc_mutex_unlock( &p_owner->lock );
736 }
737
738 static void DecoderSignalFlushed( decoder_t *p_dec )
739 {
740     decoder_owner_sys_t *p_owner = p_dec->p_owner;
741
742     vlc_mutex_lock( &p_owner->lock );
743
744     if( p_owner->b_flushing )
745     {
746         p_owner->b_flushing = false;
747         vlc_cond_signal( &p_owner->wait );
748     }
749
750     vlc_mutex_unlock( &p_owner->lock );
751 }
752
753 static bool DecoderIsFlushing( decoder_t *p_dec )
754 {
755     decoder_owner_sys_t *p_owner = p_dec->p_owner;
756     bool b_flushing;
757
758     vlc_mutex_lock( &p_owner->lock );
759
760     b_flushing = p_owner->b_flushing;
761
762     vlc_mutex_unlock( &p_owner->lock );
763
764     return b_flushing;
765 }
766
767 static void DecoderGetDelays( decoder_t *p_dec, mtime_t *pi_ts_delay, mtime_t *pi_es_delay )
768 {
769     decoder_owner_sys_t *p_owner = p_dec->p_owner;
770
771     *pi_ts_delay = p_owner->p_input->i_pts_delay;
772
773     vlc_mutex_lock( &p_owner->lock );
774
775     *pi_es_delay = p_owner->i_ts_delay;
776
777     vlc_mutex_unlock( &p_owner->lock );
778 }
779
780 static void DecoderOutputChangePause( decoder_t *p_dec, bool b_paused, mtime_t i_date )
781 {
782     decoder_owner_sys_t *p_owner = p_dec->p_owner;
783
784     vlc_assert_locked( &p_owner->lock );
785
786     /* XXX only audio and video output have to be paused.
787      * - for sout it is useless
788      * - for subs, it is done by the vout
789      */
790     if( p_dec->fmt_in.i_cat == AUDIO_ES )
791     {
792         if( p_owner->p_aout && p_owner->p_aout_input )
793             aout_DecChangePause( p_owner->p_aout, p_owner->p_aout_input,
794                                  b_paused, i_date );
795     }
796     else if( p_dec->fmt_in.i_cat == VIDEO_ES )
797     {
798         if( p_owner->p_vout )
799             vout_ChangePause( p_owner->p_vout, b_paused, i_date );
800     }
801 }
802 static inline void DecoderUpdatePreroll( int64_t *pi_preroll, const block_t *p )
803 {
804     if( p->i_flags & (BLOCK_FLAG_PREROLL|BLOCK_FLAG_DISCONTINUITY) )
805         *pi_preroll = INT64_MAX;
806     else if( p->i_pts > 0 )
807         *pi_preroll = __MIN( *pi_preroll, p->i_pts );
808     else if( p->i_dts > 0 )
809         *pi_preroll = __MIN( *pi_preroll, p->i_dts );
810 }
811
812 static mtime_t DecoderTeletextFixTs( mtime_t i_ts, mtime_t i_ts_delay )
813 {
814     mtime_t current_date = mdate();
815
816     /* FIXME I don't really like that, es_out SHOULD do it using the video pts */
817     if( !i_ts || i_ts > current_date + 10000000 || i_ts < current_date )
818     {
819         /* ETSI EN 300 472 Annex A : do not take into account the PTS
820          * for teletext streams. */
821         return current_date + 400000 + i_ts_delay;
822     }
823     return i_ts;
824 }
825
826 static void DecoderSoutBufferFixTs( block_t *p_block,
827                                     input_clock_t *p_clock,
828                                     mtime_t i_ts_delay, mtime_t i_es_delay,
829                                     bool b_teletext )
830 {
831     assert( p_clock );
832
833     if( !p_block->i_dts && !p_block->i_pts )
834         p_block->i_rate = input_clock_GetRate( p_clock );
835
836     if( p_block->i_dts > 0 )
837         p_block->i_dts = input_clock_GetTS( p_clock, &p_block->i_rate,
838                                             i_ts_delay, p_block->i_dts + i_es_delay);
839
840     if( p_block->i_pts > 0 )
841         p_block->i_pts = input_clock_GetTS( p_clock, &p_block->i_rate,
842                                             i_ts_delay, p_block->i_pts + i_es_delay );
843
844     if( p_block->i_length > 0 )
845         p_block->i_length = ( p_block->i_length * p_block->i_rate +
846                                 INPUT_RATE_DEFAULT-1 ) / INPUT_RATE_DEFAULT;
847
848     if( b_teletext )
849         p_block->i_pts = DecoderTeletextFixTs( p_block->i_pts, i_ts_delay );
850 }
851 static void DecoderAoutBufferFixTs( aout_buffer_t *p_buffer, int *pi_rate,
852                                     input_clock_t *p_clock,
853                                     mtime_t i_ts_delay, mtime_t i_es_delay )
854 {
855     /* sout display module does not set clock */
856     if( !p_clock )
857         return;
858
859     if( !p_buffer->start_date && !p_buffer->end_date )
860         *pi_rate = input_clock_GetRate( p_clock );
861
862     if( p_buffer->start_date > 0 )
863         p_buffer->start_date =
864             input_clock_GetTS( p_clock, pi_rate,
865                                i_ts_delay, p_buffer->start_date + i_es_delay );
866
867     if( p_buffer->end_date > 0 )
868         p_buffer->end_date =
869             input_clock_GetTS( p_clock, pi_rate,
870                                i_ts_delay, p_buffer->end_date + i_es_delay );
871 }
872 static void DecoderVoutBufferFixTs( picture_t *p_picture, int *pi_rate,
873                                     input_clock_t *p_clock,
874                                     mtime_t i_ts_delay, mtime_t i_es_delay )
875 {
876     /* sout display module does not set clock */
877     if( !p_clock )
878         return;
879
880     if( p_picture->date > 0 )
881         p_picture->date =
882             input_clock_GetTS( p_clock, pi_rate,
883                                i_ts_delay, p_picture->date + i_es_delay );
884 }
885 static void DecoderSpuBufferFixTs( subpicture_t *p_subpic,
886                                    input_clock_t *p_clock,
887                                    mtime_t i_ts_delay, mtime_t i_es_delay,
888                                    bool b_teletext )
889 {
890     bool b_ephemere = p_subpic->i_start == p_subpic->i_stop;
891
892     /* sout display module does not set clock */
893     if( !p_clock )
894         return;
895
896     if( p_subpic->i_start > 0 )
897         p_subpic->i_start =
898             input_clock_GetTS( p_clock, NULL,
899                                i_ts_delay, p_subpic->i_start + i_es_delay );
900
901     if( p_subpic->i_stop > 0 )
902         p_subpic->i_stop =
903             input_clock_GetTS( p_clock, NULL,
904                                i_ts_delay, p_subpic->i_stop + i_es_delay );
905
906     /* Do not create ephemere picture because of rounding errors */
907     if( !b_ephemere && p_subpic->i_start == p_subpic->i_stop )
908         p_subpic->i_stop++;
909
910     if( b_teletext )
911         p_subpic->i_start = DecoderTeletextFixTs( p_subpic->i_start, i_ts_delay );
912 }
913
914 static void DecoderDecodeAudio( decoder_t *p_dec, block_t *p_block )
915 {
916     decoder_owner_sys_t *p_owner = p_dec->p_owner;
917     input_thread_t  *p_input = p_owner->p_input;
918     input_clock_t   *p_clock = p_owner->p_clock;
919     aout_buffer_t   *p_aout_buf;
920     int i_decoded = 0;
921     int i_lost = 0;
922     int i_played = 0;
923
924     while( (p_aout_buf = p_dec->pf_decode_audio( p_dec, &p_block )) )
925     {
926         aout_instance_t *p_aout = p_owner->p_aout;
927         aout_input_t    *p_aout_input = p_owner->p_aout_input;
928         int i_lost = 0;
929         int i_played;
930
931         if( p_dec->b_die )
932         {
933             /* It prevent freezing VLC in case of broken decoder */
934             aout_DecDeleteBuffer( p_aout, p_aout_input, p_aout_buf );
935             if( p_block )
936                 block_Release( p_block );
937             break;
938         }
939         i_decoded++;
940
941         if( p_aout_buf->start_date < p_owner->i_preroll_end )
942         {
943             aout_DecDeleteBuffer( p_aout, p_aout_input, p_aout_buf );
944             continue;
945         }
946
947         if( p_owner->i_preroll_end > 0 )
948         {
949             /* FIXME TODO flush audio output (don't know how to do that) */
950             msg_Dbg( p_dec, "End of audio preroll" );
951             p_owner->i_preroll_end = -1;
952         }
953
954         bool b_reject;
955         DecoderWaitUnpause( p_dec, &b_reject );
956
957         int i_rate = INPUT_RATE_DEFAULT;
958         mtime_t i_ts_delay;
959         mtime_t i_es_delay;
960         DecoderGetDelays( p_dec, &i_ts_delay, &i_es_delay );
961
962         DecoderAoutBufferFixTs( p_aout_buf, &i_rate, p_clock, i_ts_delay, i_es_delay );
963
964         if( !p_clock && p_block && p_block->i_rate > 0 )
965             i_rate = p_block->i_rate;
966
967         /* FIXME TODO take care of audio-delay for mdate check */
968         const mtime_t i_max_date = mdate() + i_ts_delay +
969             i_es_delay * i_rate / INPUT_RATE_DEFAULT + AOUT_MAX_ADVANCE_TIME;
970
971         if( !b_reject &&
972             p_aout_buf->start_date > 0 &&
973             p_aout_buf->start_date <= i_max_date &&
974             i_rate >= INPUT_RATE_DEFAULT/AOUT_MAX_INPUT_RATE &&
975             i_rate <= INPUT_RATE_DEFAULT*AOUT_MAX_INPUT_RATE )
976         {
977             /* Wait if we are too early
978              * FIXME that's plain ugly to do it here */
979             mwait( p_aout_buf->start_date - AOUT_MAX_PREPARE_TIME );
980
981             if( !aout_DecPlay( p_aout, p_aout_input, p_aout_buf, i_rate ) )
982                 i_played++;
983             i_lost += aout_DecGetResetLost( p_aout, p_aout_input );
984         }
985         else
986         {
987             if( p_aout_buf->start_date <= 0 )
988             {
989                 msg_Warn( p_dec, "non-dated audio buffer received" );
990             }
991             else if( p_aout_buf->start_date > i_max_date )
992             {
993                 msg_Warn( p_aout, "received buffer in the future (%"PRId64")",
994                           p_aout_buf->start_date - mdate() );
995             }
996             i_lost++;
997             aout_DecDeleteBuffer( p_aout, p_aout_input, p_aout_buf );
998         }
999
1000     }
1001
1002     /* Update ugly stat */
1003     if( i_decoded > 0 || i_lost > 0 || i_played > 0 )
1004     {
1005         vlc_mutex_lock( &p_input->p->counters.counters_lock);
1006
1007         stats_UpdateInteger( p_dec, p_input->p->counters.p_lost_abuffers,
1008                              i_lost, NULL );
1009         stats_UpdateInteger( p_dec, p_input->p->counters.p_played_abuffers,
1010                              i_played, NULL );
1011         stats_UpdateInteger( p_dec, p_input->p->counters.p_decoded_audio,
1012                              i_decoded, NULL );
1013
1014         vlc_mutex_unlock( &p_input->p->counters.counters_lock);
1015     }
1016 }
1017 static void DecoderGetCc( decoder_t *p_dec, decoder_t *p_dec_cc )
1018 {
1019     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1020     block_t *p_cc;
1021     bool pb_present[4];
1022     int i;
1023     int i_cc_decoder;
1024
1025     assert( p_dec_cc->pf_get_cc != NULL );
1026
1027     /* Do not try retreiving CC if not wanted (sout) or cannot be retreived */
1028     if( !p_owner->cc.b_supported )
1029         return;
1030
1031     p_cc = p_dec_cc->pf_get_cc( p_dec_cc, pb_present );
1032     if( !p_cc )
1033         return;
1034
1035     vlc_mutex_lock( &p_owner->lock );
1036     for( i = 0, i_cc_decoder = 0; i < 4; i++ )
1037     {
1038         p_owner->cc.pb_present[i] |= pb_present[i];
1039         if( p_owner->cc.pp_decoder[i] )
1040             i_cc_decoder++;
1041     }
1042
1043     for( i = 0; i < 4; i++ )
1044     {
1045         if( !p_owner->cc.pp_decoder[i] )
1046             continue;
1047
1048         if( i_cc_decoder > 1 )
1049             DecoderProcess( p_owner->cc.pp_decoder[i], block_Duplicate( p_cc ) );
1050         else
1051             DecoderProcess( p_owner->cc.pp_decoder[i], p_cc );
1052         i_cc_decoder--;
1053     }
1054     vlc_mutex_unlock( &p_owner->lock );
1055 }
1056 static void VoutDisplayedPicture( vout_thread_t *p_vout, picture_t *p_pic )
1057 {
1058     vlc_mutex_lock( &p_vout->picture_lock );
1059
1060     if( p_pic->i_status == READY_PICTURE )
1061     {
1062         /* Grr cannot destroy ready picture by myself so be sure vout won't like it */
1063         p_pic->date = 1;
1064     }
1065     else if( p_pic->i_refcount > 0 )
1066     {
1067         p_pic->i_status = DISPLAYED_PICTURE;
1068     }
1069     else
1070     {
1071         p_pic->i_status = DESTROYED_PICTURE;
1072         picture_CleanupQuant( p_pic );
1073         p_vout->i_heap_size--;
1074     }
1075
1076     vlc_mutex_unlock( &p_vout->picture_lock );
1077 }
1078 static void VoutFlushPicture( vout_thread_t *p_vout, mtime_t i_max_date )
1079 {
1080     int i;
1081     vlc_mutex_lock( &p_vout->picture_lock );
1082     for( i = 0; i < p_vout->render.i_pictures; i++ )
1083     {
1084         picture_t *p_pic = p_vout->render.pp_picture[i];
1085
1086         if( p_pic->i_status == READY_PICTURE ||
1087             p_pic->i_status == DISPLAYED_PICTURE )
1088         {
1089             /* We cannot change picture status if it is in READY_PICTURE state,
1090              * Just make sure they won't be displayed */
1091             if( p_pic->date > i_max_date )
1092                 p_pic->date = i_max_date;
1093         }
1094     }
1095     vlc_mutex_unlock( &p_vout->picture_lock );
1096 }
1097
1098 #if 0
1099 static void DecoderOptimizePtsDelay( decoder_t *p_dec )
1100 {
1101     input_thread_t *p_input = p_dec->p_owner->p_input;
1102     vout_thread_t *p_vout = p_dec->p_owner->p_vout;
1103     input_thread_private_t *p_priv = p_input->p;
1104
1105     picture_t *p_old = NULL;
1106     picture_t *p_young = NULL;
1107     int i;
1108
1109     /* Enable with --auto-adjust-pts-delay */
1110     if( !p_priv->pts_adjust.b_auto_adjust )
1111         return;
1112
1113     for( i = 0; i < I_RENDERPICTURES; i++ )
1114     {
1115         picture_t *p_pic = PP_RENDERPICTURE[i];
1116
1117         if( p_pic->i_status != READY_PICTURE )
1118             continue;
1119
1120         if( !p_old || p_pic->date < p_old->date )
1121             p_old = p_pic;
1122         if( !p_young || p_pic->date > p_young->date )
1123             p_young = p_pic;
1124     }
1125
1126     if( !p_young || !p_old )
1127         return;
1128
1129     /* Try to find if we can reduce the pts
1130      * This first draft is way too simple, and we can't say if the
1131      * algo will converge. It's also full of constants.
1132      * But this simple algo allows to reduce the latency
1133      * to the minimum.
1134      * The whole point of this, is to bypass the pts_delay set
1135      * by the access but also the delay arbitraly set by
1136      * the remote server.
1137      * Actually the remote server's muxer may set up a
1138      * pts<->dts delay in the muxed stream. That is
1139      * why we may end up in having a negative pts_delay,
1140      * to compensate that artificial delay. */
1141     const mtime_t i_buffer_length = p_young->date - p_old->date;
1142     int64_t i_pts_slide = 0;
1143     if( i_buffer_length < 10000 )
1144     {
1145         if( p_priv->pts_adjust.i_num_faulty > 10 )
1146         {
1147             i_pts_slide = __MAX(p_input->i_pts_delay *3 / 2, 10000);
1148             p_priv->pts_adjust.i_num_faulty = 0;
1149         }
1150         if( p_priv->pts_adjust.b_to_high )
1151         {
1152             p_priv->pts_adjust.b_to_high = !p_priv->pts_adjust.b_to_high;
1153             p_priv->pts_adjust.i_num_faulty = 0;
1154         }
1155         p_priv->pts_adjust.i_num_faulty++;
1156     }
1157     else if( i_buffer_length > 100000 )
1158     {
1159         if( p_priv->pts_adjust.i_num_faulty > 25 )
1160         {
1161             i_pts_slide = -i_buffer_length/2;
1162             p_priv->pts_adjust.i_num_faulty = 0;
1163         }
1164         if( p_priv->pts_adjust.b_to_high )
1165         {
1166             p_priv->pts_adjust.b_to_high = !p_priv->pts_adjust.b_to_high;
1167             p_priv->pts_adjust.i_num_faulty = 0;
1168         }
1169         p_priv->pts_adjust.i_num_faulty++;
1170     }
1171     if( i_pts_slide != 0 )
1172     {
1173         const mtime_t i_pts_delay_org = p_input->i_pts_delay;
1174
1175         p_input->i_pts_delay += i_pts_slide;
1176
1177         /* Don't play with the pts delay for more than -2<->3sec */
1178         if( p_input->i_pts_delay < -2000000 )
1179             p_input->i_pts_delay = -2000000;
1180         else if( p_input->i_pts_delay > 3000000 )
1181             p_input->i_pts_delay = 3000000;
1182         i_pts_slide = p_input->i_pts_delay - i_pts_delay_org;
1183
1184         msg_Dbg( p_input, "Sliding the pts by %dms pts delay at %dms picture buffer was %dms",
1185             (int)i_pts_slide/1000, (int)p_input->i_pts_delay/1000, (int)i_buffer_length/1000);
1186
1187         vlc_mutex_lock( &p_vout->picture_lock );
1188         /* Slide all the picture */
1189         for( i = 0; i < I_RENDERPICTURES; i++ )
1190             PP_RENDERPICTURE[i]->date += i_pts_slide;
1191         /* FIXME: slide aout/spu */
1192         vlc_mutex_unlock( &p_vout->picture_lock );
1193     }
1194 }
1195 #endif
1196
1197 static void DecoderDecodeVideo( decoder_t *p_dec, block_t *p_block )
1198 {
1199     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1200     input_thread_t *p_input = p_owner->p_input;
1201     picture_t      *p_pic;
1202     int i_lost = 0;
1203     int i_decoded = 0;
1204     int i_displayed = 0;
1205
1206     while( (p_pic = p_dec->pf_decode_video( p_dec, &p_block )) )
1207     {
1208         vout_thread_t  *p_vout = p_owner->p_vout;
1209         if( p_dec->b_die )
1210         {
1211             /* It prevent freezing VLC in case of broken decoder */
1212             VoutDisplayedPicture( p_vout, p_pic );
1213             if( p_block )
1214                 block_Release( p_block );
1215             break;
1216         }
1217
1218         i_decoded++;
1219
1220         if( p_pic->date < p_owner->i_preroll_end )
1221         {
1222             VoutDisplayedPicture( p_vout, p_pic );
1223             continue;
1224         }
1225
1226         if( p_owner->i_preroll_end > 0 )
1227         {
1228             msg_Dbg( p_dec, "End of video preroll" );
1229             if( p_vout )
1230                 VoutFlushPicture( p_vout, 1 );
1231             /* */
1232             p_owner->i_preroll_end = -1;
1233         }
1234
1235         if( p_dec->pf_get_cc &&
1236             ( !p_owner->p_packetizer || !p_owner->p_packetizer->pf_get_cc ) )
1237             DecoderGetCc( p_dec, p_dec );
1238
1239         bool b_reject;
1240         DecoderWaitUnpause( p_dec, &b_reject );
1241
1242         mtime_t i_ts_delay;
1243         mtime_t i_es_delay;
1244         DecoderGetDelays( p_dec, &i_ts_delay, &i_es_delay );
1245         int i_rate = INPUT_RATE_DEFAULT;
1246
1247         DecoderVoutBufferFixTs( p_pic, &i_rate, p_owner->p_clock, i_ts_delay, i_es_delay );
1248
1249         /* */
1250         const mtime_t i_max_date = mdate() + i_ts_delay +
1251             i_es_delay * i_rate / INPUT_RATE_DEFAULT + VOUT_BOGUS_DELAY;
1252
1253         if( !b_reject &&
1254             p_pic->date > 0 && p_pic->date < i_max_date )
1255         {
1256             if( i_rate != p_owner->i_last_rate  )
1257             {
1258                 /* Be sure to not display old picture after our own */
1259                 VoutFlushPicture( p_vout, p_pic->date );
1260                 p_owner->i_last_rate = i_rate;
1261             }
1262
1263             vout_DatePicture( p_vout, p_pic, p_pic->date );
1264
1265             /* Re-enable it but do it right this time */
1266             //DecoderOptimizePtsDelay( p_dec );
1267             vout_DisplayPicture( p_vout, p_pic );
1268         }
1269         else
1270         {
1271             if( p_pic->date <= 0 )
1272             {
1273                 msg_Warn( p_vout, "non-dated video buffer received" );
1274             }
1275             else
1276             {
1277                 msg_Warn( p_vout, "early picture skipped (%"PRId64")",
1278                           p_pic->date - mdate() );
1279             }
1280             i_lost++;
1281             VoutDisplayedPicture( p_vout, p_pic );
1282         }
1283         int i_tmp_display;
1284         int i_tmp_lost;
1285         vout_GetResetStatistic( p_vout, &i_tmp_display, &i_tmp_lost );
1286
1287         i_displayed += i_tmp_display;
1288         i_lost += i_tmp_lost;
1289     }
1290     if( i_decoded > 0 || i_lost > 0 || i_displayed > 0 )
1291     {
1292         vlc_mutex_lock( &p_input->p->counters.counters_lock );
1293
1294         stats_UpdateInteger( p_dec, p_input->p->counters.p_decoded_video,
1295                              i_decoded, NULL );
1296         stats_UpdateInteger( p_dec, p_input->p->counters.p_lost_pictures,
1297                              i_lost , NULL);
1298
1299         stats_UpdateInteger( p_dec, p_input->p->counters.p_displayed_pictures,
1300                              i_displayed, NULL);
1301
1302         vlc_mutex_unlock( &p_input->p->counters.counters_lock );
1303     }
1304 }
1305
1306 /* This function process a block for sout
1307  */
1308 static void DecoderProcessSout( decoder_t *p_dec, block_t *p_block )
1309 {
1310     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1311     const bool b_telx = p_dec->fmt_in.i_codec == VLC_FOURCC('t','e','l','x');
1312     block_t *p_sout_block;
1313
1314     while( ( p_sout_block =
1315                  p_dec->pf_packetize( p_dec, p_block ? &p_block : NULL ) ) )
1316     {
1317         if( !p_owner->p_sout_input )
1318         {
1319             es_format_Copy( &p_owner->sout, &p_dec->fmt_out );
1320
1321             p_owner->sout.i_group = p_dec->fmt_in.i_group;
1322             p_owner->sout.i_id = p_dec->fmt_in.i_id;
1323             if( p_dec->fmt_in.psz_language )
1324             {
1325                 if( p_owner->sout.psz_language )
1326                     free( p_owner->sout.psz_language );
1327                 p_owner->sout.psz_language =
1328                     strdup( p_dec->fmt_in.psz_language );
1329             }
1330
1331             p_owner->p_sout_input =
1332                 sout_InputNew( p_owner->p_sout,
1333                                &p_owner->sout );
1334
1335             if( p_owner->p_sout_input == NULL )
1336             {
1337                 msg_Err( p_dec, "cannot create packetizer output (%4.4s)",
1338                          (char *)&p_owner->sout.i_codec );
1339                 p_dec->b_error = true;
1340
1341                 while( p_sout_block )
1342                 {
1343                     block_t *p_next = p_sout_block->p_next;
1344                     block_Release( p_sout_block );
1345                     p_sout_block = p_next;
1346                 }
1347                 break;
1348             }
1349         }
1350
1351         while( p_sout_block )
1352         {
1353             block_t *p_next = p_sout_block->p_next;
1354
1355             p_sout_block->p_next = NULL;
1356
1357             DecoderWaitUnpause( p_dec, NULL );
1358
1359             mtime_t i_ts_delay;
1360             mtime_t i_es_delay;
1361             DecoderGetDelays( p_dec, &i_ts_delay, &i_es_delay );
1362
1363             DecoderSoutBufferFixTs( p_sout_block, p_owner->p_clock,
1364                                     i_ts_delay, i_es_delay, b_telx );
1365
1366             sout_InputSendBuffer( p_owner->p_sout_input,
1367                                   p_sout_block );
1368
1369             p_sout_block = p_next;
1370         }
1371
1372         /* For now it's enough, as only sout impact on this flag */
1373         if( p_owner->p_sout->i_out_pace_nocontrol > 0 &&
1374             p_owner->p_input->p->b_out_pace_control )
1375         {
1376             msg_Dbg( p_dec, "switching to sync mode" );
1377             p_owner->p_input->p->b_out_pace_control = false;
1378         }
1379         else if( p_owner->p_sout->i_out_pace_nocontrol <= 0 &&
1380                  !p_owner->p_input->p->b_out_pace_control )
1381         {
1382             msg_Dbg( p_dec, "switching to async mode" );
1383             p_owner->p_input->p->b_out_pace_control = true;
1384         }
1385     }
1386 }
1387
1388 /* This function process a video block
1389  */
1390 static void DecoderProcessVideo( decoder_t *p_dec, block_t *p_block, bool b_flush )
1391 {
1392     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1393
1394     if( p_owner->p_packetizer )
1395     {
1396         block_t *p_packetized_block;
1397         decoder_t *p_packetizer = p_owner->p_packetizer;
1398
1399         while( (p_packetized_block =
1400                 p_packetizer->pf_packetize( p_packetizer, p_block ? &p_block : NULL )) )
1401         {
1402             if( p_packetizer->fmt_out.i_extra && !p_dec->fmt_in.i_extra )
1403             {
1404                 es_format_Clean( &p_dec->fmt_in );
1405                 es_format_Copy( &p_dec->fmt_in, &p_packetizer->fmt_out );
1406             }
1407             if( p_packetizer->pf_get_cc )
1408                 DecoderGetCc( p_dec, p_packetizer );
1409
1410             while( p_packetized_block )
1411             {
1412                 block_t *p_next = p_packetized_block->p_next;
1413                 p_packetized_block->p_next = NULL;
1414
1415                 DecoderDecodeVideo( p_dec, p_packetized_block );
1416
1417                 p_packetized_block = p_next;
1418             }
1419         }
1420     }
1421     else if( p_block )
1422     {
1423         DecoderDecodeVideo( p_dec, p_block );
1424     }
1425
1426     if( b_flush && p_owner->p_vout )
1427         VoutFlushPicture( p_owner->p_vout, 1 );
1428 }
1429
1430 /* This function process a audio block
1431  */
1432 static void DecoderProcessAudio( decoder_t *p_dec, block_t *p_block, bool b_flush )
1433 {
1434     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1435
1436     if( b_flush && p_owner->p_aout && p_owner->p_aout_input )
1437     {
1438         // TODO flush
1439     }
1440
1441     if( p_owner->p_packetizer )
1442     {
1443         block_t *p_packetized_block;
1444         decoder_t *p_packetizer = p_owner->p_packetizer;
1445
1446         while( (p_packetized_block =
1447                 p_packetizer->pf_packetize( p_packetizer, p_block ? &p_block : NULL )) )
1448         {
1449             if( p_packetizer->fmt_out.i_extra && !p_dec->fmt_in.i_extra )
1450             {
1451                 es_format_Clean( &p_dec->fmt_in );
1452                 es_format_Copy( &p_dec->fmt_in, &p_packetizer->fmt_out );
1453             }
1454
1455             while( p_packetized_block )
1456             {
1457                 block_t *p_next = p_packetized_block->p_next;
1458                 p_packetized_block->p_next = NULL;
1459
1460                 DecoderDecodeAudio( p_dec, p_packetized_block );
1461
1462                 p_packetized_block = p_next;
1463             }
1464         }
1465     }
1466     else if( p_block )
1467     {
1468         DecoderDecodeAudio( p_dec, p_block );
1469     }
1470 }
1471
1472 /* This function process a subtitle block
1473  */
1474 static void DecoderProcessSpu( decoder_t *p_dec, block_t *p_block, bool b_flush )
1475 {
1476     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1477     const bool b_telx = p_dec->fmt_in.i_codec == VLC_FOURCC('t','e','l','x');
1478
1479     input_thread_t *p_input = p_owner->p_input;
1480     vout_thread_t *p_vout;
1481     subpicture_t *p_spu;
1482
1483     if( b_flush && p_owner->p_spu_vout )
1484     {
1485         p_vout = vlc_object_find( p_dec, VLC_OBJECT_VOUT, FIND_ANYWHERE );
1486
1487         if( p_vout && p_owner->p_spu_vout == p_vout )
1488             spu_Control( p_vout->p_spu, SPU_CHANNEL_CLEAR,
1489                          p_owner->i_spu_channel );
1490
1491         if( p_vout )
1492             vlc_object_release( p_vout );
1493     }
1494
1495     while( (p_spu = p_dec->pf_decode_sub( p_dec, p_block ? &p_block : NULL ) ) )
1496     {
1497         vlc_mutex_lock( &p_input->p->counters.counters_lock );
1498         stats_UpdateInteger( p_dec, p_input->p->counters.p_decoded_sub, 1, NULL );
1499         vlc_mutex_unlock( &p_input->p->counters.counters_lock );
1500
1501         p_vout = vlc_object_find( p_dec, VLC_OBJECT_VOUT, FIND_ANYWHERE );
1502         if( p_vout && p_owner->p_spu_vout == p_vout )
1503         {
1504             /* Preroll does not work very well with subtitle */
1505             if( p_spu->i_start > 0 &&
1506                 p_spu->i_start < p_owner->i_preroll_end &&
1507                 ( p_spu->i_stop <= 0 || p_spu->i_stop < p_owner->i_preroll_end ) )
1508             {
1509                 subpicture_Delete( p_spu );
1510             }
1511             else
1512             {
1513                 bool b_reject;
1514                 DecoderWaitUnpause( p_dec, &b_reject );
1515
1516                 mtime_t i_ts_delay;
1517                 mtime_t i_es_delay;
1518                 DecoderGetDelays( p_dec, &i_ts_delay, &i_es_delay );
1519
1520                 DecoderSpuBufferFixTs( p_spu, p_owner->p_clock, i_ts_delay, i_es_delay, b_telx );
1521                 if( !b_reject )
1522                     spu_DisplaySubpicture( p_vout->p_spu, p_spu );
1523                 else
1524                     subpicture_Delete( p_spu );
1525             }
1526         }
1527         else
1528         {
1529             subpicture_Delete( p_spu );
1530         }
1531         if( p_vout )
1532             vlc_object_release( p_vout );
1533     }
1534 }
1535
1536 /**
1537  * Decode a block
1538  *
1539  * \param p_dec the decoder object
1540  * \param p_block the block to decode
1541  * \return VLC_SUCCESS or an error code
1542  */
1543 static int DecoderProcess( decoder_t *p_dec, block_t *p_block )
1544 {
1545     decoder_owner_sys_t *p_owner = (decoder_owner_sys_t *)p_dec->p_owner;
1546     const bool b_flush_request = p_block && (p_block->i_flags & BLOCK_FLAG_CORE_FLUSH);
1547
1548     if( p_block && p_block->i_buffer <= 0 )
1549     {
1550         assert( !b_flush_request );
1551         block_Release( p_block );
1552         return VLC_SUCCESS;
1553     }
1554
1555 #ifdef ENABLE_SOUT
1556     if( p_dec->i_object_type == VLC_OBJECT_PACKETIZER )
1557     {
1558         if( p_block )
1559             p_block->i_flags &= ~BLOCK_FLAG_CORE_PRIVATE_MASK;
1560
1561         DecoderProcessSout( p_dec, p_block );
1562     }
1563     else
1564 #endif
1565     {
1566         bool b_flush = false;
1567
1568         if( p_block )
1569         {
1570             const bool b_flushing = p_owner->i_preroll_end == INT64_MAX;
1571             DecoderUpdatePreroll( &p_owner->i_preroll_end, p_block );
1572
1573             b_flush = !b_flushing && b_flush_request;
1574
1575             p_block->i_flags &= ~BLOCK_FLAG_CORE_PRIVATE_MASK;
1576         }
1577
1578         if( p_dec->fmt_in.i_cat == AUDIO_ES )
1579         {
1580             DecoderProcessAudio( p_dec, p_block, b_flush );
1581         }
1582         else if( p_dec->fmt_in.i_cat == VIDEO_ES )
1583         {
1584             DecoderProcessVideo( p_dec, p_block, b_flush );
1585         }
1586         else if( p_dec->fmt_in.i_cat == SPU_ES )
1587         {
1588             DecoderProcessSpu( p_dec, p_block, b_flush );
1589         }
1590         else
1591         {
1592             msg_Err( p_dec, "unknown ES format" );
1593             p_dec->b_error = true;
1594         }
1595     }
1596
1597     /* */
1598     if( b_flush_request )
1599         DecoderSignalFlushed( p_dec );
1600
1601     return p_dec->b_error ? VLC_EGENERIC : VLC_SUCCESS;
1602 }
1603
1604 /**
1605  * Destroys a decoder object
1606  *
1607  * \param p_dec the decoder object
1608  * \return nothing
1609  */
1610 static void DeleteDecoder( decoder_t * p_dec )
1611 {
1612     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1613
1614     msg_Dbg( p_dec, "killing decoder fourcc `%4.4s', %u PES in FIFO",
1615              (char*)&p_dec->fmt_in.i_codec,
1616              (unsigned)block_FifoCount( p_owner->p_fifo ) );
1617
1618     /* Free all packets still in the decoder fifo. */
1619     block_FifoEmpty( p_owner->p_fifo );
1620     block_FifoRelease( p_owner->p_fifo );
1621
1622     /* Cleanup */
1623     if( p_owner->p_aout_input )
1624         aout_DecDelete( p_owner->p_aout, p_owner->p_aout_input );
1625     if( p_owner->p_aout )
1626     {
1627         vlc_object_release( p_owner->p_aout );
1628         p_owner->p_aout = NULL;
1629     }
1630     if( p_owner->p_vout )
1631     {
1632         int i_pic;
1633
1634 #define p_pic p_owner->p_vout->render.pp_picture[i_pic]
1635         /* Hack to make sure all the the pictures are freed by the decoder */
1636         for( i_pic = 0; i_pic < p_owner->p_vout->render.i_pictures;
1637              i_pic++ )
1638         {
1639             if( p_pic->i_status == RESERVED_PICTURE )
1640                 vout_DestroyPicture( p_owner->p_vout, p_pic );
1641             if( p_pic->i_refcount > 0 )
1642                 vout_UnlinkPicture( p_owner->p_vout, p_pic );
1643         }
1644 #undef p_pic
1645
1646         /* We are about to die. Reattach video output to p_vlc. */
1647         vout_Request( p_dec, p_owner->p_vout, NULL );
1648         var_SetBool( p_owner->p_input, "intf-change-vout", true );
1649     }
1650
1651 #ifdef ENABLE_SOUT
1652     if( p_owner->p_sout_input )
1653     {
1654         sout_InputDelete( p_owner->p_sout_input );
1655         es_format_Clean( &p_owner->sout );
1656     }
1657 #endif
1658
1659     if( p_dec->fmt_in.i_cat == SPU_ES )
1660     {
1661         vout_thread_t *p_vout;
1662
1663         p_vout = vlc_object_find( p_dec, VLC_OBJECT_VOUT, FIND_ANYWHERE );
1664         if( p_vout && p_owner->p_spu_vout == p_vout )
1665         {
1666             spu_Control( p_vout->p_spu, SPU_CHANNEL_CLEAR,
1667                          p_owner->i_spu_channel );
1668             vlc_object_release( p_vout );
1669         }
1670     }
1671
1672     es_format_Clean( &p_dec->fmt_in );
1673     es_format_Clean( &p_dec->fmt_out );
1674
1675     if( p_owner->p_packetizer )
1676     {
1677         module_unneed( p_owner->p_packetizer,
1678                        p_owner->p_packetizer->p_module );
1679         es_format_Clean( &p_owner->p_packetizer->fmt_in );
1680         es_format_Clean( &p_owner->p_packetizer->fmt_out );
1681         vlc_object_detach( p_owner->p_packetizer );
1682         vlc_object_release( p_owner->p_packetizer );
1683     }
1684
1685     vlc_cond_destroy( &p_owner->wait );
1686     vlc_mutex_destroy( &p_owner->lock );
1687
1688     vlc_object_detach( p_dec );
1689
1690     free( p_owner );
1691 }
1692
1693 /*****************************************************************************
1694  * Buffers allocation callbacks for the decoders
1695  *****************************************************************************/
1696 static aout_buffer_t *aout_new_buffer( decoder_t *p_dec, int i_samples )
1697 {
1698     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1699     aout_buffer_t *p_buffer;
1700
1701     if( p_owner->p_aout_input != NULL &&
1702         ( p_dec->fmt_out.audio.i_rate != p_owner->audio.i_rate ||
1703           p_dec->fmt_out.audio.i_original_channels !=
1704               p_owner->audio.i_original_channels ||
1705           p_dec->fmt_out.audio.i_bytes_per_frame !=
1706               p_owner->audio.i_bytes_per_frame ) )
1707     {
1708         aout_input_t *p_aout_input = p_owner->p_aout_input;
1709
1710         /* Parameters changed, restart the aout */
1711         vlc_mutex_lock( &p_owner->lock );
1712
1713         p_owner->p_aout_input = NULL;
1714         aout_DecDelete( p_owner->p_aout, p_aout_input );
1715
1716         vlc_mutex_unlock( &p_owner->lock );
1717     }
1718
1719     if( p_owner->p_aout_input == NULL )
1720     {
1721         const int i_force_dolby = config_GetInt( p_dec, "force-dolby-surround" );
1722         audio_sample_format_t format;
1723         aout_input_t *p_aout_input;
1724         aout_instance_t *p_aout;
1725
1726         p_dec->fmt_out.audio.i_format = p_dec->fmt_out.i_codec;
1727         p_owner->audio = p_dec->fmt_out.audio;
1728
1729         memcpy( &format, &p_owner->audio, sizeof( audio_sample_format_t ) );
1730         if ( i_force_dolby && (format.i_original_channels&AOUT_CHAN_PHYSMASK)
1731                                     == (AOUT_CHAN_LEFT|AOUT_CHAN_RIGHT) )
1732         {
1733             if ( i_force_dolby == 1 )
1734             {
1735                 format.i_original_channels = format.i_original_channels |
1736                                              AOUT_CHAN_DOLBYSTEREO;
1737             }
1738             else /* i_force_dolby == 2 */
1739             {
1740                 format.i_original_channels = format.i_original_channels &
1741                                              ~AOUT_CHAN_DOLBYSTEREO;
1742             }
1743         }
1744
1745         p_aout = p_owner->p_aout;
1746         p_aout_input = aout_DecNew( p_dec, &p_aout,
1747                                     &format, &p_dec->fmt_out.audio_replay_gain );
1748
1749         vlc_mutex_lock( &p_owner->lock );
1750         p_owner->p_aout = p_aout;
1751         p_owner->p_aout_input = p_aout_input;
1752         vlc_mutex_unlock( &p_owner->lock );
1753
1754         if( p_owner->p_aout_input == NULL )
1755         {
1756             msg_Err( p_dec, "failed to create audio output" );
1757             p_dec->b_error = true;
1758             return NULL;
1759         }
1760         p_dec->fmt_out.audio.i_bytes_per_frame =
1761             p_owner->audio.i_bytes_per_frame;
1762     }
1763
1764     p_buffer = aout_DecNewBuffer( p_owner->p_aout_input, i_samples );
1765
1766     return p_buffer;
1767 }
1768
1769 static void aout_del_buffer( decoder_t *p_dec, aout_buffer_t *p_buffer )
1770 {
1771     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1772
1773     aout_DecDeleteBuffer( p_owner->p_aout,
1774                           p_owner->p_aout_input, p_buffer );
1775 }
1776
1777
1778 int vout_CountPictureAvailable( vout_thread_t *p_vout );
1779
1780 static picture_t *vout_new_buffer( decoder_t *p_dec )
1781 {
1782     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1783
1784     if( p_owner->p_vout == NULL ||
1785         p_dec->fmt_out.video.i_width != p_owner->video.i_width ||
1786         p_dec->fmt_out.video.i_height != p_owner->video.i_height ||
1787         p_dec->fmt_out.video.i_chroma != p_owner->video.i_chroma ||
1788         p_dec->fmt_out.video.i_aspect != p_owner->video.i_aspect )
1789     {
1790         vout_thread_t *p_vout;
1791
1792         if( !p_dec->fmt_out.video.i_width ||
1793             !p_dec->fmt_out.video.i_height )
1794         {
1795             /* Can't create a new vout without display size */
1796             return NULL;
1797         }
1798
1799         if( !p_dec->fmt_out.video.i_visible_width ||
1800             !p_dec->fmt_out.video.i_visible_height )
1801         {
1802             if( p_dec->fmt_in.video.i_visible_width &&
1803                 p_dec->fmt_in.video.i_visible_height )
1804             {
1805                 p_dec->fmt_out.video.i_visible_width =
1806                     p_dec->fmt_in.video.i_visible_width;
1807                 p_dec->fmt_out.video.i_visible_height =
1808                     p_dec->fmt_in.video.i_visible_height;
1809             }
1810             else
1811             {
1812                 p_dec->fmt_out.video.i_visible_width =
1813                     p_dec->fmt_out.video.i_width;
1814                 p_dec->fmt_out.video.i_visible_height =
1815                     p_dec->fmt_out.video.i_height;
1816             }
1817         }
1818
1819         if( p_dec->fmt_out.video.i_visible_height == 1088 &&
1820             var_CreateGetBool( p_dec, "hdtv-fix" ) )
1821         {
1822             p_dec->fmt_out.video.i_visible_height = 1080;
1823             p_dec->fmt_out.video.i_sar_num *= 135;
1824             p_dec->fmt_out.video.i_sar_den *= 136;
1825             msg_Warn( p_dec, "Fixing broken HDTV stream (display_height=1088)");
1826         }
1827
1828         if( !p_dec->fmt_out.video.i_sar_num ||
1829             !p_dec->fmt_out.video.i_sar_den )
1830         {
1831             p_dec->fmt_out.video.i_sar_num = p_dec->fmt_out.video.i_aspect *
1832               p_dec->fmt_out.video.i_visible_height;
1833
1834             p_dec->fmt_out.video.i_sar_den = VOUT_ASPECT_FACTOR *
1835               p_dec->fmt_out.video.i_visible_width;
1836         }
1837
1838         vlc_ureduce( &p_dec->fmt_out.video.i_sar_num,
1839                      &p_dec->fmt_out.video.i_sar_den,
1840                      p_dec->fmt_out.video.i_sar_num,
1841                      p_dec->fmt_out.video.i_sar_den, 50000 );
1842
1843         p_dec->fmt_out.video.i_chroma = p_dec->fmt_out.i_codec;
1844         p_owner->video = p_dec->fmt_out.video;
1845
1846         vlc_mutex_lock( &p_owner->lock );
1847         p_vout = p_owner->p_vout;
1848         p_owner->p_vout = NULL;
1849         vlc_mutex_unlock( &p_owner->lock );
1850
1851         p_vout = vout_Request( p_dec, p_vout, &p_dec->fmt_out.video );
1852
1853         vlc_mutex_lock( &p_owner->lock );
1854         p_owner->p_vout = p_vout;
1855         vlc_mutex_unlock( &p_owner->lock );
1856
1857         var_SetBool( p_owner->p_input, "intf-change-vout", true );
1858         if( p_vout == NULL )
1859         {
1860             msg_Err( p_dec, "failed to create video output" );
1861             p_dec->b_error = true;
1862             return NULL;
1863         }
1864
1865         if( p_owner->video.i_rmask )
1866             p_owner->p_vout->render.i_rmask = p_owner->video.i_rmask;
1867         if( p_owner->video.i_gmask )
1868             p_owner->p_vout->render.i_gmask = p_owner->video.i_gmask;
1869         if( p_owner->video.i_bmask )
1870             p_owner->p_vout->render.i_bmask = p_owner->video.i_bmask;
1871     }
1872
1873     /* Get a new picture
1874      */
1875     for( ;; )
1876     {
1877         picture_t *p_picture;
1878         int i_pic, i_ready_pic;
1879
1880         if( p_dec->b_die || p_dec->b_error )
1881             return NULL;
1882
1883         /* The video filter chain required that there is always 1 free buffer
1884          * that it will use as temporary one. It will release the temporary
1885          * buffer once its work is done, so this check is safe even if we don't
1886          * lock around both count() and create().
1887          */
1888         if( vout_CountPictureAvailable( p_owner->p_vout ) >= 2 )
1889         {
1890             p_picture = vout_CreatePicture( p_owner->p_vout, 0, 0, 0 );
1891             if( p_picture )
1892                 return p_picture;
1893         }
1894
1895         if( DecoderIsFlushing( p_dec ) )
1896             return NULL;
1897
1898         /* Check the decoder doesn't leak pictures */
1899         for( i_pic = 0, i_ready_pic = 0; i_pic < p_owner->p_vout->render.i_pictures; i_pic++ )
1900         {
1901             const picture_t *p_pic = p_owner->p_vout->render.pp_picture[i_pic];
1902
1903             if( p_pic->i_status == READY_PICTURE )
1904             {
1905                 i_ready_pic++;
1906                 /* If we have at least 2 ready pictures, wait for the vout thread to
1907                  * process one */
1908                 if( i_ready_pic >= 2 )
1909                     break;
1910
1911                 continue;
1912             }
1913
1914             if( p_pic->i_status == DISPLAYED_PICTURE )
1915             {
1916                 /* If at least one displayed picture is not referenced
1917                  * let vout free it */
1918                 if( p_pic->i_refcount == 0 )
1919                     break;
1920             }
1921         }
1922
1923         if( i_pic == p_owner->p_vout->render.i_pictures )
1924         {
1925             /* Too many pictures are still referenced, there is probably a bug
1926              * with the decoder */
1927             msg_Err( p_dec, "decoder is leaking pictures, resetting the heap" );
1928
1929             /* Just free all the pictures */
1930             for( i_pic = 0; i_pic < p_owner->p_vout->render.i_pictures; i_pic++ )
1931             {
1932                 picture_t *p_pic = p_owner->p_vout->render.pp_picture[i_pic];
1933
1934                 if( p_pic->i_status == RESERVED_PICTURE )
1935                     vout_DestroyPicture( p_owner->p_vout, p_pic );
1936                 if( p_pic->i_refcount > 0 )
1937                     vout_UnlinkPicture( p_owner->p_vout, p_pic );
1938             }
1939         }
1940
1941         msleep( VOUT_OUTMEM_SLEEP );
1942     }
1943 }
1944
1945 static void vout_del_buffer( decoder_t *p_dec, picture_t *p_pic )
1946 {
1947     VoutDisplayedPicture( p_dec->p_owner->p_vout, p_pic );
1948 }
1949
1950 static void vout_link_picture( decoder_t *p_dec, picture_t *p_pic )
1951 {
1952     vout_LinkPicture( p_dec->p_owner->p_vout, p_pic );
1953 }
1954
1955 static void vout_unlink_picture( decoder_t *p_dec, picture_t *p_pic )
1956 {
1957     vout_UnlinkPicture( p_dec->p_owner->p_vout, p_pic );
1958 }
1959
1960 static subpicture_t *spu_new_buffer( decoder_t *p_dec )
1961 {
1962     decoder_owner_sys_t *p_owner = p_dec->p_owner;
1963     vout_thread_t *p_vout = NULL;
1964     subpicture_t *p_subpic;
1965     int i_attempts = 30;
1966
1967     while( i_attempts-- )
1968     {
1969         if( p_dec->b_die || p_dec->b_error )
1970             break;
1971
1972         p_vout = vlc_object_find( p_dec, VLC_OBJECT_VOUT, FIND_ANYWHERE );
1973         if( p_vout )
1974             break;
1975
1976         msleep( VOUT_DISPLAY_DELAY );
1977     }
1978
1979     if( !p_vout )
1980     {
1981         msg_Warn( p_dec, "no vout found, dropping subpicture" );
1982         return NULL;
1983     }
1984
1985     if( p_owner->p_spu_vout != p_vout )
1986     {
1987         spu_Control( p_vout->p_spu, SPU_CHANNEL_REGISTER,
1988                      &p_owner->i_spu_channel );
1989         p_owner->i_spu_order = 0;
1990         p_owner->p_spu_vout = p_vout;
1991     }
1992
1993     p_subpic = subpicture_New();
1994     if( p_subpic )
1995     {
1996         p_subpic->i_channel = p_owner->i_spu_channel;
1997         p_subpic->i_order = p_owner->i_spu_order++;
1998         p_subpic->b_subtitle = true;
1999     }
2000
2001     vlc_object_release( p_vout );
2002
2003     return p_subpic;
2004 }
2005
2006 static void spu_del_buffer( decoder_t *p_dec, subpicture_t *p_subpic )
2007 {
2008     decoder_owner_sys_t *p_owner = p_dec->p_owner;
2009     vout_thread_t *p_vout = NULL;
2010
2011     p_vout = vlc_object_find( p_dec, VLC_OBJECT_VOUT, FIND_ANYWHERE );
2012     if( !p_vout || p_owner->p_spu_vout != p_vout )
2013     {
2014         if( p_vout )
2015             vlc_object_release( p_vout );
2016         msg_Warn( p_dec, "no vout found, leaking subpicture" );
2017         return;
2018     }
2019
2020     subpicture_Delete( p_subpic );
2021
2022     vlc_object_release( p_vout );
2023 }
2024