OSDN Git Service

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