OSDN Git Service

LinGui: make Help->Guide work on windows/mingw
[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         int64_t pts_to_start = r->job->pts_to_start;
270         
271         // Find out what the first timestamp of the stream is
272         // and then seek to the appropriate offset from it
273         if ( hb_stream_read( r->stream, ps ) )
274         {
275             if ( ps->start > 0 )
276                 pts_to_start += ps->start;
277         }
278         
279         if ( hb_stream_seek_ts( r->stream, pts_to_start ) >= 0 )
280         {
281             // Seek takes us to the nearest I-frame before the timestamp
282             // that we want.  So we will retrieve the start time of the
283             // first packet we get, subtract that from pts_to_start, and
284             // inspect the reset of the frames in sync.
285             r->start_found = 2;
286             r->job->pts_to_start = pts_to_start;
287         }
288     } 
289     else if( r->stream )
290     {
291         /*
292          * Standard stream, seek to the starting chapter, if set, and track the
293          * end chapter so that we end at the right time.
294          */
295         int start = r->job->chapter_start;
296         hb_chapter_t *chap = hb_list_item( r->title->list_chapter, chapter_end - 1 );
297         
298         chapter_end = chap->index;
299         if (start > 1)
300         {
301             chap = hb_list_item( r->title->list_chapter, start - 1 );
302             start = chap->index;
303         }
304         
305         /*
306          * Seek to the start chapter.
307          */
308         hb_stream_seek_chapter( r->stream, start );
309     }
310
311     list  = hb_list_init();
312
313     while( !*r->die && !r->job->done )
314     {
315         if (r->dvd)
316             chapter = hb_dvd_chapter( r->dvd );
317         else if (r->stream)
318             chapter = hb_stream_chapter( r->stream );
319
320         if( chapter < 0 )
321         {
322             hb_log( "reader: end of the title reached" );
323             break;
324         }
325         if( chapter > chapter_end )
326         {
327             hb_log( "reader: end of chapter %d (media %d) reached at media chapter %d",
328                     r->job->chapter_end, chapter_end, chapter );
329             break;
330         }
331
332         if (r->dvd)
333         {
334           if( !hb_dvd_read( r->dvd, ps ) )
335           {
336               break;
337           }
338         }
339         else if (r->stream)
340         {
341           if ( !hb_stream_read( r->stream, ps ) )
342           {
343             break;
344           }
345           if ( r->start_found == 2 )
346           {
347             // We will inspect the timestamps of each frame in sync
348             // to skip from this seek point to the timestamp we
349             // want to start at.
350             if ( ps->start > 0 && ps->start < r->job->pts_to_start )
351                 r->job->pts_to_start -= ps->start;
352             else if ( ps->start >= r->job->pts_to_start )
353                 r->job->pts_to_start = 0;
354             r->start_found = 1;
355           }
356         }
357
358         if( r->job->indepth_scan )
359         {
360             /*
361              * Need to update the progress during a subtitle scan
362              */
363             hb_state_t state;
364
365 #define p state.param.working
366
367             state.state = HB_STATE_WORKING;
368             p.progress = (double)chapter / (double)r->job->chapter_end;
369             if( p.progress > 1.0 )
370             {
371                 p.progress = 1.0;
372             }
373             p.rate_avg = 0.0;
374             p.hours    = -1;
375             p.minutes  = -1;
376             p.seconds  = -1;
377             hb_set_state( r->job->h, &state );
378         }
379
380         (hb_demux[r->title->demuxer])( ps, list, &r->demux );
381
382         while( ( buf = hb_list_item( list, 0 ) ) )
383         {
384             hb_list_rem( list, buf );
385             fifos = GetFifoForId( r->job, buf->id );
386
387             if ( fifos && ! r->saw_video && !r->job->indepth_scan )
388             {
389                 // The first data packet with a PTS from an audio or video stream
390                 // that we're decoding defines 'time zero'. Discard packets until
391                 // we get one.
392                 if ( buf->start != -1 && buf->renderOffset != -1 &&
393                      ( buf->id == r->title->video_id || is_audio( r, buf->id ) ) )
394                 {
395                     // force a new scr offset computation
396                     r->scr_changes = r->demux.scr_changes - 1;
397                     // create a stream state if we don't have one so the
398                     // offset will get computed correctly.
399                     id_to_st( r, buf );
400                     r->saw_video = 1;
401                     hb_log( "reader: first SCR %"PRId64" id %d DTS %"PRId64,
402                             r->demux.last_scr, buf->id, buf->renderOffset );
403                 }
404                 else
405                 {
406                     fifos = NULL;
407                 }
408             }
409             if( fifos )
410             {
411                 if ( buf->renderOffset != -1 )
412                 {
413                     if ( r->scr_changes != r->demux.scr_changes )
414                     {
415                         // This is the first audio or video packet after an SCR
416                         // change. Compute a new scr offset that would make this
417                         // packet follow the last of this stream with the correct
418                         // average spacing.
419                         stream_timing_t *st = find_st( r, buf );
420
421                         if ( st )
422                         {
423                             // if this is the video stream and we don't have
424                             // audio yet or this is an audio stream
425                             // generate a new scr
426                             if ( st->is_audio ||
427                                  ( st == r->stream_timing && !r->saw_audio ) )
428                             {
429                                 new_scr_offset( r, buf );
430                             }
431                             else
432                             {
433                                 // defer the scr change until we get some
434                                 // audio since audio has a timestamp per
435                                 // frame but video & subtitles don't. Clear
436                                 // the timestamps so the decoder will generate
437                                 // them from the frame durations.
438                                 if ( st != r->stream_timing )
439                                 {
440                                     // not a video stream so it's probably
441                                     // subtitles - the best we can do is to
442                                     // line it up with the last video packet.
443                                     buf->start = r->stream_timing->last;
444                                 }
445                                 else
446                                 {
447                                     buf->start = -1;
448                                     buf->renderOffset = -1;
449                                 }
450                             }
451                         }
452                         else
453                         {
454                             // we got a new scr at the same time as the first
455                             // packet of a stream we've never seen before. We
456                             // have no idea what the timing should be so toss
457                             // this buffer & wait for a stream we've already seen.
458                             // add stream to list of streams we have seen
459                             id_to_st( r, buf );
460                             hb_buffer_close( &buf );
461                             continue;
462                         }
463                     }
464                 }
465                 if ( buf->start != -1 )
466                 {
467                     int64_t start = buf->start - r->scr_offset;
468                     if ( !r->start_found )
469                         UpdateState( r, start );
470
471                     if ( !r->start_found &&
472                         r->job->pts_to_start && 
473                         buf->renderOffset != -1 &&
474                         start >= r->job->pts_to_start )
475                     {
476                         // pts_to_start point found
477                         // force a new scr offset computation
478                         stream_timing_t *st = find_st( r, buf );
479                         if ( st && 
480                             (st->is_audio ||
481                             ( st == r->stream_timing && !r->saw_audio ) ) )
482                         {
483                             // Re-zero our timestamps
484                             st->last = -st->average;
485                             new_scr_offset( r, buf );
486                             r->start_found = 1;
487                             r->job->pts_to_start = 0;
488                         }
489                     }
490                     buf->start -= r->scr_offset;
491                 }
492                 if ( buf->renderOffset != -1 )
493                 {
494                     if ( r->scr_changes == r->demux.scr_changes )
495                     {
496                         // This packet is referenced to the same SCR as the last.
497                         // Adjust timestamp to remove the System Clock Reference
498                         // offset then update the average inter-packet time
499                         // for this stream.
500                         buf->renderOffset -= r->scr_offset;
501                         update_ipt( r, buf );
502                     }
503                 }
504                 if ( !r->start_found )
505                 {
506                     hb_buffer_close( &buf );
507                     continue;
508                 }
509
510                 buf->sequence = r->sequence++;
511                 /* if there are mutiple output fifos, send a copy of the
512                  * buffer down all but the first (we have to not ship the
513                  * original buffer or we'll race with the thread that's
514                  * consuming the buffer & inject garbage into the data stream). */
515                 for( n = 1; fifos[n] != NULL; n++)
516                 {
517                     hb_buffer_t *buf_copy = hb_buffer_init( buf->size );
518                     hb_buffer_copy_settings( buf_copy, buf );
519                     memcpy( buf_copy->data, buf->data, buf->size );
520                     push_buf( r, fifos[n], buf_copy );
521                 }
522                 push_buf( r, fifos[0], buf );
523             }
524             else
525             {
526                 hb_buffer_close( &buf );
527             }
528         }
529     }
530
531     // send empty buffers downstream to video & audio decoders to signal we're done.
532     if( !*r->die && !r->job->done )
533     {
534         push_buf( r, r->job->fifo_mpeg2, hb_buffer_init(0) );
535
536         hb_audio_t *audio;
537         for( n = 0; (audio = hb_list_item( r->job->title->list_audio, n)); ++n )
538         {
539             if ( audio->priv.fifo_in )
540                 push_buf( r, audio->priv.fifo_in, hb_buffer_init(0) );
541         }
542
543         hb_subtitle_t *subtitle;
544         for( n = 0; (subtitle = hb_list_item( r->job->title->list_subtitle, n)); ++n )
545         {
546             if ( subtitle->fifo_in && subtitle->source == VOBSUB)
547                 push_buf( r, subtitle->fifo_in, hb_buffer_init(0) );
548         }
549     }
550
551     hb_list_empty( &list );
552     hb_buffer_close( &ps );
553     if (r->dvd)
554     {
555         hb_dvd_stop( r->dvd );
556         hb_dvd_close( &r->dvd );
557     }
558     else if (r->stream)
559     {
560         hb_stream_close(&r->stream);
561     }
562
563     if ( r->stream_timing )
564     {
565         free( r->stream_timing );
566     }
567
568     hb_log( "reader: done. %d scr changes", r->demux.scr_changes );
569     if ( r->demux.dts_drops )
570     {
571         hb_log( "reader: %d drops because DTS out of range", r->demux.dts_drops );
572     }
573
574     free( r );
575     _r = NULL;
576 }
577
578 static void UpdateState( hb_reader_t  * r, int64_t start)
579 {
580     hb_state_t state;
581     uint64_t now;
582     double avg;
583
584     now = hb_get_date();
585     if( !r->st_first )
586     {
587         r->st_first = now;
588     }
589
590 #define p state.param.working
591     state.state = HB_STATE_SEARCHING;
592     p.progress  = (float) start / (float) r->job->pts_to_start;
593     if( p.progress > 1.0 )
594     {
595         p.progress = 1.0;
596     }
597     if (now > r->st_first)
598     {
599         int eta;
600
601         avg = 1000.0 * (double)start / (now - r->st_first);
602         eta = ( r->job->pts_to_start - start ) / avg;
603         p.hours   = eta / 3600;
604         p.minutes = ( eta % 3600 ) / 60;
605         p.seconds = eta % 60;
606     }
607     else
608     {
609         p.rate_avg = 0.0;
610         p.hours    = -1;
611         p.minutes  = -1;
612         p.seconds  = -1;
613     }
614 #undef p
615
616     hb_set_state( r->job->h, &state );
617 }
618 /***********************************************************************
619  * GetFifoForId
620  ***********************************************************************
621  *
622  **********************************************************************/
623 static hb_fifo_t ** GetFifoForId( hb_job_t * job, int id )
624 {
625     hb_title_t    * title = job->title;
626     hb_audio_t    * audio;
627     hb_subtitle_t * subtitle;
628     int             i, n, count;
629     static hb_fifo_t * fifos[100];
630
631     memset(fifos, 0, sizeof(fifos));
632
633     if( id == title->video_id )
634     {
635         if( job->indepth_scan )
636         {
637             /*
638              * Ditch the video here during the indepth scan until
639              * we can improve the MPEG2 decode performance.
640              */
641             return NULL;
642         }
643         else
644         {
645             fifos[0] = job->fifo_mpeg2;
646             return fifos;
647         }
648     }
649
650     n = 0;
651     count = hb_list_count( title->list_subtitle );
652     count = count > 99 ? 99 : count;
653     for( i=0; i < count; i++ ) {
654         subtitle =  hb_list_item( title->list_subtitle, i );
655         if (id == subtitle->id) {
656             subtitle->hits++;
657             if( !job->indepth_scan || job->select_subtitle_config.force )
658             {
659                 /*
660                  * Pass the subtitles to be processed if we are not scanning, or if
661                  * we are scanning and looking for forced subs, then pass them up
662                  * to decode whether the sub is a forced one.
663                  */
664                 fifos[n++] = subtitle->fifo_in;
665             }
666         }
667     }
668     if ( n != 0 )
669     {
670         return fifos;
671     }
672     
673     if( !job->indepth_scan )
674     {
675         n = 0;
676         for( i = 0; i < hb_list_count( title->list_audio ); i++ )
677         {
678             audio = hb_list_item( title->list_audio, i );
679             if( id == audio->id )
680             {
681                 fifos[n++] = audio->priv.fifo_in;
682             }
683         }
684
685         if( n != 0 )
686         {
687             return fifos;
688         }
689     }
690
691     return NULL;
692 }
693