OSDN Git Service

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