OSDN Git Service

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