OSDN Git Service

fix a crash when a TS has no aspect ratio set in the video stream
[handbrake-jp/handbrake-jp-git.git] / libhb / stream.c
1 /* $Id$
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 <string.h>
8 #include <ctype.h>
9 #include <errno.h>
10
11 #include "hb.h"
12 #include "hbffmpeg.h"
13 #include "lang.h"
14 #include "a52dec/a52.h"
15 #include "mp4v2/mp4v2.h"
16
17 #define min(a, b) a < b ? a : b
18
19 /*
20  * This table defines how ISO MPEG stream type codes map to HandBrake
21  * codecs. It is indexed by the 8 bit stream type and contains the codec
22  * worker object id and a parameter for that worker proc (ignored except
23  * for the ffmpeg-based codecs in which case it is the ffmpeg codec id).
24  *
25  * Entries with a worker proc id of 0 or a kind of 'U' indicate that HB
26  * doesn't handle the stream type.
27  * N - Not used
28  * U - Unknown (to be determined by further processing)
29  * A - Audio
30  * V - Video
31  * P - PCR
32  */
33 typedef enum { N, U, A, V, P } kind_t;
34 typedef struct {
35     kind_t kind; /* not handled / unknown / audio / video */
36     int codec;          /* HB worker object id of codec */
37     int codec_param;    /* param for codec (usually ffmpeg codec id) */
38     const char* name;   /* description of type */
39 } stream2codec_t;
40
41 #define st(id, kind, codec, codec_param, name) \
42  [id] = { kind, codec, codec_param, name }
43
44 static const stream2codec_t st2codec[256] = {
45     st(0x01, V, WORK_DECMPEG2,     0,              "MPEG1"),
46     st(0x02, V, WORK_DECMPEG2,     0,              "MPEG2"),
47     st(0x03, A, HB_ACODEC_MPGA,    CODEC_ID_MP2,   "MPEG1"),
48     st(0x04, A, HB_ACODEC_MPGA,    CODEC_ID_MP2,   "MPEG2"),
49     st(0x05, N, 0,                 0,              "ISO 13818-1 private section"),
50     st(0x06, U, 0,                 0,              "ISO 13818-1 PES private data"),
51     st(0x07, N, 0,                 0,              "ISO 13522 MHEG"),
52     st(0x08, N, 0,                 0,              "ISO 13818-1 DSM-CC"),
53     st(0x09, N, 0,                 0,              "ISO 13818-1 auxiliary"),
54     st(0x0a, N, 0,                 0,              "ISO 13818-6 encap"),
55     st(0x0b, N, 0,                 0,              "ISO 13818-6 DSM-CC U-N msgs"),
56     st(0x0c, N, 0,                 0,              "ISO 13818-6 Stream descriptors"),
57     st(0x0d, N, 0,                 0,              "ISO 13818-6 Sections"),
58     st(0x0e, N, 0,                 0,              "ISO 13818-1 auxiliary"),
59     st(0x0f, A, HB_ACODEC_MPGA,    CODEC_ID_AAC,   "ISO 13818-7 AAC Audio"),
60     st(0x10, V, WORK_DECAVCODECV,  CODEC_ID_MPEG4, "MPEG4"),
61 #if defined(OLD_LATM_PATCH)
62     st(0x11, A, HB_ACODEC_MPGA,    CODEC_ID_AAC_LATM, "MPEG4 LATM AAC"),
63 #else
64     st(0x11, N, 0,                 0,              "MPEG4 LATM AAC"),
65 #endif
66     st(0x12, U, 0,                 0,              "MPEG4 generic"),
67
68     st(0x14, N, 0,                 0,              "ISO 13818-6 DSM-CC download"),
69
70     st(0x1b, V, WORK_DECAVCODECV,  CODEC_ID_H264,  "H.264"),
71
72     st(0x80, N, HB_ACODEC_MPGA,    CODEC_ID_PCM_BLURAY, "DigiCipher II Video"),
73     st(0x81, A, HB_ACODEC_AC3,     0,              "AC-3"),
74     st(0x82, A, HB_ACODEC_DCA,     0,              "HDMV DTS"),
75     st(0x83, A, HB_ACODEC_LPCM,    0,              "LPCM"),
76     st(0x84, A, 0,                 0,              "SDDS"),
77     st(0x85, U, 0,                 0,              "ATSC Program ID"),
78     st(0x86, A, HB_ACODEC_DCA,     0,              "DTS-HD"),
79     st(0x87, A, 0,                 0,              "E-AC-3"),
80
81     st(0x8a, A, HB_ACODEC_DCA,     0,              "DTS"),
82
83     st(0x91, A, HB_ACODEC_AC3,     0,              "AC-3"),
84     st(0x92, N, 0,                 0,              "Subtitle"),
85
86     st(0x94, A, 0,                 0,              "SDDS"),
87     st(0xa0, V, 0,                 0,              "MSCODEC"),
88
89     st(0xea, V, WORK_DECAVCODECV,  CODEC_ID_VC1,   "VC1"),
90 };
91 #undef st
92
93 typedef enum {
94     hb_stream_type_unknown = 0,
95     transport,
96     program,
97     dvd_program,
98     ffmpeg
99 } hb_stream_type_t;
100
101 #define kMaxNumberDecodeStreams 32
102 #define kMaxNumberPMTStreams 32
103
104
105 struct hb_stream_s
106 {
107     int     frames;             /* video frames so far */
108     int     errors;             /* total errors so far */
109     int     last_error_frame;   /* frame # at last error message */
110     int     last_error_count;   /* # errors at last error message */
111     int     packetsize;         /* Transport Stream packet size */
112
113     uint8_t need_keyframe;      // non-zero if want to start at a keyframe
114     uint8_t ts_found_pcr;       // non-zero if we've found at least one input pcr
115     int     ts_pcr_out;         // sequence number of most recent output pcr
116     int     ts_pcr_in;          // sequence number of most recent input pcr
117     int64_t ts_pcr;             // most recent input pcr
118     int64_t ts_pcrhist[4];      // circular buffer of output pcrs
119
120     uint8_t *ts_packet;         /* buffer for one TS packet */
121     hb_buffer_t *ts_buf[kMaxNumberDecodeStreams];
122     int     ts_pos[kMaxNumberDecodeStreams];
123     int8_t  ts_skipbad[kMaxNumberDecodeStreams];
124     int8_t  ts_streamcont[kMaxNumberDecodeStreams];
125     uint8_t ts_pkt_summary[kMaxNumberDecodeStreams][8];
126
127     hb_buffer_t *fwrite_buf;      /* PS buffer (set by hb_ts_stream_decode) */
128
129     int      chapter;           /* Chapter that we are currently in */
130     int64_t  chapter_end;       /* HB time that the current chapter ends */
131
132     /*
133      * Stuff before this point is dynamic state updated as we read the
134      * stream. Stuff after this point is stream description state that
135      * we learn during the initial scan but cache so it can be
136      * reused during the conversion read.
137      */
138     uint8_t ts_number_pids;
139     uint8_t ts_flags;           // stream characteristics:
140 #define         TS_HAS_PCR  (1 << 0)    // at least one PCR seen
141 #define         TS_HAS_RAP  (1 << 1)    // Random Access Point bit seen
142 #define         TS_HAS_RSEI (1 << 2)    // "Restart point" SEI seen
143     uint8_t ts_IDRs;            // # IDRs found during duration scan
144
145     int16_t ts_pids[kMaxNumberDecodeStreams];
146
147     uint32_t ts_format_id[kMaxNumberDecodeStreams];
148 #define TS_FORMAT_ID_AC3 (('A' << 24) | ('C' << 16) | ('-' << 8) | '3')
149     uint8_t ts_stream_type[kMaxNumberDecodeStreams];
150     kind_t  ts_stream_kind[kMaxNumberDecodeStreams];
151     uint8_t ts_multiplexed[kMaxNumberDecodeStreams];
152
153     char    *path;
154     FILE    *file_handle;
155     hb_stream_type_t hb_stream_type;
156     hb_title_t *title;
157
158     AVFormatContext *ffmpeg_ic;
159     AVPacket *ffmpeg_pkt;
160     double ffmpeg_tsconv[MAX_STREAMS];
161     uint8_t ffmpeg_video_id;
162
163     struct {
164         int lang_code;
165         int flags;
166         int rate;
167         int bitrate;
168     } a52_info[kMaxNumberDecodeStreams];
169
170     struct
171     {
172         unsigned short program_number;
173         unsigned short program_map_PID;
174     } pat_info[kMaxNumberPMTStreams];
175     int     ts_number_pat_entries;
176
177     struct
178     {
179         int reading;
180         unsigned char *tablebuf;
181         unsigned int tablepos;
182         unsigned char current_continuity_counter;
183
184         int section_length;
185         int program_number;
186         unsigned int PCR_PID;
187         uint32_t reg_desc;
188         int program_info_length;
189         struct
190         {
191             unsigned char stream_type;
192             unsigned short elementary_PID;
193             unsigned short ES_info_length;
194             unsigned char *es_info_descriptor_data;
195         } pmt_stream_info[kMaxNumberPMTStreams];
196     } pmt_info;
197 };
198
199 /***********************************************************************
200  * Local prototypes
201  **********************************************************************/
202 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
203 static void hb_ts_stream_init(hb_stream_t *stream);
204 static void hb_ts_stream_find_pids(hb_stream_t *stream);
205 static int hb_ts_stream_decode(hb_stream_t *stream, hb_buffer_t *obuf);
206 static void hb_ts_stream_reset(hb_stream_t *stream);
207 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
208                                                        int idx);
209 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title);
210 static off_t align_to_next_packet(hb_stream_t *stream);
211
212 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title );
213 static void ffmpeg_close( hb_stream_t *d );
214 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream );
215 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf );
216 static int ffmpeg_seek( hb_stream_t *stream, float frac );
217 static int ffmpeg_seek_ts( hb_stream_t *stream, int64_t ts );
218
219 /*
220  * streams have a bunch of state that's learned during the scan. We don't
221  * want to throw away the state when scan does a close then relearn
222  * everything when reader does an open. So we save the stream state on
223  * the close following a scan and reuse it when 'reader' does an open.
224  */
225 static hb_list_t *stream_state_list;
226
227 static hb_stream_t *hb_stream_lookup( const char *path )
228 {
229     if ( stream_state_list == NULL )
230         return NULL;
231
232     hb_stream_t *ss;
233     int i = 0;
234
235     while ( ( ss = hb_list_item( stream_state_list, i++ ) ) != NULL )
236     {
237         if ( strcmp( path, ss->path ) == 0 )
238         {
239             break;
240         }
241     }
242     return ss;
243 }
244
245 static void hb_stream_state_delete( hb_stream_t *ss )
246 {
247     hb_list_rem( stream_state_list, ss );
248     free( ss->path );
249     free( ss );
250 }
251
252 /*
253  * logging routines.
254  * these frontend hb_log because transport streams can have a lot of errors
255  * so we want to rate limit messages. this routine limits the number of
256  * messages to at most one per minute of video. other errors that occur
257  * during the minute are counted & the count is output with the next
258  * error msg we print.
259  */
260 static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
261 {
262     // limit error printing to at most one per minute of video (at 30fps)
263     ++stream->errors;
264     if ( stream->frames - stream->last_error_frame >= 30*60 )
265     {
266         char msg[256];
267
268         vsnprintf( msg, sizeof(msg), log, args );
269
270         if ( stream->errors - stream->last_error_count < 10 )
271         {
272             hb_log( "stream: error near frame %d: %s", stream->frames, msg );
273         }
274         else
275         {
276             int Edelta = stream->errors - stream->last_error_count;
277             double Epcnt = (double)Edelta * 100. /
278                             (stream->frames - stream->last_error_frame);
279             hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
280                     Edelta, Epcnt, stream->frames, msg );
281         }
282         stream->last_error_frame = stream->frames;
283         stream->last_error_count = stream->errors;
284     }
285 }
286
287 static void ts_warn( hb_stream_t*, char*, ... ) HB_WPRINTF(2,3);
288 static void ts_err( hb_stream_t*, int, char*, ... ) HB_WPRINTF(3,4);
289
290 static void ts_warn( hb_stream_t *stream, char *log, ... )
291 {
292     va_list args;
293     va_start( args, log );
294     ts_warn_helper( stream, log, args );
295     va_end( args );
296 }
297
298 static kind_t ts_stream_kind( hb_stream_t *stream, int curstream )
299 {
300     return st2codec[stream->ts_stream_type[curstream]].kind;
301 }
302
303 static int index_of_pid(hb_stream_t *stream, int pid)
304 {
305     int i;
306
307     for ( i = 0; i < stream->ts_number_pids; ++i )
308         if ( pid == stream->ts_pids[i] )
309             return i;
310
311     return -1;
312 }
313
314 static int index_of_video(hb_stream_t *stream)
315 {
316     int i;
317
318     for ( i = 0; i < stream->ts_number_pids; ++i )
319         if ( V == stream->ts_stream_kind[i] )
320             return i;
321
322     return -1;
323 }
324
325 static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
326 {
327     va_list args;
328     va_start( args, log );
329     ts_warn_helper( stream, log, args );
330     va_end( args );
331
332     stream->ts_skipbad[curstream] = 1;
333     stream->ts_pos[curstream] = 0;
334     stream->ts_streamcont[curstream] = -1;
335 }
336
337 static int check_ps_sync(const uint8_t *buf)
338 {
339     // a legal MPEG program stream must start with a Pack header in the
340     // first four bytes.
341     return (buf[0] == 0x00) && (buf[1] == 0x00) &&
342            (buf[2] == 0x01) && (buf[3] == 0xba);
343 }
344
345 static int check_ps_sc(const uint8_t *buf)
346 {
347     // a legal MPEG program stream must start with a Pack followed by a
348     // some other start code. If we've already verified the pack, this skip
349     // it and checks for a start code prefix.
350     int pos = 14 + ( buf[13] & 0x7 );   // skip over the PACK
351     return (buf[pos+0] == 0x00) && (buf[pos+1] == 0x00) && (buf[pos+2] == 0x01);
352 }
353
354 static int check_ts_sync(const uint8_t *buf)
355 {
356     // must have initial sync byte, no scrambling & a legal adaptation ctrl
357     return (buf[0] == 0x47) && ((buf[3] >> 6) == 0) && ((buf[3] >> 4) > 0);
358 }
359
360 static int have_ts_sync(const uint8_t *buf, int psize)
361 {
362     return check_ts_sync(&buf[0*psize]) && check_ts_sync(&buf[1*psize]) &&
363            check_ts_sync(&buf[2*psize]) && check_ts_sync(&buf[3*psize]) &&
364            check_ts_sync(&buf[4*psize]) && check_ts_sync(&buf[5*psize]) &&
365            check_ts_sync(&buf[6*psize]) && check_ts_sync(&buf[7*psize]);
366 }
367
368 static int hb_stream_check_for_ts(const uint8_t *buf)
369 {
370     // transport streams should have a sync byte every 188 bytes.
371     // search the first 8KB of buf looking for at least 8 consecutive
372     // correctly located sync patterns.
373     int offset = 0;
374
375     for ( offset = 0; offset < 8*1024-8*188; ++offset )
376     {
377         if ( have_ts_sync( &buf[offset], 188) )
378             return 188 | (offset << 8);
379         if ( have_ts_sync( &buf[offset], 192) )
380             return 192 | (offset << 8);
381         if ( have_ts_sync( &buf[offset], 204) )
382             return 204 | (offset << 8);
383         if ( have_ts_sync( &buf[offset], 208) )
384             return 208 | (offset << 8);
385     }
386     return 0;
387 }
388
389 static int hb_stream_check_for_ps(hb_stream_t *stream)
390 {
391     uint8_t buf[2048*4];
392     uint8_t sc_buf[4];
393     int pos;
394     int hits = 0;
395
396     fseek(stream->file_handle, 0, SEEK_SET);
397
398     // program streams should start with a PACK then some other mpeg start 
399     // code (usually a SYS but that might be missing if we only have a clip). 
400     while (pos < 512 * 1024)
401     {
402         int offset;
403
404         if ( fread(buf, 1, sizeof(buf), stream->file_handle) != sizeof(buf) )
405             return 0;
406
407         for ( offset = 0; offset < 8*1024-27; ++offset )
408         {
409             if ( check_ps_sync( &buf[offset] ) && check_ps_sc( &buf[offset] ) )
410             {
411                 int pes_offset, prev, data_len;
412                 uint8_t sid;
413
414                 if ( ++hits == 3 )
415                     return 1;
416                 pes_offset = 14 + (buf[13] & 0x7);
417                 sid = buf[pes_offset+3];
418                 data_len = (buf[pes_offset+4] << 8) + buf[pes_offset+5];
419                 if ( data_len && sid > 0xba && sid < 0xf9 )
420                 {
421                     prev = ftell( stream->file_handle );
422                     pos = pes_offset + 6 + data_len + prev;
423                     fseek( stream->file_handle, pos, SEEK_SET );
424                     if ( fread(sc_buf, 1, 4, stream->file_handle) != 4 )
425                         return 0;
426                     if (sc_buf[0] == 0x00 && sc_buf[1] == 0x00 && 
427                         sc_buf[2] == 0x01)
428                     {
429                         return 1;
430                     }
431                     fseek( stream->file_handle, prev, SEEK_SET );
432                 }
433             }
434         }
435         fseek( stream->file_handle, -27, SEEK_CUR );
436         pos = ftell( stream->file_handle );
437     }
438     return 0;
439 }
440
441 static int hb_stream_check_for_dvd_ps(const uint8_t *buf)
442 {
443     // DVD program streams should have a Pack header every 2048 bytes.
444     // check that we have 4 of these in a row.
445     return check_ps_sync(&buf[0*2048]) && check_ps_sync(&buf[1*2048]) &&
446            check_ps_sync(&buf[2*2048]) && check_ps_sync(&buf[3*2048]);
447 }
448
449 static int hb_stream_get_type(hb_stream_t *stream)
450 {
451     uint8_t buf[2048*4];
452
453     if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
454     {
455         int psize;
456         if ( ( psize = hb_stream_check_for_ts(buf) ) != 0 )
457         {
458             int offset = psize >> 8;
459             psize &= 0xff;
460             hb_log("file is MPEG Transport Stream with %d byte packets"
461                    " offset %d bytes", psize, offset);
462             stream->packetsize = psize;
463             stream->hb_stream_type = transport;
464             hb_ts_stream_init(stream);
465             if ( index_of_video( stream ) < 0 )
466             {
467                 return 0;
468             }
469             return 1;
470         }
471         if ( hb_stream_check_for_dvd_ps(buf) != 0 )
472         {
473             hb_log("file is MPEG DVD Program Stream");
474             stream->hb_stream_type = dvd_program;
475             return 1;
476         }
477         if ( hb_stream_check_for_ps(stream) != 0 )
478         {
479             hb_log("file is MPEG Program Stream");
480             stream->hb_stream_type = program;
481             return 1;
482         }
483     }
484     return 0;
485 }
486
487 static void hb_stream_delete_dynamic( hb_stream_t *d )
488 {
489     if( d->file_handle )
490     {
491         fclose( d->file_handle );
492         d->file_handle = NULL;
493     }
494
495     int i=0;
496
497     if ( d->ts_packet )
498     {
499         free( d->ts_packet );
500         d->ts_packet = NULL;
501     }
502     for (i = 0; i < kMaxNumberDecodeStreams; i++)
503     {
504         if (d->ts_buf[i])
505         {
506             hb_buffer_close(&(d->ts_buf[i]));
507             d->ts_buf[i] = NULL;
508         }
509     }
510 }
511
512 static void hb_stream_delete( hb_stream_t *d )
513 {
514     hb_stream_delete_dynamic( d );
515     free( d->path );
516     free( d );
517 }
518
519 static int audio_inactive( hb_stream_t *stream, int idx )
520 {
521     int pid = stream->ts_pids[idx];
522
523     if ( pid < 0 )
524     {
525         // PID declared inactive by hb_stream_title_scan
526         return 1;
527     }
528     if ( pid == stream->pmt_info.PCR_PID )
529     {
530         // PCR PID is always active
531         return 0;
532     }
533
534     // see if we should make the stream inactive because scan.c didn't
535     // find a valid audio bitstream.
536     int i;
537     for ( i = 0; i < hb_list_count( stream->title->list_audio ); ++i )
538     {
539         hb_audio_t *audio = hb_list_item( stream->title->list_audio, i );
540         if ( audio->id == pid )
541         {
542             return 0;
543         }
544     }
545
546     // not in the title's audio list - declare the PID inactive
547     stream->ts_pids[idx] = -stream->ts_pids[idx];
548     return 1;
549 }
550
551 /***********************************************************************
552  * hb_stream_open
553  ***********************************************************************
554  *
555  **********************************************************************/
556 hb_stream_t * hb_stream_open( char *path, hb_title_t *title )
557 {
558     FILE *f = fopen( path, "rb" );
559     if ( f == NULL )
560     {
561         hb_log( "hb_stream_open: open %s failed", path );
562         return NULL;
563     }
564
565     hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
566     if ( d == NULL )
567     {
568         fclose( f );
569         hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
570         return NULL;
571     }
572
573     /*
574      * if we're opening the stream to read & convert, we need
575      * the state we saved when we scanned the stream. if we're
576      * opening the stream to scan it we want to rebuild the state
577      * (even if we have saved state, the stream may have changed).
578      */
579     hb_stream_t *ss = hb_stream_lookup( path );
580     if ( title && ss && ss->hb_stream_type != ffmpeg )
581     {
582         /*
583          * copy the saved state since we might be encoding the same stream
584          * multiple times.
585          */
586         memcpy( d, ss, sizeof(*d) );
587         d->file_handle = f;
588         d->title = title;
589         d->path = strdup( path );
590
591         if ( d->hb_stream_type == transport )
592         {
593             d->ts_packet = malloc( d->packetsize );
594
595             int i;
596             for ( i = 0; i < d->ts_number_pids; i++)
597             {
598                 if ( d->ts_stream_kind[i] == A &&
599                      audio_inactive( d, i ) )
600                 {
601                     // this PID isn't wanted (we don't have a codec for it
602                     // or scan didn't find audio parameters)
603                     continue;
604                 }
605                 d->ts_buf[i] = hb_buffer_init(d->packetsize);
606                 d->ts_buf[i]->size = 0;
607             }
608             hb_stream_seek( d, 0. );
609         }
610         return d;
611     }
612
613     /*
614      * opening for scan - delete any saved state then (re)scan the stream.
615      * If it's something we can deal with (MPEG2 PS or TS) return a stream
616      * reference structure & null otherwise.
617      */
618     if ( ss != NULL )
619     {
620         hb_stream_state_delete( ss );
621     }
622     d->file_handle = f;
623     d->title = title;
624     d->path = strdup( path );
625     if (d->path != NULL )
626     {
627         if ( hb_stream_get_type( d ) != 0 )
628         {
629             return d;
630         }
631         fclose( d->file_handle );
632         d->file_handle = NULL;
633         if ( ffmpeg_open( d, title ) )
634         {
635             return d;
636         }
637     }
638     if ( d->file_handle )
639     {
640         fclose( d->file_handle );
641     }
642     if (d->path)
643     {
644         free( d->path );
645     }
646     hb_log( "hb_stream_open: open %s failed", path );
647     free( d );
648     return NULL;
649 }
650
651 hb_stream_t * hb_bd_stream_open( hb_title_t *title )
652 {
653     int ii;
654
655     hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
656     if ( d == NULL )
657     {
658         hb_log( "hb_bd_stream_open: can't allocate space for stream state" );
659         return NULL;
660     }
661
662     for (ii = 0; ii < kMaxNumberDecodeStreams; ii++)
663     {
664         d->ts_streamcont[ii] = -1;
665         d->ts_pids[ii] = -1;
666     }
667
668     d->file_handle = NULL;
669     d->title = title;
670     d->path = NULL;
671     d->ts_packet = NULL;
672
673     d->ts_number_pids = 0;
674     d->ts_pids[0] = title->video_id;
675     d->ts_stream_type[0] = title->video_stream_type;
676     d->ts_stream_kind[0] = V;
677     d->ts_number_pids++;
678
679     hb_audio_t * audio;
680     for ( ii = 0; ( audio = hb_list_item( title->list_audio, ii ) ); ++ii )
681     {
682         d->ts_pids[d->ts_number_pids] = audio->id;
683         d->ts_stream_type[d->ts_number_pids] = audio->config.in.stream_type;
684         d->ts_stream_kind[d->ts_number_pids] = A;
685
686         if ( d->ts_stream_type[d->ts_number_pids] == 0x83 &&
687              title->reg_desc == STR4_TO_UINT32("HDMV") )
688         {
689             // This is an interleaved TrueHD/AC-3 stream and the esid of
690             // the AC-3 is 0x76
691             d->ts_multiplexed[d->ts_number_pids] = 0x76;
692             d->ts_stream_type[d->ts_number_pids] = 0x81;
693         }
694         if ( d->ts_stream_type[d->ts_number_pids] == 0x86 &&
695              title->reg_desc == STR4_TO_UINT32("HDMV") )
696         {
697             // This is an interleaved DTS-HD/DTS stream and the esid of
698             // the DTS is 0x71
699             d->ts_multiplexed[d->ts_number_pids] = 0x71;
700             d->ts_stream_type[d->ts_number_pids] = 0x82;
701         }
702
703         d->ts_number_pids++;
704     }
705
706     d->ts_flags = TS_HAS_RAP;
707     // When scanning, title->job == NULL.  We don't need to wait for
708     // a PCR when scanning. In fact, it trips us up on the first
709     // preview of every title since we would have to read quite a
710     // lot of data before finding the PCR.
711     if (title->pcr_pid != 0xFFFF && title->job)
712     {
713         if ( index_of_pid( d, title->pcr_pid ) < 0 )
714         {
715             // BD PCR PID is specified to always be 0x1001
716             d->ts_pids[d->ts_number_pids] = 0x1001;
717             d->ts_stream_kind[d->ts_number_pids] = P;
718             d->ts_number_pids++;
719         }
720     }
721
722     d->packetsize = 192;
723     d->hb_stream_type = transport;
724
725     for ( ii = 0; ii < d->ts_number_pids; ii++ )
726     {
727         d->ts_buf[ii] = hb_buffer_init(d->packetsize);
728         d->ts_buf[ii]->size = 0;
729     }
730
731     return d;
732 }
733
734 /***********************************************************************
735  * hb_stream_close
736  ***********************************************************************
737  * Closes and frees everything
738  **********************************************************************/
739 void hb_stream_close( hb_stream_t ** _d )
740 {
741     hb_stream_t *stream = * _d;
742
743     if ( stream->hb_stream_type == ffmpeg )
744     {
745         ffmpeg_close( stream );
746         hb_stream_delete( stream );
747         *_d = NULL;
748         return;
749     }
750
751     if ( stream->frames )
752     {
753         hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
754                 stream->errors, (double)stream->errors * 100. /
755                 (double)stream->frames );
756     }
757
758     /*
759      * if the stream was opened for a scan, cache the result, otherwise delete
760      * the state.
761      */
762     if ( stream->title == NULL )
763     {
764         hb_stream_delete_dynamic( stream );
765         if ( stream_state_list == NULL )
766         {
767             stream_state_list = hb_list_init();
768         }
769         hb_list_add( stream_state_list, stream );
770     }
771     else
772     {
773         hb_stream_delete( stream );
774     }
775     *_d = NULL;
776 }
777
778 /* when the file was first opened we made entries for all the audio elementary
779  * streams we found in it. Streams that were later found during the preview scan
780  * now have an audio codec, type, rate, etc., associated with them. At the end
781  * of the scan we delete all the audio entries that weren't found by the scan
782  * or don't have a format we support. This routine deletes audio entry 'indx'
783  * by setting its PID to an invalid value so no packet will match it. (We can't
784  * move any of the entries since the index of the entry is used as the id
785  * of the media stream for HB. */
786 static void hb_stream_delete_entry(hb_stream_t *stream, int indx)
787 {
788     if ( stream->ts_pids[indx] > 0 )
789     {
790         stream->ts_pids[indx] = -stream->ts_pids[indx];
791     }
792 }
793
794 /***********************************************************************
795  * hb_ps_stream_title_scan
796  ***********************************************************************
797  *
798  **********************************************************************/
799 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
800 {
801     if ( stream->hb_stream_type == ffmpeg )
802         return ffmpeg_title_scan( stream );
803
804     // 'Barebones Title'
805     hb_title_t *aTitle = hb_title_init( stream->path, 0 );
806     aTitle->type = HB_STREAM_TYPE;
807     aTitle->index = 1;
808
809     // Copy part of the stream path to the title name
810     char *sep = strrchr(stream->path, '/');
811     if (sep)
812         strcpy(aTitle->name, sep+1);
813     char *dot_term = strrchr(aTitle->name, '.');
814     if (dot_term)
815         *dot_term = '\0';
816
817     // Height, width,  rate and aspect ratio information is filled in when the previews are built
818
819     hb_stream_duration(stream, aTitle);
820
821     // One Chapter
822     hb_chapter_t * chapter;
823     chapter = calloc( sizeof( hb_chapter_t ), 1 );
824     chapter->index = 1;
825     chapter->duration = aTitle->duration;
826     chapter->hours = aTitle->hours;
827     chapter->minutes = aTitle->minutes;
828     chapter->seconds = aTitle->seconds;
829     hb_list_add( aTitle->list_chapter, chapter );
830
831     // Figure out how many audio streams we really have:
832     // - For transport streams, for each PID listed in the PMT (whether
833     //   or not it was an audio stream type) read the bitstream until we
834     //   find an packet from that PID containing a PES header and see if
835     //   the elementary stream is an audio type.
836     // - For program streams read the first 4MB and take every unique
837     //   audio stream we find.
838     if (stream->hb_stream_type == transport)
839     {
840         int i;
841
842         for (i=0; i < stream->ts_number_pids; i++)
843         {
844             hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
845             if ( audio )
846             {
847                 hb_list_add( aTitle->list_audio, audio );
848             }
849         }
850
851         // make sure we're grabbing the PCR PID
852         if ( index_of_pid( stream, stream->pmt_info.PCR_PID ) < 0 )
853         {
854             stream->ts_pids[stream->ts_number_pids] = stream->pmt_info.PCR_PID;
855             stream->ts_stream_kind[stream->ts_number_pids] = P;
856             stream->ts_number_pids++;
857         }
858
859         for (i = 0; i < stream->ts_number_pids; i++)
860         {
861             kind_t kind = stream->ts_stream_kind[i];
862
863             if ( kind == N || kind == U )
864             {
865                 hb_stream_delete_entry(stream, i);
866             }
867         }
868
869         // set the video id, codec & muxer
870         int idx = index_of_video( stream );
871         if ( idx < 0 )
872         {
873             hb_title_close( &aTitle );
874             return NULL;
875         }
876
877         aTitle->video_id = stream->ts_pids[idx];
878         aTitle->video_codec = st2codec[stream->ts_stream_type[idx]].codec;
879         aTitle->video_codec_param = st2codec[stream->ts_stream_type[idx]].codec_param;
880         aTitle->demuxer = HB_MPEG2_TS_DEMUXER;
881
882         if ( ( stream->ts_flags & TS_HAS_PCR ) == 0 )
883         {
884             hb_log( "transport stream missing PCRs - using video DTS instead" );
885         }
886
887         if ( stream->ts_IDRs < 1 )
888         {
889             hb_log( "transport stream doesn't seem to have video IDR frames" );
890             aTitle->flags |= HBTF_NO_IDR;
891         }
892     }
893     else
894     {
895         hb_ps_stream_find_audio_ids(stream, aTitle);
896     }
897
898     return aTitle;
899 }
900
901 /*
902  * read the next transport stream packet from 'stream'. Return NULL if
903  * we hit eof & a pointer to the sync byte otherwise.
904  */
905 static const uint8_t *next_packet( hb_stream_t *stream )
906 {
907     uint8_t *buf = stream->ts_packet + stream->packetsize - 188;
908
909     while ( 1 )
910     {
911         if ( fread(stream->ts_packet, 1, stream->packetsize, stream->file_handle) !=
912              stream->packetsize )
913         {
914             return NULL;
915         }
916         if (buf[0] == 0x47)
917         {
918             return buf;
919         }
920         // lost sync - back up to where we started then try to re-establish.
921         off_t pos = ftello(stream->file_handle) - stream->packetsize;
922         off_t pos2 = align_to_next_packet(stream);
923         if ( pos2 == 0 )
924         {
925             hb_log( "next_packet: eof while re-establishing sync @ %"PRId64, pos );
926             return NULL;
927         }
928         ts_warn( stream, "next_packet: sync lost @ %"PRId64", regained after %"PRId64" bytes",
929                  pos, pos2 );
930     }
931 }
932
933 /*
934  * skip to the start of the next PACK header in program stream src_stream.
935  */
936 static void skip_to_next_pack( hb_stream_t *src_stream )
937 {
938     // scan forward until we find the start of the next pack
939     uint32_t strt_code = -1;
940     int c;
941
942     flockfile( src_stream->file_handle );
943     while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
944     {
945         strt_code = ( strt_code << 8 ) | c;
946         if ( strt_code == 0x000001ba )
947             // we found the start of the next pack
948             break;
949     }
950     funlockfile( src_stream->file_handle );
951
952     // if we didn't terminate on an eof back up so the next read
953     // starts on the pack boundary.
954     if ( c != EOF )
955     {
956         fseeko( src_stream->file_handle, -4, SEEK_CUR );
957     }
958 }
959
960 static int isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
961 {
962     // For mpeg2: look for a gop start or i-frame picture start
963     // for h.264: look for idr nal type or a slice header for an i-frame
964     // for vc1:   look for a Sequence header
965     int i;
966     uint32_t strid = 0;
967
968
969     if ( stream->ts_stream_type[0] <= 2 )
970     {
971         // This section of the code handles MPEG-1 and MPEG-2 video streams
972         for (i = 13 + adapt_len; i < 188; i++)
973         {
974             strid = (strid << 8) | buf[i];
975             if ( ( strid >> 8 ) == 1 )
976             {
977                 // we found a start code
978                 uint8_t id = strid;
979                 switch ( id )
980                 {
981                     case 0xB8: // group_start_code (GOP header)
982                     case 0xB3: // sequence_header code
983                         return 1;
984
985                     case 0x00: // picture_start_code
986                         // picture_header, let's see if it's an I-frame
987                         if (i<185)
988                         {
989                             // check if picture_coding_type == 1
990                             if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
991                             {
992                                 // found an I-frame picture
993                                 return 1;
994                             }
995                         }
996                         break;
997                 }
998             }
999         }
1000         // didn't find an I-frame
1001         return 0;
1002     }
1003     if ( stream->ts_stream_type[0] == 0x1b )
1004     {
1005         // we have an h.264 stream 
1006         for (i = 13 + adapt_len; i < 188; i++)
1007         {
1008             strid = (strid << 8) | buf[i];
1009             if ( ( strid >> 8 ) == 1 )
1010             {
1011                 // we found a start code - remove the ref_idc from the nal type
1012                 uint8_t nal_type = strid & 0x1f;
1013                 if ( nal_type == 0x05 )
1014                     // h.264 IDR picture start
1015                     return 1;
1016             }
1017         }
1018         // didn't find an I-frame
1019         return 0;
1020     }
1021     if ( stream->ts_stream_type[0] == 0xea )
1022     {
1023         // we have an vc1 stream 
1024         for (i = 13 + adapt_len; i < 188; i++)
1025         {
1026             strid = (strid << 8) | buf[i];
1027             if ( strid == 0x10f )
1028             {
1029                 // the ffmpeg vc1 decoder requires a seq hdr code in the first
1030                 // frame.
1031                 return 1;
1032             }
1033         }
1034         // didn't find an I-frame
1035         return 0;
1036     }
1037
1038     // we don't understand the stream type so just say "yes" otherwise
1039     // we'll discard all the video.
1040     return 1;
1041 }
1042
1043 /*
1044  * scan the next MB of 'stream' to find the next start packet for
1045  * the Packetized Elementary Stream associated with TS PID 'pid'.
1046  */
1047 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
1048 {
1049     int npack = 300000; // max packets to read
1050
1051     while (--npack >= 0)
1052     {
1053         const uint8_t *buf = next_packet( stream );
1054         if ( buf == NULL )
1055         {
1056             hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
1057             return 0;
1058         }
1059
1060         // while we're reading the stream, check if it has valid PCRs
1061         // and/or random access points.
1062         uint32_t pack_pid = ( (buf[1] & 0x1f) << 8 ) | buf[2];
1063         if ( pack_pid == stream->pmt_info.PCR_PID )
1064         {
1065             if ( ( buf[5] & 0x10 ) &&
1066                  ( ( ( buf[3] & 0x30 ) == 0x20 ) ||
1067                    ( ( buf[3] & 0x30 ) == 0x30 && buf[4] > 6 ) ) )
1068             {
1069                 stream->ts_flags |= TS_HAS_PCR;
1070             }
1071         }
1072         if ( buf[5] & 0x40 )
1073         {
1074             stream->ts_flags |= TS_HAS_RAP;
1075         }
1076
1077         /*
1078          * The PES header is only in TS packets with 'start' set so we check
1079          * that first then check for the right PID.
1080          */
1081         if ((buf[1] & 0x40) == 0 || pack_pid != pid )
1082         {
1083             // not a start packet or not the pid we want
1084             continue;
1085         }
1086
1087         /* skip over the TS hdr to return a pointer to the PES hdr */
1088         int udata = 4;
1089         switch (buf[3] & 0x30)
1090         {
1091             case 0x00: // illegal
1092             case 0x20: // fill packet
1093                 continue;
1094
1095             case 0x30: // adaptation
1096                 if (buf[4] > 182)
1097                 {
1098                     hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
1099                     continue;
1100                 }
1101                 udata += buf[4] + 1;
1102                 break;
1103         }
1104         /* PES hdr has to begin with an mpeg start code */
1105         if (buf[udata+0] == 0x00 && buf[udata+1] == 0x00 && buf[udata+2] == 0x01)
1106         {
1107             return &buf[udata];
1108         }
1109     }
1110
1111     /* didn't find it */
1112     return 0;
1113 }
1114
1115 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
1116 {
1117     hb_buffer_t *buf  = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1118     hb_list_t *list = hb_list_init();
1119     // how many blocks we read while searching for a video PES header
1120     int blksleft = 1024;
1121     uint64_t pts = 0;
1122
1123     while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1124     {
1125         hb_buffer_t *es;
1126
1127         // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1128         hb_demux_ps( buf, list, 0 );
1129
1130         while ( ( es = hb_list_item( list, 0 ) ) )
1131         {
1132             hb_list_rem( list, es );
1133             if ( es->id == 0xe0 )
1134             {
1135                 // this PES contains video - if there's a PTS we're done
1136                 // hb_demux_ps left the PTS in buf_es->start.
1137                 if ( es->start != ~0 )
1138                 {
1139                     pts = es->start;
1140                     blksleft = 0;
1141                     break;
1142                 }
1143             }
1144             hb_buffer_close( &es );
1145         }
1146     }
1147     hb_list_empty( &list );
1148     hb_buffer_close(&buf);
1149     return pts;
1150 }
1151
1152 /***********************************************************************
1153  * hb_stream_duration
1154  ***********************************************************************
1155  *
1156  * Finding stream duration is difficult.  One issue is that the video file
1157  * may have chunks from several different program fragments (main feature,
1158  * commercials, station id, trailers, etc.) all with their own base pts
1159  * value.  We can't find the piece boundaries without reading the entire
1160  * file but if we compute a rate based on time stamps from two different
1161  * pieces the result will be meaningless.  The second issue is that the
1162  * data rate of compressed video normally varies by 5-10x over the length
1163  * of the video. This says that we want to compute the rate over relatively
1164  * long segments to get a representative average but long segments increase
1165  * the likelihood that we'll cross a piece boundary.
1166  *
1167  * What we do is take time stamp samples at several places in the file
1168  * (currently 16) then compute the average rate (i.e., ticks of video per
1169  * byte of the file) for all pairs of samples (N^2 rates computed for N
1170  * samples). Some of those rates will be absurd because the samples came
1171  * from different segments. Some will be way low or high because the
1172  * samples came from a low or high motion part of the segment. But given
1173  * that we're comparing *all* pairs the majority of the computed rates
1174  * should be near the overall average.  So we median filter the computed
1175  * rates to pick the most representative value.
1176  *
1177  **********************************************************************/
1178 struct pts_pos {
1179     uint64_t pos;   /* file position of this PTS sample */
1180     uint64_t pts;   /* PTS from video stream */
1181 };
1182
1183 #define NDURSAMPLES 128
1184
1185 // get one (position, timestamp) sampple from a transport or program
1186 // stream.
1187 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
1188 {
1189     struct pts_pos pp = { 0, 0 };
1190
1191     if ( stream->hb_stream_type == transport )
1192     {
1193         const uint8_t *buf;
1194         fseeko( stream->file_handle, fpos, SEEK_SET );
1195         align_to_next_packet( stream );
1196         int pid = stream->ts_pids[index_of_video(stream)];
1197         buf = hb_ts_stream_getPEStype( stream, pid );
1198         if ( buf == NULL )
1199         {
1200             hb_log("hb_sample_pts: couldn't find video packet near %"PRIu64, fpos);
1201             return pp;
1202         }
1203         if ( ( buf[7] >> 7 ) != 1 )
1204         {
1205             hb_log("hb_sample_pts: no PTS in video packet near %"PRIu64, fpos);
1206             return pp;
1207         }
1208         pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
1209                  ( (uint64_t)buf[10] << 22 ) |
1210                  ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
1211                  ( (uint64_t)buf[12] << 7 ) |
1212                  ( (uint64_t)buf[13] >> 1 );
1213
1214         if ( isIframe( stream, buf, -4 ) )
1215         {
1216             if (  stream->ts_IDRs < 255 )
1217             {
1218                 ++stream->ts_IDRs;
1219             }
1220         }
1221     }
1222     else
1223     {
1224         // round address down to nearest dvd sector start
1225         fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
1226         fseeko( stream->file_handle, fpos, SEEK_SET );
1227         if ( stream->hb_stream_type == program )
1228         {
1229             skip_to_next_pack( stream );
1230         }
1231         pp.pts = hb_ps_stream_getVideoPTS( stream );
1232     }
1233     pp.pos = ftello(stream->file_handle);
1234     return pp;
1235 }
1236
1237 static int dur_compare( const void *a, const void *b )
1238 {
1239     const double *aval = a, *bval = b;
1240     return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
1241 }
1242
1243 // given an array of (position, time) samples, compute a max-likelihood
1244 // estimate of the average rate by computing the rate between all pairs
1245 // of samples then taking the median of those rates.
1246 static double compute_stream_rate( struct pts_pos *pp, int n )
1247 {
1248     int i, j;
1249     double rates[NDURSAMPLES * NDURSAMPLES / 8];
1250     double *rp = rates;
1251
1252     // the following nested loops compute the rates between all pairs.
1253     *rp = 0;
1254     for ( i = 0; i < n-1; ++i )
1255     {
1256         // Bias the median filter by not including pairs that are "far"
1257         // from one another. This is to handle cases where the file is
1258         // made of roughly equal size pieces where a symmetric choice of
1259         // pairs results in having the same number of intra-piece &
1260         // inter-piece rate estimates. This would mean that the median
1261         // could easily fall in the inter-piece part of the data which
1262         // would give a bogus estimate. The 'ns' index creates an
1263         // asymmetry that favors locality.
1264         int ns = i + ( n >> 3 );
1265         if ( ns > n )
1266             ns = n;
1267         for ( j = i+1; j < ns; ++j )
1268         {
1269             if ( (uint64_t)(pp[j].pts - pp[i].pts) > 90000LL*3600*6 )
1270                 break;
1271             if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
1272             {
1273                 *rp = ((double)( pp[j].pts - pp[i].pts )) /
1274                       ((double)( pp[j].pos - pp[i].pos ));
1275                 ++rp;
1276             }
1277         }
1278     }
1279     // now compute and return the median of all the (n*n/2) rates we computed
1280     // above.
1281     int nrates = rp - rates;
1282     qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
1283     return rates[nrates >> 1];
1284 }
1285
1286 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
1287 {
1288     struct pts_pos ptspos[NDURSAMPLES];
1289     struct pts_pos *pp = ptspos;
1290     int i;
1291
1292     fseeko(stream->file_handle, 0, SEEK_END);
1293     uint64_t fsize = ftello(stream->file_handle);
1294     uint64_t fincr = fsize / NDURSAMPLES;
1295     uint64_t fpos = fincr / 2;
1296     for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
1297     {
1298         *pp++ = hb_sample_pts(stream, fpos);
1299     }
1300     uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
1301     inTitle->duration = dur;
1302     dur /= 90000;
1303     inTitle->hours    = dur / 3600;
1304     inTitle->minutes  = ( dur % 3600 ) / 60;
1305     inTitle->seconds  = dur % 60;
1306
1307     rewind(stream->file_handle);
1308 }
1309
1310 /***********************************************************************
1311  * hb_stream_read
1312  ***********************************************************************
1313  *
1314  **********************************************************************/
1315 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
1316 {
1317     if ( src_stream->hb_stream_type == ffmpeg )
1318     {
1319         return ffmpeg_read( src_stream, b );
1320     }
1321     if ( src_stream->hb_stream_type == dvd_program )
1322     {
1323         size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
1324                                 src_stream->file_handle);
1325         return (amt_read > 0);
1326     }
1327     if ( src_stream->hb_stream_type == program )
1328     {
1329         // a general program stream has arbitrary sized pack's. we're
1330         // currently positioned at the start of a pack so read up to but
1331         // not including the start of the next, expanding the buffer
1332         // as necessary.
1333         uint8_t *cp = b->data;
1334         uint8_t *ep = cp + b->alloc;
1335         uint32_t strt_code = -1;
1336         int c;
1337
1338         // consume the first byte of the initial pack so we don't match on
1339         // it in the loop below.
1340         if ( ( c = getc( src_stream->file_handle ) ) == EOF )
1341             return 0;
1342
1343         *cp++ = c;
1344
1345         flockfile( src_stream->file_handle );
1346         while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
1347         {
1348             strt_code = ( strt_code << 8 ) | c;
1349             if ( strt_code == 0x000001ba )
1350                 // we found the start of the next pack
1351                 break;
1352             if ( cp >= ep )
1353             {
1354                 // need to expand the buffer
1355                 int curSize = cp - b->data;
1356                 hb_buffer_realloc( b, curSize * 2 );
1357                 cp = b->data + curSize;
1358                 ep = b->data + b->alloc;
1359             }
1360             *cp++ = c;
1361             // Non-video streams can emulate start codes, so we need
1362             // to inspect PES packets and skip over their data
1363             // sections to avoid mis-detection of the next pack header.
1364             if ( ( strt_code >> 8 ) == 0x000001 &&
1365                  ( strt_code & 0xff ) >= 0xbb )
1366             {
1367                 int len = 0;
1368                 c = getc_unlocked( src_stream->file_handle );
1369                 if ( c == EOF )
1370                     break;
1371                 len = c << 8;
1372                 c = getc_unlocked( src_stream->file_handle );
1373                 if ( c == EOF )
1374                     break;
1375                 len |= c;
1376                 if ( cp+len+2 > ep )
1377                 {
1378                     // need to expand the buffer
1379                     int curSize = cp - b->data;
1380                     if ( curSize * 2 > curSize+len+2 )
1381                         hb_buffer_realloc( b, curSize * 2 );
1382                     else
1383                         hb_buffer_realloc( b, curSize + len + 2 );
1384                     cp = b->data + curSize;
1385                     ep = b->data + b->alloc;
1386                 }
1387                 *cp++ = len >> 8;
1388                 *cp++ = len & 0xff;
1389                 fread( cp, 1, len, src_stream->file_handle );
1390                 cp += len;
1391             }
1392         }
1393         funlockfile( src_stream->file_handle );
1394
1395         // if we didn't terminate on an eof back up so the next read
1396         // starts on the pack boundary.
1397         b->size = cp - b->data;
1398         if ( c != EOF )
1399         {
1400             fseeko( src_stream->file_handle, -4, SEEK_CUR );
1401             // Only 3 of the 4 bytes read were added to the buffer.
1402             b->size -= 3;
1403         }
1404         return 1;
1405     }
1406     return hb_ts_stream_decode( src_stream, b );
1407 }
1408
1409 int64_t ffmpeg_initial_timestamp( hb_stream_t * stream )
1410 {
1411     AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_video_id];
1412     if ( s->nb_index_entries < 1 )
1413         return 0;
1414
1415     return s->index_entries[0].timestamp;
1416 }
1417 int hb_stream_seek_chapter( hb_stream_t * stream, int chapter_num )
1418 {
1419
1420     if ( stream->hb_stream_type != ffmpeg )
1421     {
1422         // currently meaningliess for transport and program streams
1423         return 1;
1424     }
1425     if ( !stream || !stream->title ||
1426          chapter_num > hb_list_count( stream->title->list_chapter ) )
1427     {
1428         return 0;
1429     }
1430
1431     int64_t sum_dur = 0;
1432     hb_chapter_t *chapter = NULL;
1433     int i;
1434     for ( i = 0; i < chapter_num; ++i)
1435     {
1436         chapter = hb_list_item( stream->title->list_chapter, i );
1437         sum_dur += chapter->duration;
1438     }
1439     stream->chapter = chapter_num - 1;
1440     stream->chapter_end = sum_dur;
1441
1442     int64_t pos = ( ( ( sum_dur - chapter->duration ) * AV_TIME_BASE ) / 90000 ) + ffmpeg_initial_timestamp( stream );
1443
1444     hb_deep_log( 2, "Seeking to chapter %d: starts %"PRId64", ends %"PRId64", AV pos %"PRId64,
1445                  chapter_num, sum_dur - chapter->duration, sum_dur, pos);
1446
1447     if ( chapter_num > 1 && pos > 0 )
1448     {
1449         av_seek_frame( stream->ffmpeg_ic, -1, pos, 0);
1450     }
1451     else
1452     {
1453         // ffmpeg has a bug that causes the first PTS after
1454         // av_find_stream_info() is called to be incorrect.
1455         // av_find_stream_info is called whenever opening a file
1456         // with ffmpeg.  av_seek_frame clears the condition
1457         // that causes the problem. since hb_stream_seek_chapter
1458         // is called before we start reading, make sure
1459         // we do a seek here.
1460         av_seek_frame( stream->ffmpeg_ic, -1, ffmpeg_initial_timestamp( stream ), AVSEEK_FLAG_BACKWARD );
1461     }
1462     return 1;
1463 }
1464
1465 /***********************************************************************
1466  * hb_stream_chapter
1467  ***********************************************************************
1468  * Return the number of the chapter that we are currently in. We store
1469  * the chapter number starting from 0, so + 1 for the real chpater num.
1470  **********************************************************************/
1471 int hb_stream_chapter( hb_stream_t * src_stream )
1472 {
1473     return( src_stream->chapter + 1 );
1474 }
1475
1476 /***********************************************************************
1477  * hb_stream_seek
1478  ***********************************************************************
1479  *
1480  **********************************************************************/
1481 int hb_stream_seek( hb_stream_t * stream, float f )
1482 {
1483     if ( stream->hb_stream_type == ffmpeg )
1484     {
1485         return ffmpeg_seek( stream, f );
1486     }
1487     off_t stream_size, cur_pos, new_pos;
1488     double pos_ratio = f;
1489     cur_pos = ftello( stream->file_handle );
1490     fseeko( stream->file_handle, 0, SEEK_END );
1491     stream_size = ftello( stream->file_handle );
1492     new_pos = (off_t) ((double) (stream_size) * pos_ratio);
1493     new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
1494
1495     int r = fseeko( stream->file_handle, new_pos, SEEK_SET );
1496     if (r == -1)
1497     {
1498         fseeko( stream->file_handle, cur_pos, SEEK_SET );
1499         return 0;
1500     }
1501
1502     if ( stream->hb_stream_type == transport )
1503     {
1504         // We need to drop the current decoder output and move
1505         // forwards to the next transport stream packet.
1506         hb_ts_stream_reset(stream);
1507         if ( f > 0 )
1508         {
1509             if ( stream->ts_IDRs )
1510             {
1511                 // the stream has IDRs so look for one.
1512                 stream->need_keyframe = 1;
1513             }
1514         }
1515         else
1516         {
1517             // we're at the beginning - say we have video sync so that we
1518             // won't drop initial SPS & PPS data on an AVC stream.
1519             stream->need_keyframe = 0;
1520         }
1521     }
1522     else if ( stream->hb_stream_type == program )
1523     {
1524         skip_to_next_pack( stream );
1525     }
1526
1527     return 1;
1528 }
1529
1530 int hb_stream_seek_ts( hb_stream_t * stream, int64_t ts )
1531 {
1532     if ( stream->hb_stream_type == ffmpeg )
1533     {
1534         return ffmpeg_seek_ts( stream, ts );
1535     }
1536     return -1;
1537 }
1538
1539 static const char* make_upper( const char* s )
1540 {
1541     static char name[8];
1542     char *cp = name;
1543     char *ep = cp + sizeof(name)-1;
1544
1545     while ( *s && cp < ep )
1546     {
1547         *cp++ = islower(*s)? toupper(*s) : *s;
1548         ++s;
1549     }
1550     *cp = 0;
1551     return name;
1552 }
1553
1554 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1555 {
1556     /* XXX
1557      * This is a duplicate of code in dvd.c - it should get factored out
1558      * into a common routine. We probably should only be putting the lang
1559      * code or a lang pointer into the audio config & let the common description
1560      * formatting routine in scan.c do all the stuff below.
1561      */
1562     const char *codec_name;
1563     AVCodecContext *cc;
1564
1565     if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1566          ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1567          avcodec_find_decoder( cc->codec_id ) )
1568     {
1569         codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1570         if ( !strcmp( codec_name, "LIBFAAD" ) )
1571         {
1572             codec_name = "AAC";
1573         }
1574     }
1575     else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1576               avcodec_find_decoder( audio->config.in.codec_param ) )
1577     {
1578         codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1579     }
1580     else
1581     {
1582         codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1583                      audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1584                      audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" : 
1585                      audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" : 
1586                      audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1587                      "Unknown";
1588     }
1589     snprintf( audio->config.lang.description,
1590               sizeof( audio->config.lang.description ), "%s (%s)",
1591               strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1592               codec_name );
1593
1594     if (audio->config.in.codec == HB_ACODEC_FFMPEG)
1595     {
1596         int layout = audio->config.in.channel_layout;
1597         char *desc = audio->config.lang.description +
1598                         strlen( audio->config.lang.description );
1599         sprintf( desc, " (%d.%d ch)",
1600                  HB_INPUT_CH_LAYOUT_GET_DISCRETE_FRONT_COUNT(layout) +
1601                      HB_INPUT_CH_LAYOUT_GET_DISCRETE_REAR_COUNT(layout),
1602                  HB_INPUT_CH_LAYOUT_GET_DISCRETE_LFE_COUNT(layout) );
1603     }
1604
1605     snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1606               strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1607     snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1608               "%s", lang->iso639_2);
1609 }
1610
1611 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1612                                                        int idx)
1613 {
1614     off_t cur_pos = ftello(stream->file_handle);
1615     hb_audio_t *audio = NULL;
1616     const uint8_t *buf;
1617     kind_t kind;
1618     uint8_t stype = 0;
1619
1620     kind = stream->ts_stream_kind[idx];
1621
1622     if ( kind != A && kind != U && kind != N )
1623     {
1624         // Not audio
1625         return NULL;
1626     }
1627     stype = stream->ts_stream_type[idx];
1628
1629     fseeko(stream->file_handle, 0, SEEK_SET);
1630     align_to_next_packet(stream);
1631
1632     buf = hb_ts_stream_getPEStype(stream, stream->ts_pids[idx]);
1633
1634     /* check that we found a PES header */
1635     if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1636     {
1637         // 0xbd ("private stream 1") is the normal container for non-ISO
1638         // media - AC3/DCA/PCM/etc.
1639         if ( buf[3] == 0xbd )
1640         {
1641             if ( kind == U )
1642             {
1643                 // XXX assume unknown stream types are AC-3 (if they're not
1644                 // audio we'll find that out during the scan but if they're
1645                 // some other type of audio we'll end up ignoring them).
1646                 stype = 0x81;
1647                 stream->ts_stream_type[idx] = 0x81;
1648                 kind = A;
1649             }
1650             if ( stype == 0x80 && 
1651                  stream->pmt_info.reg_desc == STR4_TO_UINT32("HDMV") )
1652             {
1653                 // LPCM audio in bluray have an stype of 0x80
1654                 // 0x80 is used for other DigiCipher normally
1655                 // To distinguish, Bluray streams have a reg_desc of HDMV
1656                 kind = A;
1657             }
1658         }
1659         else if ( buf[3] == 0xfd )
1660         {
1661             // 0xfd indicates an extended stream id (ISO 13818-1(2007)).
1662             // the blu ray consortium apparently forgot to read the portion
1663             // of the MPEG spec that says one PID should map to one media
1664             // stream and multiplexed multiple types of audio into one PID
1665             // using the extended stream identifier of the PES header to
1666             // distinguish them. So we have to check if that's happening and
1667             // if so tell the runtime what esid we want.
1668             if ( st2codec[stype].kind == A && stype == 0x83 &&
1669                  stream->ts_format_id[idx] == TS_FORMAT_ID_AC3 )
1670             {
1671                 // This is an interleaved TrueHD/AC-3 stream and the esid of
1672                 // the AC-3 is 0x76
1673                 stream->ts_multiplexed[idx] = 0x76;
1674                 stype = 0x81;
1675                 stream->ts_stream_type[idx] = 0x81;
1676                 kind = A;
1677             }
1678             if ( st2codec[stype].kind == A && stype == 0x86 )
1679             {
1680                 // This is an interleaved DTS-HD/DTS stream and the esid of
1681                 // the DTS is 0x71
1682                 stream->ts_multiplexed[idx] = 0x71;
1683                 stype = 0x82;
1684                 stream->ts_stream_type[idx] = 0x82;
1685                 kind = A;
1686             }
1687         }
1688         else if ((buf[3] & 0xe0) == 0xc0)
1689         {
1690             // 0xC0 - 0xCF are the normal containers for ISO-standard
1691             // media (mpeg2 audio and mpeg4 AAC).
1692             if ( st2codec[stype].kind == U )
1693             {
1694                 // XXX assume unknown stream types are MPEG audio
1695                 stype = 0x03;
1696                 stream->ts_stream_type[idx] = 0x03;
1697                 kind = A;
1698             }
1699         }
1700         else
1701         {
1702             stype = 0;
1703             kind = N;
1704         }
1705     }
1706
1707     // if we found an audio stream type & HB has a codec that can decode it
1708     // finish configuring the audio so we'll add it to the title's list.
1709     if ( kind == A && st2codec[stype].codec )
1710     {
1711         audio = calloc( sizeof( hb_audio_t ), 1 );
1712
1713         stream->ts_stream_kind[idx] = A;
1714         audio->id = stream->ts_pids[idx];
1715         audio->config.in.codec = st2codec[stype].codec;
1716         audio->config.in.codec_param = st2codec[stype].codec_param;
1717         set_audio_description( audio,
1718                   lang_for_code( stream->a52_info[idx].lang_code ) );
1719         hb_log("transport stream pid 0x%x (type 0x%x) may be %s audio (id 0x%x)",
1720                stream->ts_pids[idx],
1721                stype, st2codec[stype].name, audio->id);
1722
1723     }
1724     else
1725     {
1726         if ( buf )
1727         {
1728             hb_log("transport stream pid 0x%x (type 0x%x, substream 0x%x) "
1729                     "isn't audio", stream->ts_pids[idx],
1730                     stream->ts_stream_type[idx], buf[3]);
1731         }
1732         else
1733         {
1734             hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1735                     stream->ts_pids[idx],
1736                     stream->ts_stream_type[idx]);
1737         }
1738     }
1739     fseeko(stream->file_handle, cur_pos, SEEK_SET);
1740
1741     return audio;
1742 }
1743
1744 static void add_audio_to_title(hb_title_t *title, int id)
1745 {
1746     hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1747
1748     audio->id = id;
1749     switch ( id >> 12 )
1750     {
1751         case 0x0:
1752             audio->config.in.codec = HB_ACODEC_MPGA;
1753             hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1754             break;
1755         case 0x2:
1756             // type 2 is a DVD subtitle stream - just ignore it */
1757             free( audio );
1758             return;
1759         case 0x8:
1760             audio->config.in.codec = HB_ACODEC_AC3;
1761             hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1762             break;
1763         case 0xa:
1764             audio->config.in.codec = HB_ACODEC_LPCM;
1765             hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1766             break;
1767         default:
1768             hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1769             free( audio );
1770             return;
1771
1772     }
1773     set_audio_description( audio, lang_for_code( 0 ) );
1774     hb_list_add( title->list_audio, audio );
1775 }
1776
1777 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1778 {
1779     off_t cur_pos = ftello(stream->file_handle);
1780     hb_buffer_t *buf  = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1781     hb_list_t *list = hb_list_init();
1782     // how many blocks we read while searching for audio streams
1783     int blksleft = 4096;
1784     // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1785     // so we use a bitmap to keep track of the ones we've already seen.
1786     // Bit 'i' of smap is set if we've already added the audio for
1787     // audio substream id 'i' to the title's audio list.
1788     uint32_t smap = 0;
1789
1790     // start looking 20% into the file since there's occasionally no
1791     // audio at the beginning (particularly for vobs).
1792     hb_stream_seek(stream, 0.2f);
1793
1794     while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1795     {
1796         hb_buffer_t *es;
1797
1798         // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1799         hb_demux_ps( buf, list, 0 );
1800
1801         while ( ( es = hb_list_item( list, 0 ) ) )
1802         {
1803             hb_list_rem( list, es );
1804             if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1805             {
1806                 // this PES contains some kind of audio - get the substream id
1807                 // and check if we've seen it already.
1808                 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1809                 if ( (smap & (1 << ssid)) == 0 )
1810                 {
1811                     // we haven't seen this stream before - add it to the
1812                     // title's list of audio streams.
1813                     smap |= (1 << ssid);
1814                     add_audio_to_title(title, es->id);
1815                 }
1816             }
1817             hb_buffer_close( &es );
1818         }
1819     }
1820     hb_list_empty( &list );
1821     hb_buffer_close(&buf);
1822     fseeko(stream->file_handle, cur_pos, SEEK_SET);
1823 }
1824
1825 /***********************************************************************
1826  * hb_ts_stream_init
1827  ***********************************************************************
1828  *
1829  **********************************************************************/
1830
1831 static void hb_ts_stream_init(hb_stream_t *stream)
1832 {
1833     int i;
1834
1835     for (i=0; i < kMaxNumberDecodeStreams; i++)
1836     {
1837         stream->ts_streamcont[i] = -1;
1838         stream-> ts_pids[i] = -1;
1839     }
1840     stream->ts_packet = malloc( stream->packetsize );
1841
1842     // Find the audio and video pids in the stream
1843     hb_ts_stream_find_pids(stream);
1844
1845     for (i = 0; i < stream->ts_number_pids; i++)
1846     {
1847         // demuxing buffer for TS to PS conversion
1848         stream->ts_buf[i] = hb_buffer_init(stream->packetsize);
1849         stream->ts_buf[i]->size = 0;
1850     }
1851 }
1852
1853 #define MAX_HOLE 208*80
1854
1855 static off_t align_to_next_packet(hb_stream_t *stream)
1856 {
1857     uint8_t buf[MAX_HOLE];
1858     off_t pos = 0;
1859     off_t start = ftello(stream->file_handle);
1860     off_t orig;
1861
1862     if ( start >= stream->packetsize ) {
1863         start -= stream->packetsize;
1864         fseeko(stream->file_handle, start, SEEK_SET);
1865     }
1866     orig = start;
1867
1868     while (1)
1869     {
1870         if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1871         {
1872             const uint8_t *bp = buf;
1873             int i;
1874
1875             for ( i = sizeof(buf) - 8 * stream->packetsize; --i >= 0; ++bp )
1876             {
1877                 if ( have_ts_sync( bp, stream->packetsize ) )
1878                 {
1879                     break;
1880                 }
1881             }
1882             if ( i >= 0 )
1883             {
1884                 pos = ( bp - buf ) - stream->packetsize + 188;
1885                 break;
1886             }
1887             fseeko(stream->file_handle, -8 * stream->packetsize, SEEK_CUR);
1888             start = ftello(stream->file_handle);
1889         }
1890         else
1891         {
1892             return 0;
1893         }
1894     }
1895     fseeko(stream->file_handle, start+pos, SEEK_SET);
1896     return start - orig + pos;
1897 }
1898
1899
1900 typedef struct {
1901     uint8_t *buf;
1902     uint32_t val;
1903     int pos;
1904 } bitbuf_t;
1905
1906 static const unsigned int bitmask[] = {
1907     0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1908     0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1909     0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1910     0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1911
1912 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1913 {
1914     bb->pos = 0;
1915     bb->buf = buf;
1916     bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1917               (bb->buf[2] << 8) | bb->buf[3];
1918     if (clear)
1919         memset(bb->buf, 0, bufsize);
1920 }
1921
1922 static inline int buf_size(bitbuf_t *bb)
1923 {
1924     return bb->pos >> 3;
1925 }
1926
1927 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1928 {
1929     unsigned int val;
1930     int left = 32 - (bb->pos & 31);
1931
1932     if (bits < left)
1933     {
1934         val = (bb->val >> (left - bits)) & bitmask[bits];
1935         bb->pos += bits;
1936     }
1937     else
1938     {
1939         val = (bb->val & bitmask[left]) << (bits - left);
1940         bb->pos += left;
1941         bits -= left;
1942
1943         int pos = bb->pos >> 3;
1944         bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1945
1946         if (bits > 0)
1947         {
1948             val |= (bb->val >> (32 - bits)) & bitmask[bits];
1949             bb->pos += bits;
1950         }
1951     }
1952
1953     return val;
1954 }
1955
1956 // extract what useful information we can from the elementary stream
1957 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1958 // Descriptors with info we don't currently use are ignored.
1959 // The descriptor list & descriptor item formats are defined in
1960 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1961 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1962                                        const uint8_t *dp, uint8_t dlen)
1963 {
1964     const uint8_t *ep = dp + dlen;
1965
1966     while (dp < ep)
1967     {
1968         switch (dp[0])
1969         {
1970             case 5:    // Registration descriptor
1971                 stream->ts_format_id[esindx] = (dp[2] << 24) | (dp[3] << 16) |
1972                                                (dp[4] << 8)  | dp[5];
1973                 break;
1974
1975             case 10:    // ISO_639_language descriptor
1976                 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1977                 break;
1978
1979             case 0x6a:  // DVB AC-3 descriptor
1980                 stream->ts_stream_type[esindx] = 0x81;
1981                 break;
1982
1983             default:
1984                 break;
1985         }
1986         dp += dp[1] + 2;
1987     }
1988 }
1989
1990 static const char *stream_type_name (uint8_t stream_type)
1991 {
1992     return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
1993 }
1994
1995 int decode_program_map(hb_stream_t* stream)
1996 {
1997     bitbuf_t bb;
1998     set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1999
2000     get_bits(&bb, 8);  // table_id
2001     get_bits(&bb, 4);
2002     unsigned int section_length = get_bits(&bb, 12);
2003     stream->pmt_info.section_length = section_length;
2004
2005     unsigned int program_number = get_bits(&bb, 16);
2006     stream->pmt_info.program_number = program_number;
2007     get_bits(&bb, 2);
2008     get_bits(&bb, 5);  // version_number
2009     get_bits(&bb, 1);
2010     get_bits(&bb, 8);  // section_number
2011     get_bits(&bb, 8);  // last_section_number
2012     get_bits(&bb, 3);
2013     stream->pmt_info.PCR_PID = get_bits(&bb, 13);
2014     get_bits(&bb, 4);
2015     int program_info_length = get_bits(&bb, 12);
2016     stream->pmt_info.program_info_length = program_info_length;
2017
2018     int i;
2019     for (i = 0; i < program_info_length - 2; )
2020     {
2021         uint8_t tag, len;
2022         tag = get_bits(&bb, 8);
2023         len = get_bits(&bb, 8);
2024         i += 2;
2025         if ( i + len > program_info_length )
2026         {
2027             break;
2028         }
2029         if (tag == 0x05 && len >= 4)
2030         {
2031             // registration descriptor
2032             stream->pmt_info.reg_desc = get_bits(&bb, 32);
2033             i += 4;
2034             len -= 4;
2035         }
2036         int j;
2037         for ( j = 0; j < len; j++ )
2038         {
2039             get_bits(&bb, 8);
2040         }
2041         i += len;
2042     }
2043     for ( ; i < program_info_length; i++ )
2044     {
2045         get_bits(&bb, 8);
2046     }
2047
2048     int cur_pos =  9 /* data after the section length field*/ + program_info_length;
2049     int done_reading_stream_types = 0;
2050     while (!done_reading_stream_types)
2051     {
2052         unsigned char stream_type = get_bits(&bb, 8);
2053         get_bits(&bb, 3);
2054         unsigned int elementary_PID = get_bits(&bb, 13);
2055         get_bits(&bb, 4);
2056         unsigned int ES_info_length = get_bits(&bb, 12);
2057
2058         int i=0;
2059         unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
2060         for (i=0; i < ES_info_length; i++)
2061         {
2062             ES_info_buf[i] = get_bits(&bb, 8);
2063         }
2064
2065         if ( index_of_pid( stream, elementary_PID ) < 0 )
2066         {
2067             // Defined audio stream types are 0x81 for AC-3/A52 audio 
2068             // and 0x03 for mpeg audio. But content producers seem to 
2069             // use other values (0x04 and 0x06 have both been observed) 
2070             // so at this point we say everything that isn't a video 
2071             // pid is audio then at the end of hb_stream_title_scan 
2072             // we'll figure out which are really audio by looking at 
2073             // the PES headers.
2074             i = stream->ts_number_pids;
2075             if (i < kMaxNumberDecodeStreams)
2076             {
2077                 stream->ts_pids[i] = elementary_PID;
2078                 stream->ts_stream_type[i] = stream_type;
2079                 if (ES_info_length > 0)
2080                 {
2081                     decode_element_descriptors(stream, i, ES_info_buf,
2082                                             ES_info_length);
2083                 }
2084                 stream->ts_stream_kind[i] = ts_stream_kind(stream, i);
2085                 ++stream->ts_number_pids;
2086             }
2087         }
2088
2089         cur_pos += 5 /* stream header */ + ES_info_length;
2090
2091         free(ES_info_buf);
2092
2093         if (cur_pos >= section_length - 4 /* stop before the CRC */)
2094             done_reading_stream_types = 1;
2095     }
2096
2097     return 1;
2098 }
2099
2100 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
2101 {
2102     // Get adaption header info
2103     int adapt_len = 0;
2104     int adaption = (buf[3] & 0x30) >> 4;
2105     if (adaption == 0)
2106             return 0;
2107     else if (adaption == 0x2)
2108             adapt_len = 184;
2109     else if (adaption == 0x3)
2110             adapt_len = buf[4] + 1;
2111     if (adapt_len > 184)
2112             return 0;
2113
2114     // Get payload start indicator
2115     int start;
2116     start = (buf[1] & 0x40) != 0;
2117
2118     // Get pointer length - only valid in packets with a start flag
2119     int pointer_len = 0;
2120
2121     if (start)
2122     {
2123         pointer_len = buf[4 + adapt_len] + 1;
2124         stream->pmt_info.tablepos = 0;
2125     }
2126     // Get Continuity Counter
2127     int continuity_counter = buf[3] & 0x0f;
2128     if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
2129     {
2130         hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
2131         return 0;
2132     }
2133     stream->pmt_info.current_continuity_counter = continuity_counter;
2134     stream->pmt_info.reading |= start;
2135
2136     // Add the payload for this packet to the current buffer
2137     int amount_to_copy = 184 - adapt_len - pointer_len;
2138     if (stream->pmt_info.reading && (amount_to_copy > 0))
2139     {
2140             stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
2141
2142             memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
2143             stream->pmt_info.tablepos += amount_to_copy;
2144     }
2145     if (stream->pmt_info.tablepos > 3)
2146     {
2147         // We have enough to check the section length
2148         int length;
2149         length = ((stream->pmt_info.tablebuf[1] << 8) + 
2150                   stream->pmt_info.tablebuf[2]) & 0xFFF;
2151         if (stream->pmt_info.tablepos > length + 1)
2152         {
2153             // We just finished a bunch of packets - parse the program map details
2154             int decode_ok = 0;
2155             if (stream->pmt_info.tablebuf[0] == 0x02)
2156                 decode_ok = decode_program_map(stream);
2157             free(stream->pmt_info.tablebuf);
2158             stream->pmt_info.tablebuf = NULL;
2159             stream->pmt_info.tablepos = 0;
2160             stream->pmt_info.reading = 0;
2161             if (decode_ok)
2162                 return decode_ok;
2163         }
2164
2165     }
2166
2167     return 0;
2168 }
2169
2170 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
2171 {
2172     unsigned char tablebuf[1024];
2173     unsigned int tablepos = 0;
2174
2175     int reading = 0;
2176
2177
2178     // Get adaption header info
2179     int adapt_len = 0;
2180     int adaption = (buf[3] & 0x30) >> 4;
2181     if (adaption == 0)
2182             return 0;
2183     else if (adaption == 0x2)
2184             adapt_len = 184;
2185     else if (adaption == 0x3)
2186             adapt_len = buf[4] + 1;
2187     if (adapt_len > 184)
2188             return 0;
2189
2190     // Get pointer length
2191     int pointer_len = buf[4 + adapt_len] + 1;
2192
2193     // Get payload start indicator
2194     int start;
2195     start = (buf[1] & 0x40) != 0;
2196
2197     if (start)
2198             reading = 1;
2199
2200     // Add the payload for this packet to the current buffer
2201     if (reading && (184 - adapt_len) > 0)
2202     {
2203             if (tablepos + 184 - adapt_len - pointer_len > 1024)
2204             {
2205                     hb_log("decode_PAT - Bad program section length (> 1024)");
2206                     return 0;
2207             }
2208             memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
2209             tablepos += 184 - adapt_len - pointer_len;
2210     }
2211
2212     if (start && reading)
2213     {
2214             memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
2215
2216
2217             unsigned int pos = 0;
2218             //while (pos < tablepos)
2219             {
2220                     bitbuf_t bb;
2221                     set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
2222
2223                     unsigned char section_id    = get_bits(&bb, 8);
2224                     get_bits(&bb, 4);
2225                     unsigned int section_len    = get_bits(&bb, 12);
2226                     get_bits(&bb, 16); // transport_id
2227                     get_bits(&bb, 2);
2228                     get_bits(&bb, 5);  // version_num
2229                     get_bits(&bb, 1);  // current_next
2230                     get_bits(&bb, 8);  // section_num
2231                     get_bits(&bb, 8);  // last_section
2232
2233                     switch (section_id)
2234                     {
2235                       case 0x00:
2236                         {
2237                           // Program Association Section
2238                           section_len -= 5;    // Already read transport stream ID, version num, section num, and last section num
2239                           section_len -= 4;   // Ignore the CRC
2240                           int curr_pos = 0;
2241                           stream->ts_number_pat_entries = 0;
2242                           while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
2243                           {
2244                             unsigned int pkt_program_num = get_bits(&bb, 16);
2245                             stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
2246
2247                             get_bits(&bb, 3);  // Reserved
2248                             if (pkt_program_num == 0)
2249                             {
2250                               get_bits(&bb, 13); // pkt_network_id
2251                             }
2252                             else
2253                             {
2254                               unsigned int pkt_program_map_PID = get_bits(&bb, 13);
2255                                 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
2256                             }
2257                             curr_pos += 4;
2258                             stream->ts_number_pat_entries++;
2259                           }
2260                         }
2261                         break;
2262                       case 0xC7:
2263                             {
2264                                     break;
2265                             }
2266                       case 0xC8:
2267                             {
2268                                     break;
2269                             }
2270                     }
2271
2272                     pos += 3 + section_len;
2273             }
2274
2275             tablepos = 0;
2276     }
2277     return 1;
2278 }
2279
2280 static void hb_ts_stream_find_pids(hb_stream_t *stream)
2281 {
2282     // To be different from every other broadcaster in the world, New Zealand TV
2283     // changes PMTs (and thus video & audio PIDs) when 'programs' change. Since
2284     // we may have the tail of the previous program at the beginning of this
2285     // file, take our PMT from the middle of the file.
2286     fseeko(stream->file_handle, 0, SEEK_END);
2287     uint64_t fsize = ftello(stream->file_handle);
2288     fseeko(stream->file_handle, fsize >> 1, SEEK_SET);
2289     align_to_next_packet(stream);
2290
2291     // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
2292     // to find the program map PID and then decode that to get the list of audio and video PIDs
2293
2294     for (;;)
2295     {
2296         const uint8_t *buf = next_packet( stream );
2297
2298         if ( buf == NULL )
2299         {
2300             hb_log("hb_ts_stream_find_pids - end of file");
2301             break;
2302         }
2303
2304         // Get pid
2305         int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
2306
2307         if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
2308         {
2309           decode_PAT(buf, stream);
2310           continue;
2311         }
2312
2313         int pat_index = 0;
2314         for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
2315         {
2316             // There are some streams where the PAT table has multiple entries as if their are
2317             // multiple programs in the same transport stream, and yet there's actually only one
2318             // program really in the stream. This seems to be true for transport streams that
2319             // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
2320             // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
2321             // but the EyeTV is only recording a single (selected) program number and not rewriting the
2322             // PAT info on export to match what's actually on the stream.
2323             // Until we have a way of handling multiple programs per transport stream elegantly we'll match
2324             // on the first pat entry for which we find a matching program map PID.  The ideal solution would
2325             // be to build a title choice popup from the PAT program number details and then select from
2326             // their - but right now the API's not capable of that.
2327             if (stream->pat_info[pat_index].program_number != 0 &&
2328                 pid == stream->pat_info[pat_index].program_map_PID)
2329             {
2330               if (build_program_map(buf, stream) > 0)
2331                 break;
2332             }
2333         }
2334         // Keep going  until we have a complete set of PIDs
2335         if ( index_of_video( stream ) >= 0 )
2336           break;
2337     }
2338
2339     hb_log("hb_ts_stream_find_pids - found the following PIDS");
2340     hb_log("    Video PIDS : ");
2341     int i;
2342     for (i=0; i < stream->ts_number_pids; i++)
2343     {
2344         if ( stream->ts_stream_kind[i] == V )
2345         {
2346             hb_log( "      0x%x type %s (0x%x)", 
2347                     stream->ts_pids[i],
2348                     stream_type_name(stream->ts_stream_type[i]),
2349                     stream->ts_stream_type[i]);
2350         }
2351     }
2352     hb_log("    Audio PIDS : ");
2353     for (i = 0; i < stream->ts_number_pids; i++)
2354     {
2355         if ( stream->ts_stream_kind[i] != V )
2356         {
2357             hb_log( "      0x%x type %s (0x%x)", 
2358                     stream->ts_pids[i],
2359                     stream_type_name(stream->ts_stream_type[i]),
2360                     stream->ts_stream_type[i] );
2361         }
2362     }
2363  }
2364
2365
2366 static void fwrite64( hb_stream_t *stream, void *buf, int len )
2367 {
2368     if ( len > 0 )
2369     {
2370         int pos = stream->fwrite_buf->size;
2371         if ( pos + len > stream->fwrite_buf->alloc )
2372         {
2373             int size = MAX(stream->fwrite_buf->alloc * 2, pos + len);
2374             hb_buffer_realloc(stream->fwrite_buf, size);
2375         }
2376         memcpy( &(stream->fwrite_buf->data[pos]), buf, len );
2377         stream->fwrite_buf->size += len;
2378     }
2379 }
2380
2381 // convert a PES PTS or DTS to an int64
2382 static int64_t pes_timestamp( const uint8_t *pes )
2383 {
2384     int64_t ts = ( (uint64_t)(pes[0] & 0xe ) << 29 );
2385     ts |= ( pes[1] << 22 ) | ( ( pes[2] >> 1 ) << 15 ) |
2386           ( pes[3] << 7 ) | ( pes[4] >> 1 );
2387     return ts;
2388 }
2389
2390 static void generate_output_data(hb_stream_t *stream, int curstream)
2391 {
2392     hb_buffer_t *buf = stream->fwrite_buf;
2393     uint8_t *tdat = stream->ts_buf[curstream]->data;
2394
2395     buf->id = stream->ts_pids[curstream];
2396     switch (stream->ts_stream_kind[curstream])
2397     {
2398         case A:
2399             buf->type = AUDIO_BUF;
2400             break;
2401
2402         case V:
2403             buf->type = VIDEO_BUF;
2404             break;
2405
2406         default:
2407             buf->type = OTHER_BUF;
2408             break;
2409     }
2410
2411     // check if this packet was referenced to an older pcr and if that
2412     // pcr was significantly different than the one we're using now.
2413     // (the reason for the uint cast on the pcr difference is that the
2414     // difference is significant if it advanced by more than 200ms or if
2415     // it went backwards by any amount. The negative numbers look like huge
2416     // unsigned ints so the cast allows both conditions to be checked at once.
2417     int bufpcr = stream->ts_buf[curstream]->cur;
2418     int curpcr = stream->ts_pcr_out;
2419     if ( bufpcr && bufpcr < curpcr &&
2420          (uint64_t)(stream->ts_pcrhist[curpcr & 3] - stream->ts_pcrhist[bufpcr & 3]) > 200*90LL )
2421     {
2422         // we've sent up a new pcr but have a packet referenced to an
2423         // old pcr and the difference was enough to trigger a discontinuity
2424         // correction. smash the timestamps or we'll mess up the correction.
2425         buf->start = -1;
2426         buf->renderOffset = -1;
2427     }
2428     else
2429     {
2430         if ( stream->ts_pcr_out != stream->ts_pcr_in )
2431         {
2432             // we have a new pcr
2433             stream->ts_pcr_out = stream->ts_pcr_in;
2434             buf->stop = stream->ts_pcr;
2435             stream->ts_pcrhist[stream->ts_pcr_out & 3] = stream->ts_pcr;
2436         }
2437         else
2438         {
2439             buf->stop = -1;
2440         }
2441
2442         // put the PTS & possible DTS into 'start' & 'renderOffset' then strip
2443         // off the PES header.
2444         if ( tdat[7] & 0xc0 )
2445         {
2446             buf->start = pes_timestamp( tdat + 9 );
2447             buf->renderOffset = ( tdat[7] & 0x40 )? pes_timestamp( tdat + 14 ) :
2448                                                     buf->start;
2449         }
2450         else
2451         {
2452             buf->start = -1;
2453             buf->renderOffset = -1;
2454         }
2455     }
2456     int hlen = tdat[8] + 9;
2457
2458     fwrite64( stream,  tdat + hlen, stream->ts_pos[curstream] - hlen );
2459
2460     stream->ts_pos[curstream] = 0;
2461     stream->ts_buf[curstream]->size = 0;
2462 }
2463
2464 static void hb_ts_stream_append_pkt(hb_stream_t *stream, int idx, const uint8_t *buf, int len)
2465 {
2466     if (stream->ts_pos[idx] + len > stream->ts_buf[idx]->alloc)
2467     {
2468         int size;
2469
2470         size = MAX(stream->ts_buf[idx]->alloc * 2, stream->ts_pos[idx] + len);
2471         hb_buffer_realloc(stream->ts_buf[idx], size);
2472     }
2473     memcpy(stream->ts_buf[idx]->data + stream->ts_pos[idx], buf, len);
2474     stream->ts_pos[idx] += len;
2475     stream->ts_buf[idx]->size += len;
2476 }
2477
2478 /***********************************************************************
2479  * hb_ts_stream_decode
2480  ***********************************************************************
2481  *
2482  **********************************************************************/
2483 int hb_ts_decode_pkt( hb_stream_t *stream, const uint8_t * pkt, hb_buffer_t *obuf )
2484 {
2485     /*
2486      * stash the output buffer pointer in our stream so we don't have to
2487      * pass it & its original value to everything we call.
2488      */
2489     obuf->size = 0;
2490     stream->fwrite_buf = obuf;
2491
2492     int video_index = index_of_video(stream);
2493
2494     int curstream;
2495
2496     /* This next section validates the packet */
2497
2498     // Get pid and use it to find stream state.
2499     int pid = ((pkt[1] & 0x1F) << 8) | pkt[2];
2500     if ( ( curstream = index_of_pid( stream, pid ) ) < 0 )
2501     {
2502         return 0;
2503     }
2504
2505     // Get error
2506     int errorbit = (pkt[1] & 0x80) != 0;
2507     if (errorbit)
2508     {
2509         ts_err( stream, curstream,  "packet error bit set");
2510         return 0;
2511     }
2512
2513     // Get adaption header info
2514     int adaption = (pkt[3] & 0x30) >> 4;
2515     int adapt_len = 0;
2516     if (adaption == 0)
2517     {
2518         ts_err( stream, curstream,  "adaptation code 0");
2519         return 0;
2520     }
2521     else if (adaption == 0x2)
2522         adapt_len = 184;
2523     else if (adaption == 0x3)
2524     {
2525         adapt_len = pkt[4] + 1;
2526         if (adapt_len > 184)
2527         {
2528             ts_err( stream, curstream,  "invalid adapt len %d", adapt_len);
2529             return 0;
2530         }
2531     }
2532
2533     if ( adapt_len > 0 )
2534     {
2535         if ( pkt[5] & 0x40 )
2536         {
2537             // found a random access point
2538         }
2539         // if there's an adaptation header & PCR_flag is set
2540         // get the PCR (Program Clock Reference)
2541         if ( adapt_len > 7 && ( pkt[5] & 0x10 ) != 0 )
2542         {
2543             stream->ts_pcr = ( (uint64_t)pkt[6] << (33 - 8) ) |
2544                              ( (uint64_t)pkt[7] << (33 - 16) ) |
2545                              ( (uint64_t)pkt[8] << (33 - 24) ) |
2546                              ( (uint64_t)pkt[9] << (33 - 32) ) |
2547                              ( pkt[10] >> 7 );
2548             ++stream->ts_pcr_in;
2549             stream->ts_found_pcr = 1;
2550             stream->ts_flags |= TS_HAS_PCR;
2551         }
2552     }
2553
2554     // If we don't have a PCR yet but the stream has PCRs just loop
2555     // so we don't process anything until we have a clock reference.
2556     // Unfortunately the HD Home Run appears to null out the PCR so if
2557     // we didn't detect a PCR during scan keep going and we'll use
2558     // the video stream DTS for the PCR.
2559
2560     if ( !stream->ts_found_pcr && ( stream->ts_flags & TS_HAS_PCR ) )
2561     {
2562         return 0;
2563     }
2564
2565     // Get continuity
2566     // Continuity only increments for adaption values of 0x3 or 0x01
2567     // and is not checked for start packets.
2568
2569     int start = (pkt[1] & 0x40) != 0;
2570
2571     if ( (adaption & 0x01) != 0 )
2572     {
2573         int continuity = (pkt[3] & 0xF);
2574         if ( continuity == stream->ts_streamcont[curstream] )
2575         {
2576             // Spliced transport streams can have duplicate 
2577             // continuity counts at the splice boundary.
2578             // Test to see if the packet is really a duplicate
2579             // by comparing packet summaries to see if they
2580             // match.
2581             uint8_t summary[8];
2582
2583             summary[0] = adaption;
2584             summary[1] = adapt_len;
2585             if (adapt_len + 4 + 6 + 9 <= 188)
2586             {
2587                 memcpy(&summary[2], pkt+4+adapt_len+9, 6);
2588             }
2589             else
2590             {
2591                 memset(&summary[2], 0, 6);
2592             }
2593             if ( memcmp( summary, stream->ts_pkt_summary[curstream], 8 ) == 0 )
2594             {
2595                 // we got a duplicate packet (usually used to introduce
2596                 // a PCR when one is needed). The only thing that can
2597                 // change in the dup is the PCR which we grabbed above
2598                 // so ignore the rest.
2599                 return 0;
2600             }
2601         }
2602         if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2603              !stream->ts_skipbad[curstream] &&
2604              (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2605         {
2606             ts_err( stream, curstream,  "continuity error: got %d expected %d",
2607                     (int)continuity,
2608                     (stream->ts_streamcont[curstream] + 1) & 0xf );
2609             stream->ts_streamcont[curstream] = continuity;
2610             return 0;
2611         }
2612         stream->ts_streamcont[curstream] = continuity;
2613
2614         // Save a summary of this packet for later duplicate
2615         // testing.  The summary includes some header information
2616         // and payload bytes.  Should be enough to detect 
2617         // non-duplicates.
2618         stream->ts_pkt_summary[curstream][0] = adaption;
2619         stream->ts_pkt_summary[curstream][1] = adapt_len;
2620         if (adapt_len + 4 + 6 + 9 <= 188)
2621         {
2622             memcpy(&stream->ts_pkt_summary[curstream][2], 
2623                     pkt+4+adapt_len+9, 6);
2624         }
2625         else
2626         {
2627             memset(&stream->ts_pkt_summary[curstream][2], 0, 6);
2628         }
2629     }
2630
2631     /* If we get here the packet is valid - process its data */
2632
2633     if ( start )
2634     {
2635         // Found a random access point (now we can start a frame/audio packet..)
2636
2637         if ( stream->need_keyframe )
2638         {
2639             // we're looking for the first video frame because we're
2640             // doing random access during 'scan'
2641             if ( curstream != video_index || !isIframe( stream, pkt, adapt_len ) )
2642             {
2643                 // not the video stream or didn't find an I frame
2644                 // but we'll only wait 255 video frames for an I frame.
2645                 if ( curstream != video_index || ++stream->need_keyframe )
2646                 {
2647                     return 0;
2648                 }
2649             }
2650             stream->need_keyframe = 0;
2651         }
2652
2653         // If we were skipping a bad packet, start fresh on this new PES packet..
2654         if (stream->ts_skipbad[curstream] == 1)
2655         {
2656             stream->ts_skipbad[curstream] = 0;
2657         }
2658
2659         if ( curstream == video_index )
2660         {
2661             ++stream->frames;
2662
2663             // if we don't have a pcr yet use the dts from this frame
2664             if ( !stream->ts_found_pcr )
2665             {
2666                 // PES must begin with an mpeg start code & contain
2667                 // a DTS or PTS.
2668                 const uint8_t *pes = pkt + adapt_len + 4;
2669                 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2670                      ( pes[7] >> 6 ) == 0 )
2671                 {
2672                     return 0;
2673                 }
2674                 // if we have a dts use it otherwise use the pts
2675                 stream->ts_pcr = pes_timestamp( pes + ( pes[7] & 0x40?14:9 ) );
2676                 ++stream->ts_pcr_in;
2677             }
2678         }
2679
2680         // if this is a multiplexed stream make sure this is the
2681         // substream we want.
2682         if ( stream->ts_multiplexed[curstream] )
2683         {
2684             // PES must begin with an mpeg start code & contain
2685             // a DTS or PTS.
2686             const uint8_t *pes = pkt + adapt_len + 4;
2687             if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2688                  pes[3] != 0xfd )
2689             {
2690                 stream->ts_skipbad[curstream] = 1;
2691                 return 0;
2692             }
2693             // the last byte of the header is the extension id. see if
2694             // it's the one we want.
2695             if ( pes[pes[8]+8] != stream->ts_multiplexed[curstream] )
2696             {
2697                 stream->ts_skipbad[curstream] = 1;
2698                 return 0;
2699             }
2700         }
2701
2702         // If we have some data already on this stream, turn it into
2703         // a program stream packet. Then add the payload for this
2704         // packet to the current pid's buffer.
2705         if ( stream->ts_pos[curstream] )
2706         {
2707             // we have to ship the old packet before updating the pcr
2708             // since the packet we've been accumulating is referenced
2709             // to the old pcr.
2710             generate_output_data(stream, curstream);
2711
2712             // remember the pcr that was in effect when we started
2713             // this packet.
2714             stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2715             hb_ts_stream_append_pkt(stream, curstream, pkt + 4 + adapt_len,
2716                                     184 - adapt_len);
2717             return 1;
2718         }
2719         // remember the pcr that was in effect when we started this packet.
2720         stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2721     }
2722
2723     // Add the payload for this packet to the current buffer
2724     if (!stream->ts_skipbad[curstream] && (184 - adapt_len) > 0)
2725     {
2726         hb_ts_stream_append_pkt(stream, curstream, pkt + 4 + adapt_len,
2727                                 184 - adapt_len);
2728         // see if we've hit the end of this PES packet
2729         const uint8_t *pes = stream->ts_buf[curstream]->data;
2730         int len = ( pes[4] << 8 ) + pes[5] + 6;
2731         if ( len > 6 && stream->ts_pos[curstream] == len &&
2732              pes[0] == 0x00 && pes[1] == 0x00 && pes[2] == 0x01 )
2733         {
2734             generate_output_data(stream, curstream);
2735             return 1;
2736         }
2737     }
2738     return 0;
2739 }
2740
2741 static int hb_ts_stream_decode( hb_stream_t *stream, hb_buffer_t *obuf )
2742 {
2743     // spin until we get a packet of data from some stream or hit eof
2744     while ( 1 )
2745     {
2746         const uint8_t *buf = next_packet(stream);
2747         if ( buf == NULL )
2748         {
2749             // end of file - we didn't finish filling our ps write buffer
2750             // so just discard the remainder (the partial buffer is useless)
2751             hb_log("hb_ts_stream_decode - eof");
2752             return 0;
2753         }
2754
2755         if (hb_ts_decode_pkt( stream, buf, obuf ))
2756         {
2757             return 1;
2758         }
2759     }
2760     return 0;
2761 }
2762
2763 static void hb_ts_stream_reset(hb_stream_t *stream)
2764 {
2765     int i;
2766
2767     for (i=0; i < kMaxNumberDecodeStreams; i++)
2768     {
2769         stream->ts_pos[i] = 0;
2770         stream->ts_skipbad[i] = 1;
2771         stream->ts_streamcont[i] = -1;
2772     }
2773
2774     stream->need_keyframe = 0;
2775
2776     stream->ts_found_pcr = 0;
2777     stream->ts_pcr_out = 0;
2778     stream->ts_pcr_in = 0;
2779     stream->ts_pcr = 0;
2780
2781     stream->frames = 0;
2782     stream->errors = 0;
2783     stream->last_error_frame = -10000;
2784     stream->last_error_count = 0;
2785
2786     align_to_next_packet(stream);
2787 }
2788
2789 // ------------------------------------------------------------------
2790 // Support for reading media files via the ffmpeg libraries.
2791
2792 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2793 {
2794     // add a codec to the context here so it will be there when we
2795     // read the first packet.
2796     AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2797     context->workaround_bugs = FF_BUG_AUTODETECT;
2798     context->error_recognition = 1;
2799     context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2800     AVCodec *codec = avcodec_find_decoder( context->codec_id );
2801     hb_avcodec_open( context, codec );
2802 }
2803
2804 // The ffmpeg stream reader / parser shares a lot of state with the 
2805 // decoder via a codec context kept in the AVStream of the reader's
2806 // AVFormatContext. Since decoding is done in a different thread we
2807 // have to somehow pass this codec context to the decoder and we have
2808 // to do it before the first packet is read (so we can't put the info
2809 // in the buf we'll send downstream). Decoders don't have any way to
2810 // get to the stream directly (they're not passed the title or job
2811 // pointers during a scan) so this is a back door for the decoder to
2812 // get the codec context. We just stick the stream pointer in the next
2813 // slot an array of pointers maintained as a circular list then return
2814 // the index into the list combined with the ffmpeg stream index as the
2815 // codec_param that will be passed to the decoder init routine. We make
2816 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2817 // so that we don't have to do a complicated allocator or worry about
2818 // deleting entries on close. 
2819 //
2820 // Entries can only be added to this list during a scan and are never
2821 // deleted so the list access doesn't require locking.
2822 static hb_stream_t **ffmpeg_streams;    // circular list of stream pointers
2823 static int ffmpeg_stream_cur;           // where we put the last stream pointer
2824 #define ffmpeg_sl_bits (10)             // log2 stream list size (in entries)
2825 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2826
2827 // add a stream to the list & return the appropriate codec_param to access it
2828 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2829 {
2830     if ( !ffmpeg_streams )
2831     {
2832         ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2833     }
2834
2835     // the title scan adds all the ffmpeg media streams at once so we
2836     // only add a new entry to our stream list if the stream is different
2837     // than last time.
2838     int slot = ffmpeg_stream_cur;
2839     if ( ffmpeg_streams[slot] != stream )
2840     {
2841         // new stream - put it in the next slot of the stream list
2842         slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2843         ffmpeg_streams[slot] = stream;
2844     }
2845
2846     ffmpeg_add_codec( stream, stream_index );
2847
2848     return ( stream_index << ffmpeg_sl_bits ) | slot;
2849 }
2850
2851 // we're about to open 'title' to convert it - remap the stream associated
2852 // with the video & audio codec params of the title to refer to 'stream'
2853 // (the original scan stream was closed and no longer exists).
2854 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2855 {
2856     // all the video & audio came from the same stream so remapping
2857     // the video's stream slot takes care of everything.
2858     int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2859     ffmpeg_streams[slot] = stream;
2860
2861     // add codecs for all the streams used by the title
2862     ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2863
2864     int i;
2865     hb_audio_t *audio;
2866     for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2867     {
2868         if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2869         {
2870             ffmpeg_add_codec( stream,
2871                               audio->config.in.codec_param >> ffmpeg_sl_bits );
2872         }
2873     }
2874 }
2875
2876 void *hb_ffmpeg_context( int codec_param )
2877 {
2878     if ( ffmpeg_streams == NULL )
2879         return NULL;
2880
2881     int slot = codec_param & (ffmpeg_sl_size - 1);
2882     int stream_index = codec_param >> ffmpeg_sl_bits;
2883     return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2884 }
2885
2886 void *hb_ffmpeg_avstream( int codec_param )
2887 {
2888     if ( ffmpeg_streams == NULL )
2889         return NULL;
2890
2891     int slot = codec_param & (ffmpeg_sl_size - 1);
2892     int stream_index = codec_param >> ffmpeg_sl_bits;
2893     return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2894 }
2895
2896 static AVFormatContext *ffmpeg_deferred_close;
2897
2898 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2899 {
2900     if ( ffmpeg_deferred_close )
2901     {
2902         av_close_input_file( ffmpeg_deferred_close );
2903         ffmpeg_deferred_close = NULL;
2904     }
2905     AVFormatContext *ic;
2906
2907     av_log_set_level( AV_LOG_ERROR );
2908     if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2909     {
2910         return 0;
2911     }
2912     if ( av_find_stream_info( ic ) < 0 )
2913         goto fail;
2914
2915     stream->ffmpeg_ic = ic;
2916     stream->hb_stream_type = ffmpeg;
2917     stream->ffmpeg_pkt = malloc(sizeof(*stream->ffmpeg_pkt));
2918     av_init_packet( stream->ffmpeg_pkt );
2919     stream->chapter_end = INT64_MAX;
2920
2921     if ( title )
2922     {
2923         // we're opening for read. scan passed out codec params that
2924         // indexed its stream so we need to remap them so they point
2925         // to this stream.
2926         ffmpeg_remap_stream( stream, title );
2927         av_log_set_level( AV_LOG_ERROR );
2928     }
2929     else
2930     {
2931         // we're opening for scan. let ffmpeg put some info into the
2932         // log about what we've got.
2933         av_log_set_level( AV_LOG_INFO );
2934         dump_format( ic, 0, stream->path, 0 );
2935         av_log_set_level( AV_LOG_ERROR );
2936
2937         // accept this file if it has at least one video stream we can decode
2938         int i;
2939         for (i = 0; i < ic->nb_streams; ++i )
2940         {
2941             if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2942             {
2943                 break;
2944             }
2945         }
2946         if ( i >= ic->nb_streams )
2947             goto fail;
2948     }
2949     return 1;
2950
2951   fail:
2952     av_close_input_file( ic );
2953     return 0;
2954 }
2955
2956 static void ffmpeg_close( hb_stream_t *d )
2957 {
2958     // XXX since we're sharing the CodecContext with the downstream
2959     // decoder proc we can't close the stream. We need to reference count
2960     // this so we can close it when both are done with their instance but
2961     // for now just defer the close until the next stream open or close.
2962     if ( ffmpeg_deferred_close )
2963     {
2964         av_close_input_file( ffmpeg_deferred_close );
2965     }
2966     ffmpeg_deferred_close = d->ffmpeg_ic;
2967     if ( d->ffmpeg_pkt != NULL )
2968     {
2969         free( d->ffmpeg_pkt );
2970         d->ffmpeg_pkt = NULL;
2971     }
2972 }
2973
2974 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2975 {
2976     AVStream *st = stream->ffmpeg_ic->streams[id];
2977     AVCodecContext *codec = st->codec;
2978     int layout;
2979
2980     // scan will ignore any audio without a bitrate. Since we've already
2981     // typed the audio in order to determine its codec we set up the audio
2982     // paramters here.
2983     layout = hb_ff_layout_xlat( codec->channel_layout, codec->channels );
2984     if ( !layout )
2985     {
2986         // Unsupported layout
2987         return;
2988     }
2989     if ( codec->bit_rate || codec->sample_rate )
2990     {
2991         hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
2992
2993         audio->id = id;
2994         if ( codec->codec_id == CODEC_ID_AC3 )
2995         {
2996             audio->config.in.codec = HB_ACODEC_AC3;
2997         }
2998         else if ( codec->codec_id == CODEC_ID_DTS )
2999         {
3000             audio->config.in.codec = HB_ACODEC_DCA;
3001         }
3002         else
3003         {
3004             audio->config.in.codec = HB_ACODEC_FFMPEG;
3005             audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
3006
3007             audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
3008             audio->config.in.samplerate = codec->sample_rate;
3009             audio->config.in.channel_layout = layout;
3010         }
3011
3012         set_audio_description( audio, lang_for_code2( st->language ) );
3013
3014         hb_list_add( title->list_audio, audio );
3015     }
3016 }
3017
3018 /*
3019  * Format:
3020  *   MkvVobSubtitlePrivateData = ( Line )*
3021  *   Line = FieldName ':' ' ' FieldValue '\n'
3022  *   FieldName = [^:]+
3023  *   FieldValue = [^\n]+
3024  * 
3025  * The line of interest is:
3026  *   PaletteLine = "palette" ':' ' ' RRGGBB ( ',' ' ' RRGGBB )*
3027  * 
3028  * More information on the format at:
3029  *   http://www.matroska.org/technical/specs/subtitles/images.html
3030  */
3031 static int ffmpeg_parse_vobsub_extradata_mkv( AVCodecContext *codec, hb_subtitle_t *subtitle )
3032 {
3033     // lines = (string) codec->extradata;
3034     char *lines = malloc( codec->extradata_size + 1 );
3035     if ( lines == NULL )
3036         return 1;
3037     memcpy( lines, codec->extradata, codec->extradata_size );
3038     lines[codec->extradata_size] = '\0';
3039     
3040     uint32_t rgb[16];
3041     int gotPalette = 0;
3042     int gotDimensions = 0;
3043     
3044     char *curLine, *curLine_parserData;
3045     for ( curLine = strtok_r( lines, "\n", &curLine_parserData );
3046           curLine;
3047           curLine = strtok_r( NULL, "\n", &curLine_parserData ) )
3048     {
3049         if (!gotPalette)
3050         {
3051             int numElementsRead = sscanf(curLine, "palette: "
3052                 "%06x, %06x, %06x, %06x, "
3053                 "%06x, %06x, %06x, %06x, "
3054                 "%06x, %06x, %06x, %06x, "
3055                 "%06x, %06x, %06x, %06x",
3056                 &rgb[0],  &rgb[1],  &rgb[2],  &rgb[3],
3057                 &rgb[4],  &rgb[5],  &rgb[6],  &rgb[7],
3058                 &rgb[8],  &rgb[9],  &rgb[10], &rgb[11],
3059                 &rgb[12], &rgb[13], &rgb[14], &rgb[15]);
3060
3061             if (numElementsRead == 16) {
3062                 gotPalette = 1;
3063             }
3064         }
3065         if (!gotDimensions)
3066         {
3067             int numElementsRead = sscanf(curLine, "size: %dx%d",
3068                 &subtitle->width, &subtitle->height);
3069
3070             if (numElementsRead == 2) {
3071                 gotDimensions = 1;
3072             }
3073         }
3074         if (gotPalette && gotDimensions)
3075             break;
3076     }
3077
3078     if (subtitle->width == 0 || subtitle->height == 0)
3079     {
3080         subtitle->width = 720;
3081         subtitle->height = 480;
3082     }
3083     
3084     free( lines );
3085     
3086     if ( gotPalette )
3087     {
3088         int i;
3089         for (i=0; i<16; i++)
3090             subtitle->palette[i] = hb_rgb2yuv(rgb[i]);
3091         return 0;
3092     }
3093     else
3094     {
3095         return 1;
3096     }
3097 }
3098
3099 /*
3100  * Format: 8-bit {0,Y,Cb,Cr} x 16
3101  */
3102 static int ffmpeg_parse_vobsub_extradata_mp4( AVCodecContext *codec, hb_subtitle_t *subtitle )
3103 {
3104     if ( codec->extradata_size != 4*16 )
3105         return 1;
3106     
3107     int i, j;
3108     for ( i=0, j=0; i<16; i++, j+=4 )
3109     {
3110         subtitle->palette[i] = 
3111             codec->extradata[j+1] << 16 |   // Y
3112             codec->extradata[j+2] << 8  |   // Cb
3113             codec->extradata[j+3] << 0;     // Cr
3114     }
3115     if (codec->width <= 0 || codec->height <= 0)
3116     {
3117         subtitle->width = 720;
3118         subtitle->height = 480;
3119     }
3120     else
3121     {
3122         subtitle->width = codec->width;
3123         subtitle->height = codec->height;
3124     }
3125     return 0;
3126 }
3127
3128 /*
3129  * Parses the 'subtitle->palette' information from the specific VOB subtitle track's private data.
3130  * Returns 0 if successful or 1 if parsing failed or was incomplete.
3131  */
3132 static int ffmpeg_parse_vobsub_extradata( AVCodecContext *codec, hb_subtitle_t *subtitle )
3133 {
3134     // XXX: Better if we actually chose the correct parser based on the input container
3135     return
3136         ffmpeg_parse_vobsub_extradata_mkv( codec, subtitle ) &&
3137         ffmpeg_parse_vobsub_extradata_mp4( codec, subtitle );
3138 }
3139
3140 static void add_ffmpeg_subtitle( hb_title_t *title, hb_stream_t *stream, int id )
3141 {
3142     AVStream *st = stream->ffmpeg_ic->streams[id];
3143     AVCodecContext *codec = st->codec;
3144     
3145     hb_subtitle_t *subtitle = calloc( 1, sizeof(*subtitle) );
3146     
3147     subtitle->id = id;
3148     
3149     switch ( codec->codec_id )
3150     {
3151         case CODEC_ID_DVD_SUBTITLE:
3152             subtitle->format = PICTURESUB;
3153             subtitle->source = VOBSUB;
3154             subtitle->config.dest = RENDERSUB;  // By default render (burn-in) the VOBSUB.
3155             if ( ffmpeg_parse_vobsub_extradata( codec, subtitle ) )
3156                 hb_log( "add_ffmpeg_subtitle: malformed extradata for VOB subtitle track; "
3157                         "subtitle colors likely to be wrong" );
3158             break;
3159         case CODEC_ID_TEXT:
3160             subtitle->format = TEXTSUB;
3161             subtitle->source = UTF8SUB;
3162             subtitle->config.dest = PASSTHRUSUB;
3163             break;
3164         case CODEC_ID_MOV_TEXT: // TX3G
3165             subtitle->format = TEXTSUB;
3166             subtitle->source = TX3GSUB;
3167             subtitle->config.dest = PASSTHRUSUB;
3168             break;
3169         case CODEC_ID_SSA:
3170             subtitle->format = TEXTSUB;
3171             subtitle->source = SSASUB;
3172             subtitle->config.dest = PASSTHRUSUB;
3173             break;
3174         default:
3175             hb_log( "add_ffmpeg_subtitle: unknown subtitle stream type: 0x%x", (int) codec->codec_id );
3176             free(subtitle);
3177             return;
3178     }
3179     
3180     iso639_lang_t *language = lang_for_code2( st->language );
3181     strcpy( subtitle->lang, language->eng_name );
3182     strncpy( subtitle->iso639_2, language->iso639_2, 4 );
3183     
3184     hb_list_add(title->list_subtitle, subtitle);
3185 }
3186
3187 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
3188 {
3189     AVFormatContext *ic = stream->ffmpeg_ic;
3190
3191     // 'Barebones Title'
3192     hb_title_t *title = hb_title_init( stream->path, 0 );
3193     title->type = HB_STREAM_TYPE;
3194     title->index = 1;
3195
3196     // Copy part of the stream path to the title name
3197     char *sep = strrchr(stream->path, '/');
3198     if (sep)
3199         strcpy(title->name, sep+1);
3200     char *dot_term = strrchr(title->name, '.');
3201     if (dot_term)
3202         *dot_term = '\0';
3203
3204     uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
3205     title->duration = dur;
3206     dur /= 90000;
3207     title->hours    = dur / 3600;
3208     title->minutes  = ( dur % 3600 ) / 60;
3209     title->seconds  = dur % 60;
3210
3211     // set the title to decode the first video stream in the file
3212     title->demuxer = HB_NULL_DEMUXER;
3213     title->video_codec = 0;
3214     int i;
3215     for (i = 0; i < ic->nb_streams; ++i )
3216     {
3217         if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
3218              avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
3219              title->video_codec == 0 )
3220         {
3221             AVCodecContext *context = ic->streams[i]->codec;
3222             if ( context->pix_fmt != PIX_FMT_YUV420P &&
3223                  !sws_isSupportedInput( context->pix_fmt ) )
3224             {
3225                 hb_log( "ffmpeg_title_scan: Unsupported color space" );
3226                 continue;
3227             }
3228             title->video_id = i;
3229             stream->ffmpeg_video_id = i;
3230
3231             // We have to use the 'internal' avcodec decoder because
3232             // it needs to share the codec context from this video
3233             // stream. The parser internal to av_read_frame
3234             // passes a bunch of state info to the decoder via the context.
3235             title->video_codec = WORK_DECAVCODECVI;
3236             title->video_codec_param = ffmpeg_codec_param( stream, i );
3237         }
3238         else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
3239                   avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
3240         {
3241             add_ffmpeg_audio( title, stream, i );
3242         }
3243         else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_SUBTITLE )
3244         {
3245             add_ffmpeg_subtitle( title, stream, i );
3246         }
3247     }
3248
3249     title->container_name = strdup( ic->iformat->name );
3250     title->data_rate = ic->bit_rate;
3251
3252     hb_deep_log( 2, "Found ffmpeg %d chapters, container=%s", ic->nb_chapters, ic->iformat->name );
3253
3254     if( ic->nb_chapters != 0 )
3255     {
3256         AVChapter *m;
3257         uint64_t duration_sum = 0;
3258         for( i = 0; i < ic->nb_chapters; i++ )
3259             if( ( m = ic->chapters[i] ) != NULL )
3260             {
3261                 hb_chapter_t * chapter;
3262                 chapter = calloc( sizeof( hb_chapter_t ), 1 );
3263                 chapter->index    = i+1;
3264                 chapter->duration = ( m->end / ( (double) m->time_base.num * m->time_base.den ) ) * 90000  - duration_sum;
3265                 duration_sum     += chapter->duration;
3266                 chapter->hours    = chapter->duration / 90000 / 3600;
3267                 chapter->minutes  = ( ( chapter->duration / 90000 ) % 3600 ) / 60;
3268                 chapter->seconds  = ( chapter->duration / 90000 ) % 60;
3269                 strcpy( chapter->title, m->title );
3270                 hb_deep_log( 2, "Added chapter %i, name='%s', dur=%"PRIu64", (%02i:%02i:%02i)",
3271                             chapter->index, chapter->title,
3272                             chapter->duration, chapter->hours,
3273                             chapter->minutes, chapter->seconds );
3274                 hb_list_add( title->list_chapter, chapter );
3275             }
3276     }
3277
3278     /*
3279      * Fill the metadata.
3280      */
3281     decmetadata( title );
3282
3283     if( hb_list_count( title->list_chapter ) == 0 )
3284     {
3285         // Need at least one chapter
3286         hb_chapter_t * chapter;
3287         chapter = calloc( sizeof( hb_chapter_t ), 1 );
3288         chapter->index = 1;
3289         chapter->duration = title->duration;
3290         chapter->hours = title->hours;
3291         chapter->minutes = title->minutes;
3292         chapter->seconds = title->seconds;
3293         hb_list_add( title->list_chapter, chapter );
3294     }
3295
3296     return title;
3297 }
3298
3299 static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
3300 {
3301     if ( pts == AV_NOPTS_VALUE )
3302         return -1;
3303     return (int64_t)( (double)pts * conv_factor );
3304 }
3305
3306 static int ffmpeg_is_keyframe( hb_stream_t *stream )
3307 {
3308     uint8_t *pkt;
3309
3310     switch ( stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->codec_id )
3311     {
3312         case CODEC_ID_VC1:
3313             // XXX the VC1 codec doesn't mark key frames so to get previews
3314             // we do it ourselves here. The decoder gets messed up if it
3315             // doesn't get a SEQ header first so we consider that to be a key frame.
3316             pkt = stream->ffmpeg_pkt->data;
3317             if ( !pkt[0] && !pkt[1] && pkt[2] == 1 && pkt[3] == 0x0f )
3318                 return 1;
3319
3320             return 0;
3321
3322         case CODEC_ID_WMV3:
3323             // XXX the ffmpeg WMV3 codec doesn't mark key frames.
3324             // Only M$ could make I-frame detection this complicated: there
3325             // are two to four bits of unused junk ahead of the frame type
3326             // so we have to look at the sequence header to find out how much
3327             // to skip. Then there are three different ways of coding the type
3328             // depending on whether it's main or advanced profile then whether
3329             // there are bframes or not so we have to look at the sequence
3330             // header to get that.
3331             pkt = stream->ffmpeg_pkt->data;
3332             uint8_t *seqhdr = stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->extradata;
3333             int pshift = 2;
3334             if ( ( seqhdr[3] & 0x02 ) == 0 )
3335                 // no FINTERPFLAG
3336                 ++pshift;
3337             if ( ( seqhdr[3] & 0x80 ) == 0 )
3338                 // no RANGEREDUCTION
3339                 ++pshift;
3340             if ( seqhdr[3] & 0x70 )
3341                 // stream has b-frames
3342                 return ( ( pkt[0] >> pshift ) & 0x3 ) == 0x01;
3343
3344             return ( ( pkt[0] >> pshift ) & 0x2 ) == 0;
3345
3346         default:
3347             break;
3348     }
3349     return ( stream->ffmpeg_pkt->flags & PKT_FLAG_KEY );
3350 }
3351
3352 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
3353 {
3354     int err;
3355   again:
3356     if ( ( err = av_read_frame( stream->ffmpeg_ic, stream->ffmpeg_pkt )) < 0 )
3357     {
3358         // XXX the following conditional is to handle avi files that
3359         // use M$ 'packed b-frames' and occasionally have negative
3360         // sizes for the null frames these require.
3361         if ( err != AVERROR_NOMEM || stream->ffmpeg_pkt->size >= 0 )
3362             // eof
3363             return 0;
3364     }
3365     if ( stream->ffmpeg_pkt->size <= 0 )
3366     {
3367         // M$ "invalid and inefficient" packed b-frames require 'null frames'
3368         // following them to preserve the timing (since the packing puts two
3369         // or more frames in what looks like one avi frame). The contents and
3370         // size of these null frames are ignored by the ff_h263_decode_frame
3371         // as long as they're < 20 bytes. We need a positive size so we use
3372         // one byte if we're given a zero or negative size. We don't know
3373         // if the pkt data points anywhere reasonable so we just stick a
3374         // byte of zero in our outbound buf.
3375         buf->size = 1;
3376         *buf->data = 0;
3377     }
3378     else
3379     {
3380         if ( stream->ffmpeg_pkt->size > buf->alloc )
3381         {
3382             // sometimes we get absurd sizes from ffmpeg
3383             if ( stream->ffmpeg_pkt->size >= (1 << 25) )
3384             {
3385                 hb_log( "ffmpeg_read: pkt too big: %d bytes", stream->ffmpeg_pkt->size );
3386                 av_free_packet( stream->ffmpeg_pkt );
3387                 return ffmpeg_read( stream, buf );
3388             }
3389             // need to expand buffer
3390             hb_buffer_realloc( buf, stream->ffmpeg_pkt->size );
3391         }
3392         memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
3393         buf->size = stream->ffmpeg_pkt->size;
3394     }
3395     buf->id = stream->ffmpeg_pkt->stream_index;
3396     if ( buf->id == stream->ffmpeg_video_id )
3397     {
3398         if ( stream->need_keyframe )
3399         {
3400             // we've just done a seek (generally for scan or live preview) and
3401             // want to start at a keyframe. Some ffmpeg codecs seek to a key
3402             // frame but most don't. So we spin until we either get a keyframe
3403             // or we've looked through 50 video frames without finding one.
3404             if ( ! ffmpeg_is_keyframe( stream ) && ++stream->need_keyframe < 50 )
3405             {
3406                 av_free_packet( stream->ffmpeg_pkt );
3407                 goto again;
3408             }
3409             stream->need_keyframe = 0;
3410         }
3411         ++stream->frames;
3412     }
3413
3414     // if we haven't done it already, compute a conversion factor to go
3415     // from the ffmpeg timebase for the stream to HB's 90KHz timebase.
3416     double tsconv = stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index];
3417     if ( ! tsconv )
3418     {
3419         AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index];
3420         tsconv = 90000. * (double)s->time_base.num / (double)s->time_base.den;
3421         stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index] = tsconv;
3422     }
3423
3424     buf->start = av_to_hb_pts( stream->ffmpeg_pkt->pts, tsconv );
3425     buf->renderOffset = av_to_hb_pts( stream->ffmpeg_pkt->dts, tsconv );
3426     if ( buf->renderOffset >= 0 && buf->start == -1 )
3427     {
3428         buf->start = buf->renderOffset;
3429     }
3430     else if ( buf->renderOffset == -1 && buf->start >= 0 )
3431     {
3432         buf->renderOffset = buf->start;
3433     }
3434     
3435     /* 
3436      * Fill out buf->stop for subtitle packets
3437      * 
3438      * libavcodec's MKV demuxer stores the duration of UTF-8 subtitles (CODEC_ID_TEXT)
3439      * in the 'convergence_duration' field for some reason.
3440      * 
3441      * Other subtitles' durations are stored in the 'duration' field.
3442      * 
3443      * VOB subtitles (CODEC_ID_DVD_SUBTITLE) do not have their duration stored in
3444      * either field. This is not a problem because the VOB decoder can extract this
3445      * information from the packet payload itself.
3446      * 
3447      * SSA subtitles (CODEC_ID_SSA) do not have their duration stored in
3448      * either field. This is not a problem because the SSA decoder can extract this
3449      * information from the packet payload itself.
3450      */
3451     enum CodecID ffmpeg_pkt_codec = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index]->codec->codec_id;
3452     if ( ffmpeg_pkt_codec == CODEC_ID_TEXT ) {
3453         int64_t ffmpeg_pkt_duration = stream->ffmpeg_pkt->convergence_duration;
3454         int64_t buf_duration = av_to_hb_pts( ffmpeg_pkt_duration, tsconv );
3455         buf->stop = buf->start + buf_duration;
3456     }
3457     if ( ffmpeg_pkt_codec == CODEC_ID_MOV_TEXT ) {
3458         int64_t ffmpeg_pkt_duration = stream->ffmpeg_pkt->duration;
3459         int64_t buf_duration = av_to_hb_pts( ffmpeg_pkt_duration, tsconv );
3460         buf->stop = buf->start + buf_duration;
3461     }
3462
3463     /*
3464      * Check to see whether this video buffer is on a chapter
3465      * boundary, if so mark it as such in the buffer then advance
3466      * chapter_end to the end of the next chapter.
3467      * If there are no chapters, chapter_end is always initialized to INT64_MAX
3468      * (roughly 3 million years at our 90KHz clock rate) so the test
3469      * below handles both the chapters & no chapters case.
3470      */
3471     if ( buf->id == stream->ffmpeg_video_id && buf->start >= stream->chapter_end )
3472     {
3473         hb_chapter_t *chapter = hb_list_item( stream->title->list_chapter,
3474                                               stream->chapter+1 );
3475         if( chapter )
3476         {
3477             stream->chapter++;
3478             stream->chapter_end += chapter->duration;
3479             buf->new_chap = stream->chapter + 1;
3480             hb_deep_log( 2, "ffmpeg_read starting chapter %i at %"PRId64,
3481                          buf->new_chap, buf->start);
3482         } else {
3483             // Must have run out of chapters, stop looking.
3484             stream->chapter_end = INT64_MAX;
3485         }
3486     } else {
3487         buf->new_chap = 0;
3488     }
3489     av_free_packet( stream->ffmpeg_pkt );
3490     return 1;
3491 }
3492
3493 static int ffmpeg_seek( hb_stream_t *stream, float frac )
3494 {
3495     AVFormatContext *ic = stream->ffmpeg_ic;
3496     if ( frac > 0. )
3497     {
3498         int64_t pos = (double)ic->duration * (double)frac;
3499         if ( ic->start_time != AV_NOPTS_VALUE && ic->start_time > 0 )
3500         {
3501             pos += ic->start_time;
3502         }
3503         av_seek_frame( ic, -1, pos, 0 );
3504         stream->need_keyframe = 1;
3505     }
3506     else
3507     {
3508         av_seek_frame( ic, -1, 0LL, AVSEEK_FLAG_BACKWARD );
3509     }
3510     return 1;
3511 }
3512
3513 // Assumes that we are always seeking forward
3514 static int ffmpeg_seek_ts( hb_stream_t *stream, int64_t ts )
3515 {
3516     AVFormatContext *ic = stream->ffmpeg_ic;
3517     int64_t pos;
3518
3519     pos = ts * AV_TIME_BASE / 90000 + ffmpeg_initial_timestamp( stream );
3520     stream->need_keyframe = 1;
3521     // Seek to the nearest timestamp before that requested where
3522     // there is an I-frame
3523     return av_seek_frame( ic, -1, pos, AVSEEK_FLAG_BACKWARD );
3524 }