OSDN Git Service

disable asserts in libdvdnav except when configured with --debug=max
[handbrake-jp/handbrake-jp-git.git] / libhb / reader.c
1 /* $Id: reader.c,v 1.21 2005/11/25 15:05:25 titer Exp $
2
3    This file is part of the HandBrake source code.
4    Homepage: <http://handbrake.fr/>.
5    It may be used under the terms of the GNU General Public License. */
6
7 #include "hb.h"
8
9 typedef struct
10 {
11     double average; // average time between packets
12     int64_t last;   // last timestamp seen on this stream
13     int id;         // stream id
14     int is_audio;   // != 0 if this is an audio stream
15 } stream_timing_t;
16
17 typedef struct
18 {
19     hb_job_t     * job;
20     hb_title_t   * title;
21     volatile int * die;
22
23     hb_dvd_t     * dvd;
24     hb_stream_t  * stream;
25
26     stream_timing_t *stream_timing;
27     int64_t        scr_offset;
28     hb_psdemux_t   demux;
29     int            scr_changes;
30     uint32_t       sequence;
31     uint8_t        st_slots;        // size (in slots) of stream_timing array
32     uint8_t        saw_video;       // != 0 if we've seen video
33     uint8_t        saw_audio;       // != 0 if we've seen audio
34
35     int            start_found;     // found pts_to_start point
36     uint64_t       st_first;
37 } hb_reader_t;
38
39 /***********************************************************************
40  * Local prototypes
41  **********************************************************************/
42 static void        ReaderFunc( void * );
43 static hb_fifo_t ** GetFifoForId( hb_job_t * job, int id );
44 static void UpdateState( hb_reader_t  * r, int64_t start);
45
46 /***********************************************************************
47  * hb_reader_init
48  ***********************************************************************
49  *
50  **********************************************************************/
51 hb_thread_t * hb_reader_init( hb_job_t * job )
52 {
53     hb_reader_t * r;
54
55     r = calloc( sizeof( hb_reader_t ), 1 );
56
57     r->job   = job;
58     r->title = job->title;
59     r->die   = job->die;
60     r->sequence = 0;
61
62     r->st_slots = 4;
63     r->stream_timing = calloc( sizeof(stream_timing_t), r->st_slots );
64     r->stream_timing[0].id = r->title->video_id;
65     r->stream_timing[0].average = 90000. * (double)job->vrate_base /
66                                            (double)job->vrate;
67     r->stream_timing[0].last = -r->stream_timing[0].average;
68     r->stream_timing[1].id = -1;
69
70     if ( !job->pts_to_start )
71         r->start_found = 1;
72
73     return hb_thread_init( "reader", ReaderFunc, r,
74                            HB_NORMAL_PRIORITY );
75 }
76
77 static void push_buf( const hb_reader_t *r, hb_fifo_t *fifo, hb_buffer_t *buf )
78 {
79     while ( !*r->die && !r->job->done )
80     {
81         if ( hb_fifo_full_wait( fifo ) )
82         {
83             hb_fifo_push( fifo, buf );
84             break;
85         }
86     }
87 }
88
89 static int is_audio( hb_reader_t *r, int id )
90 {
91     int i;
92     hb_audio_t *audio;
93
94     for( i = 0; ( audio = hb_list_item( r->title->list_audio, i ) ); ++i )
95     {
96         if ( audio->id == id )
97         {
98             return 1;
99         }
100     }
101     return 0;
102 }
103
104 // The MPEG STD (Standard Target Decoder) essentially requires that we keep
105 // per-stream timing so that when there's a timing discontinuity we can
106 // seemlessly join packets on either side of the discontinuity. This join
107 // requires that we know the timestamp of the previous packet and the
108 // average inter-packet time (since we position the new packet at the end
109 // of the previous packet). The next four routines keep track of this
110 // per-stream timing.
111
112 // find the per-stream timing state for 'buf'
113
114 static stream_timing_t *find_st( hb_reader_t *r, const hb_buffer_t *buf )
115 {
116     stream_timing_t *st = r->stream_timing;
117     for ( ; st->id != -1; ++st )
118     {
119         if ( st->id == buf->id )
120             return st;
121     }
122     return NULL;
123 }
124
125 // find or create the per-stream timing state for 'buf'
126
127 static stream_timing_t *id_to_st( hb_reader_t *r, const hb_buffer_t *buf )
128 {
129     stream_timing_t *st = r->stream_timing;
130     while ( st->id != buf->id && st->id != -1)
131     {
132         ++st;
133     }
134     // if we haven't seen this stream add it.
135     if ( st->id == -1 )
136     {
137         // we keep the steam timing info in an array with some power-of-two
138         // number of slots. If we don't have two slots left (one for our new
139         // entry plus one for the "-1" eol) we need to expand the array.
140         int slot = st - r->stream_timing;
141         if ( slot + 1 >= r->st_slots )
142         {
143             r->st_slots *= 2;
144             r->stream_timing = realloc( r->stream_timing, r->st_slots *
145                                         sizeof(*r->stream_timing) );
146             st = r->stream_timing + slot;
147         }
148         st->id = buf->id;
149         st->average = 30.*90.;
150         if ( r->saw_video )
151             st->last = buf->renderOffset - st->average;
152         else
153             st->last = -st->average;
154         if ( ( st->is_audio = is_audio( r, buf->id ) ) != 0 )
155         {
156             r->saw_audio = 1;
157         }
158         st[1].id = -1;
159     }
160     return st;
161 }
162
163 // update the average inter-packet time of the stream associated with 'buf'
164 // using a recursive low-pass filter with a 16 packet time constant.
165
166 static void update_ipt( hb_reader_t *r, const hb_buffer_t *buf )
167 {
168     stream_timing_t *st = id_to_st( r, buf );
169     double dt = buf->renderOffset - st->last;
170     st->average += ( dt - st->average ) * (1./32.);
171     st->last = buf->renderOffset;
172 }
173
174 // use the per-stream state associated with 'buf' to compute a new scr_offset
175 // such that 'buf' will follow the previous packet of this stream separated
176 // by the average packet time of the stream.
177
178 static void new_scr_offset( hb_reader_t *r, hb_buffer_t *buf )
179 {
180     stream_timing_t *st = id_to_st( r, buf );
181     int64_t nxt = st->last + st->average;
182     r->scr_offset = buf->renderOffset - nxt;
183     buf->renderOffset = nxt;
184     r->scr_changes = r->demux.scr_changes;
185     st->last = buf->renderOffset;
186 }
187
188 /***********************************************************************
189  * ReaderFunc
190  ***********************************************************************
191  *
192  **********************************************************************/
193 static void ReaderFunc( void * _r )
194 {
195     hb_reader_t  * r = _r;
196     hb_fifo_t   ** fifos;
197     hb_buffer_t  * buf;
198     hb_list_t    * list;
199     int            n;
200     int            chapter = -1;
201     int            chapter_end = r->job->chapter_end;
202
203     if ( r->title->type == HB_DVD_TYPE )
204     {
205         if ( !( r->dvd = hb_dvd_init( r->title->path ) ) )
206             return;
207     }
208     else if ( r->title->type == HB_STREAM_TYPE )
209     {
210         if ( !( r->stream = hb_stream_open( r->title->path, r->title ) ) )
211             return;
212     }
213     else
214     {
215         // Unknown type, should never happen
216         return;
217     }
218
219     hb_buffer_t *ps = hb_buffer_init( HB_DVD_READ_BUFFER_SIZE );
220     if (r->dvd)
221     {
222         /*
223          * XXX this code is a temporary hack that should go away if/when
224          *     chapter merging goes away in libhb/dvd.c
225          * map the start and end chapter numbers to on-media chapter
226          * numbers since chapter merging could cause the handbrake numbers
227          * to diverge from the media numbers and, if our chapter_end is after
228          * a media chapter that got merged, we'll stop ripping too early.
229          */
230         int start = r->job->chapter_start;
231         hb_chapter_t *chap = hb_list_item( r->title->list_chapter, chapter_end - 1 );
232
233         chapter_end = chap->index;
234         if (start > 1)
235         {
236            chap = hb_list_item( r->title->list_chapter, start - 1 );
237            start = chap->index;
238         }
239         /* end chapter mapping XXX */
240
241         if( !hb_dvd_start( r->dvd, r->title, start ) )
242         {
243             hb_dvd_close( &r->dvd );
244             hb_buffer_close( &ps );
245             return;
246         }
247         if (r->job->angle)
248         {
249             hb_dvd_set_angle( r->dvd, r->job->angle );
250         }
251
252         if ( r->job->start_at_preview )
253         {
254             // XXX code from DecodePreviews - should go into its own routine
255             hb_dvd_seek( r->dvd, (float)r->job->start_at_preview /
256                          ( r->job->seek_points ? ( r->job->seek_points + 1.0 ) : 11.0 ) );
257         }
258     }
259     else if ( r->stream && r->job->start_at_preview )
260     {
261         
262         // XXX code from DecodePreviews - should go into its own routine
263         hb_stream_seek( r->stream, (float)( r->job->start_at_preview - 1 ) /
264                         ( r->job->seek_points ? ( r->job->seek_points + 1.0 ) : 11.0 ) );
265
266     } 
267     else if ( r->stream && r->job->pts_to_start )
268     {
269         
270         // Find out what the first timestamp of the stream is
271         // and then seek to the appropriate offset from it
272         if ( hb_stream_read( r->stream, ps ) )
273         {
274             if ( ps->start > 0 )
275                 r->job->pts_to_start += ps->start;
276         }
277         
278         if ( hb_stream_seek_ts( r->stream, r->job->pts_to_start ) >= 0 )
279         {
280             // Seek takes us to the nearest I-frame before the timestamp
281             // that we want.  So we will retrieve the start time of the
282             // first packet we get, subtract that from pts_to_start, and
283             // inspect the reset of the frames in sync.
284             r->start_found = 2;
285         }
286
287     } 
288     else if( r->stream )
289     {
290         /*
291          * Standard stream, seek to the starting chapter, if set, and track the
292          * end chapter so that we end at the right time.
293          */
294         int start = r->job->chapter_start;
295         hb_chapter_t *chap = hb_list_item( r->title->list_chapter, chapter_end - 1 );
296         
297         chapter_end = chap->index;
298         if (start > 1)
299         {
300             chap = hb_list_item( r->title->list_chapter, start - 1 );
301             start = chap->index;
302         }
303         
304         /*
305          * Seek to the start chapter.
306          */
307         hb_stream_seek_chapter( r->stream, start );
308     }
309
310     list  = hb_list_init();
311
312     while( !*r->die && !r->job->done )
313     {
314         if (r->dvd)
315             chapter = hb_dvd_chapter( r->dvd );
316         else if (r->stream)
317             chapter = hb_stream_chapter( r->stream );
318
319         if( chapter < 0 )
320         {
321             hb_log( "reader: end of the title reached" );
322             break;
323         }
324         if( chapter > chapter_end )
325         {
326             hb_log( "reader: end of chapter %d (media %d) reached at media chapter %d",
327                     r->job->chapter_end, chapter_end, chapter );
328             break;
329         }
330
331         if (r->dvd)
332         {
333           if( !hb_dvd_read( r->dvd, ps ) )
334           {
335               break;
336           }
337         }
338         else if (r->stream)
339         {
340           if ( !hb_stream_read( r->stream, ps ) )
341           {
342             break;
343           }
344           if ( r->start_found == 2 )
345           {
346             // We will inspect the timestamps of each frame in sync
347             // to skip from this seek point to the timestamp we
348             // want to start at.
349             if ( ps->start > 0 && ps->start < r->job->pts_to_start )
350                 r->job->pts_to_start -= ps->start;
351             r->start_found = 1;
352           }
353         }
354
355         if( r->job->indepth_scan )
356         {
357             /*
358              * Need to update the progress during a subtitle scan
359              */
360             hb_state_t state;
361
362 #define p state.param.working
363
364             state.state = HB_STATE_WORKING;
365             p.progress = (double)chapter / (double)r->job->chapter_end;
366             if( p.progress > 1.0 )
367             {
368                 p.progress = 1.0;
369             }
370             p.rate_avg = 0.0;
371             p.hours    = -1;
372             p.minutes  = -1;
373             p.seconds  = -1;
374             hb_set_state( r->job->h, &state );
375         }
376
377         (hb_demux[r->title->demuxer])( ps, list, &r->demux );
378
379         while( ( buf = hb_list_item( list, 0 ) ) )
380         {
381             hb_list_rem( list, buf );
382             fifos = GetFifoForId( r->job, buf->id );
383
384             if ( fifos && ! r->saw_video && !r->job->indepth_scan )
385             {
386                 // The first data packet with a PTS from an audio or video stream
387                 // that we're decoding defines 'time zero'. Discard packets until
388                 // we get one.
389                 if ( buf->start != -1 && buf->renderOffset != -1 &&
390                      ( buf->id == r->title->video_id || is_audio( r, buf->id ) ) )
391                 {
392                     // force a new scr offset computation
393                     r->scr_changes = r->demux.scr_changes - 1;
394                     // create a stream state if we don't have one so the
395                     // offset will get computed correctly.
396                     id_to_st( r, buf );
397                     r->saw_video = 1;
398                     hb_log( "reader: first SCR %"PRId64" id %d DTS %"PRId64,
399                             r->demux.last_scr, buf->id, buf->renderOffset );
400                 }
401                 else
402                 {
403                     fifos = NULL;
404                 }
405             }
406             if( fifos )
407             {
408                 if ( buf->start != -1 )
409                 {
410                     int64_t start = buf->start - r->scr_offset;
411                     if ( !r->start_found )
412                         UpdateState( r, start );
413
414                     if ( !r->start_found &&
415                         r->job->pts_to_start && 
416                         buf->renderOffset != -1 &&
417                         start >= r->job->pts_to_start )
418                     {
419                         // pts_to_start point found
420                         // force a new scr offset computation
421                         stream_timing_t *st = find_st( r, buf );
422                         if ( st && 
423                             (st->is_audio ||
424                             ( st == r->stream_timing && !r->saw_audio ) ) )
425                         {
426                             // Re-zero our timestamps
427                             st->last = -st->average;
428                             new_scr_offset( r, buf );
429                             r->start_found = 1;
430                             r->job->pts_to_start = 0;
431                         }
432                     }
433                 }
434                 if ( buf->renderOffset != -1 )
435                 {
436                     if ( r->scr_changes == r->demux.scr_changes )
437                     {
438                         // This packet is referenced to the same SCR as the last.
439                         // Adjust timestamp to remove the System Clock Reference
440                         // offset then update the average inter-packet time
441                         // for this stream.
442                         buf->renderOffset -= r->scr_offset;
443                         update_ipt( r, buf );
444                     }
445                     else
446                     {
447                         // This is the first audio or video packet after an SCR
448                         // change. Compute a new scr offset that would make this
449                         // packet follow the last of this stream with the correct
450                         // average spacing.
451                         stream_timing_t *st = find_st( r, buf );
452
453                         if ( st )
454                         {
455                             // if this is the video stream and we don't have
456                             // audio yet or this is an audio stream
457                             // generate a new scr
458                             if ( st->is_audio ||
459                                  ( st == r->stream_timing && !r->saw_audio ) )
460                             {
461                                 new_scr_offset( r, buf );
462                             }
463                             else
464                             {
465                                 // defer the scr change until we get some
466                                 // audio since audio has a timestamp per
467                                 // frame but video & subtitles don't. Clear
468                                 // the timestamps so the decoder will generate
469                                 // them from the frame durations.
470                                 if ( st != r->stream_timing )
471                                 {
472                                     // not a video stream so it's probably
473                                     // subtitles - the best we can do is to
474                                     // line it up with the last video packet.
475                                     buf->start = r->stream_timing->last;
476                                 }
477                                 else
478                                 {
479                                     buf->start = -1;
480                                     buf->renderOffset = -1;
481                                 }
482                             }
483                         }
484                         else
485                         {
486                             // we got a new scr at the same time as the first
487                             // packet of a stream we've never seen before. We
488                             // have no idea what the timing should be so toss
489                             // this buffer & wait for a stream we've already seen.
490                             // add stream to list of streams we have seen
491                             id_to_st( r, buf );
492                             hb_buffer_close( &buf );
493                             continue;
494                         }
495                     }
496                 }
497                 if ( buf->start != -1 )
498                 {
499                     buf->start -= r->scr_offset;
500                 }
501                 if ( !r->start_found )
502                 {
503                     hb_buffer_close( &buf );
504                     continue;
505                 }
506
507                 buf->sequence = r->sequence++;
508                 /* if there are mutiple output fifos, send a copy of the
509                  * buffer down all but the first (we have to not ship the
510                  * original buffer or we'll race with the thread that's
511                  * consuming the buffer & inject garbage into the data stream). */
512                 for( n = 1; fifos[n] != NULL; n++)
513                 {
514                     hb_buffer_t *buf_copy = hb_buffer_init( buf->size );
515                     hb_buffer_copy_settings( buf_copy, buf );
516                     memcpy( buf_copy->data, buf->data, buf->size );
517                     push_buf( r, fifos[n], buf_copy );
518                 }
519                 push_buf( r, fifos[0], buf );
520             }
521             else
522             {
523                 hb_buffer_close( &buf );
524             }
525         }
526     }
527
528     // send empty buffers downstream to video & audio decoders to signal we're done.
529     if( !*r->die && !r->job->done )
530     {
531         push_buf( r, r->job->fifo_mpeg2, hb_buffer_init(0) );
532
533         hb_audio_t *audio;
534         for( n = 0; (audio = hb_list_item( r->job->title->list_audio, n)); ++n )
535         {
536             if ( audio->priv.fifo_in )
537                 push_buf( r, audio->priv.fifo_in, hb_buffer_init(0) );
538         }
539
540         hb_subtitle_t *subtitle;
541         for( n = 0; (subtitle = hb_list_item( r->job->title->list_subtitle, n)); ++n )
542         {
543             if ( subtitle->fifo_in && subtitle->source == VOBSUB)
544                 push_buf( r, subtitle->fifo_in, hb_buffer_init(0) );
545         }
546     }
547
548     hb_list_empty( &list );
549     hb_buffer_close( &ps );
550     if (r->dvd)
551     {
552         hb_dvd_stop( r->dvd );
553         hb_dvd_close( &r->dvd );
554     }
555     else if (r->stream)
556     {
557         hb_stream_close(&r->stream);
558     }
559
560     if ( r->stream_timing )
561     {
562         free( r->stream_timing );
563     }
564
565     hb_log( "reader: done. %d scr changes", r->demux.scr_changes );
566     if ( r->demux.dts_drops )
567     {
568         hb_log( "reader: %d drops because DTS out of range", r->demux.dts_drops );
569     }
570
571     free( r );
572     _r = NULL;
573 }
574
575 static void UpdateState( hb_reader_t  * r, int64_t start)
576 {
577     hb_state_t state;
578     uint64_t now;
579     double avg;
580
581     now = hb_get_date();
582     if( !r->st_first )
583     {
584         r->st_first = now;
585     }
586
587 #define p state.param.working
588     state.state = HB_STATE_SEARCHING;
589     p.progress  = (float) start / (float) r->job->pts_to_start;
590     if( p.progress > 1.0 )
591     {
592         p.progress = 1.0;
593     }
594     if (now > r->st_first)
595     {
596         int eta;
597
598         avg = 1000.0 * (double)start / (now - r->st_first);
599         eta = ( r->job->pts_to_start - start ) / avg;
600         p.hours   = eta / 3600;
601         p.minutes = ( eta % 3600 ) / 60;
602         p.seconds = eta % 60;
603     }
604     else
605     {
606         p.rate_avg = 0.0;
607         p.hours    = -1;
608         p.minutes  = -1;
609         p.seconds  = -1;
610     }
611 #undef p
612
613     hb_set_state( r->job->h, &state );
614 }
615 /***********************************************************************
616  * GetFifoForId
617  ***********************************************************************
618  *
619  **********************************************************************/
620 static hb_fifo_t ** GetFifoForId( hb_job_t * job, int id )
621 {
622     hb_title_t    * title = job->title;
623     hb_audio_t    * audio;
624     hb_subtitle_t * subtitle;
625     int             i, n, count;
626     static hb_fifo_t * fifos[100];
627
628     memset(fifos, 0, sizeof(fifos));
629
630     if( id == title->video_id )
631     {
632         if( job->indepth_scan )
633         {
634             /*
635              * Ditch the video here during the indepth scan until
636              * we can improve the MPEG2 decode performance.
637              */
638             return NULL;
639         }
640         else
641         {
642             fifos[0] = job->fifo_mpeg2;
643             return fifos;
644         }
645     }
646
647     n = 0;
648     count = hb_list_count( title->list_subtitle );
649     count = count > 99 ? 99 : count;
650     for( i=0; i < count; i++ ) {
651         subtitle =  hb_list_item( title->list_subtitle, i );
652         if (id == subtitle->id) {
653             subtitle->hits++;
654             if( !job->indepth_scan || job->select_subtitle_config.force )
655             {
656                 /*
657                  * Pass the subtitles to be processed if we are not scanning, or if
658                  * we are scanning and looking for forced subs, then pass them up
659                  * to decode whether the sub is a forced one.
660                  */
661                 fifos[n++] = subtitle->fifo_in;
662             }
663         }
664     }
665     if ( n != 0 )
666     {
667         return fifos;
668     }
669     
670     if( !job->indepth_scan )
671     {
672         n = 0;
673         for( i = 0; i < hb_list_count( title->list_audio ); i++ )
674         {
675             audio = hb_list_item( title->list_audio, i );
676             if( id == audio->id )
677             {
678                 fifos[n++] = audio->priv.fifo_in;
679             }
680         }
681
682         if( n != 0 )
683         {
684             return fifos;
685         }
686     }
687
688     return NULL;
689 }
690