OSDN Git Service

bump ffmpeg from r25374 to r25689
[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 );
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 const char* make_upper( const char* s )
1544 {
1545     static char name[8];
1546     char *cp = name;
1547     char *ep = cp + sizeof(name)-1;
1548
1549     while ( *s && cp < ep )
1550     {
1551         *cp++ = islower(*s)? toupper(*s) : *s;
1552         ++s;
1553     }
1554     *cp = 0;
1555     return name;
1556 }
1557
1558 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1559 {
1560     /* XXX
1561      * This is a duplicate of code in dvd.c - it should get factored out
1562      * into a common routine. We probably should only be putting the lang
1563      * code or a lang pointer into the audio config & let the common description
1564      * formatting routine in scan.c do all the stuff below.
1565      */
1566     const char *codec_name;
1567     AVCodecContext *cc;
1568
1569     if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1570          ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1571          avcodec_find_decoder( cc->codec_id ) )
1572     {
1573         codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1574         if ( !strcmp( codec_name, "LIBFAAD" ) )
1575         {
1576             codec_name = "AAC";
1577         }
1578     }
1579     else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1580               avcodec_find_decoder( audio->config.in.codec_param ) )
1581     {
1582         codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1583     }
1584     else
1585     {
1586         codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1587                      audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1588                      audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" : 
1589                      audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" : 
1590                      audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1591                      "Unknown";
1592     }
1593     snprintf( audio->config.lang.description,
1594               sizeof( audio->config.lang.description ), "%s (%s)",
1595               strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1596               codec_name );
1597
1598     if (audio->config.in.codec == HB_ACODEC_FFMPEG)
1599     {
1600         int layout = audio->config.in.channel_layout;
1601         char *desc = audio->config.lang.description +
1602                         strlen( audio->config.lang.description );
1603         sprintf( desc, " (%d.%d ch)",
1604                  HB_INPUT_CH_LAYOUT_GET_DISCRETE_FRONT_COUNT(layout) +
1605                      HB_INPUT_CH_LAYOUT_GET_DISCRETE_REAR_COUNT(layout),
1606                  HB_INPUT_CH_LAYOUT_GET_DISCRETE_LFE_COUNT(layout) );
1607     }
1608
1609     snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1610               strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1611     snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1612               "%s", lang->iso639_2);
1613 }
1614
1615 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1616                                                        int idx)
1617 {
1618     off_t cur_pos = ftello(stream->file_handle);
1619     hb_audio_t *audio = NULL;
1620     const uint8_t *buf;
1621     kind_t kind;
1622     uint8_t stype = 0;
1623
1624     kind = stream->ts_stream_kind[idx];
1625
1626     if ( kind != A && kind != U && kind != N )
1627     {
1628         // Not audio
1629         return NULL;
1630     }
1631     stype = stream->ts_stream_type[idx];
1632
1633     fseeko(stream->file_handle, 0, SEEK_SET);
1634     align_to_next_packet(stream);
1635
1636     buf = hb_ts_stream_getPEStype(stream, stream->ts_pids[idx]);
1637
1638     /* check that we found a PES header */
1639     if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1640     {
1641         // 0xbd ("private stream 1") is the normal container for non-ISO
1642         // media - AC3/DCA/PCM/etc.
1643         if ( buf[3] == 0xbd )
1644         {
1645             if ( kind == U )
1646             {
1647                 // XXX assume unknown stream types are AC-3 (if they're not
1648                 // audio we'll find that out during the scan but if they're
1649                 // some other type of audio we'll end up ignoring them).
1650                 stype = 0x81;
1651                 stream->ts_stream_type[idx] = 0x81;
1652                 kind = A;
1653             }
1654             if ( stype == 0x80 && 
1655                  stream->pmt_info.reg_desc == STR4_TO_UINT32("HDMV") )
1656             {
1657                 // LPCM audio in bluray have an stype of 0x80
1658                 // 0x80 is used for other DigiCipher normally
1659                 // To distinguish, Bluray streams have a reg_desc of HDMV
1660                 kind = A;
1661             }
1662         }
1663         else if ( buf[3] == 0xfd )
1664         {
1665             // 0xfd indicates an extended stream id (ISO 13818-1(2007)).
1666             // the blu ray consortium apparently forgot to read the portion
1667             // of the MPEG spec that says one PID should map to one media
1668             // stream and multiplexed multiple types of audio into one PID
1669             // using the extended stream identifier of the PES header to
1670             // distinguish them. So we have to check if that's happening and
1671             // if so tell the runtime what esid we want.
1672             if ( st2codec[stype].kind == A && stype == 0x83 &&
1673                  stream->ts_format_id[idx] == TS_FORMAT_ID_AC3 )
1674             {
1675                 // This is an interleaved TrueHD/AC-3 stream and the esid of
1676                 // the AC-3 is 0x76
1677                 stream->ts_multiplexed[idx] = 0x76;
1678                 stype = 0x81;
1679                 stream->ts_stream_type[idx] = 0x81;
1680                 kind = A;
1681             }
1682             if ( st2codec[stype].kind == A && stype == 0x86 )
1683             {
1684                 // This is an interleaved DTS-HD/DTS stream and the esid of
1685                 // the DTS is 0x71
1686                 stream->ts_multiplexed[idx] = 0x71;
1687                 stype = 0x82;
1688                 stream->ts_stream_type[idx] = 0x82;
1689                 kind = A;
1690             }
1691             if ( stype == 0x84 && 
1692                  stream->pmt_info.reg_desc == STR4_TO_UINT32("HDMV") )
1693             {
1694                 // EAC3 audio in bluray has an stype of 0x84
1695                 // which conflicts with SDDS
1696                 // To distinguish, Bluray streams have a reg_desc of HDMV
1697                 stype = 0x87;
1698                 stream->ts_stream_type[idx] = 0x87;
1699                 kind = A;
1700             }
1701         }
1702         else if ((buf[3] & 0xe0) == 0xc0)
1703         {
1704             // 0xC0 - 0xCF are the normal containers for ISO-standard
1705             // media (mpeg2 audio and mpeg4 AAC).
1706             if ( st2codec[stype].kind == U )
1707             {
1708                 // XXX assume unknown stream types are MPEG audio
1709                 stype = 0x03;
1710                 stream->ts_stream_type[idx] = 0x03;
1711                 kind = A;
1712             }
1713         }
1714         else
1715         {
1716             stype = 0;
1717             kind = N;
1718         }
1719     }
1720
1721     // if we found an audio stream type & HB has a codec that can decode it
1722     // finish configuring the audio so we'll add it to the title's list.
1723     if ( kind == A && st2codec[stype].codec )
1724     {
1725         audio = calloc( sizeof( hb_audio_t ), 1 );
1726
1727         stream->ts_stream_kind[idx] = A;
1728         audio->id = stream->ts_pids[idx];
1729         audio->config.in.codec = st2codec[stype].codec;
1730         audio->config.in.codec_param = st2codec[stype].codec_param;
1731         set_audio_description( audio,
1732                   lang_for_code( stream->a52_info[idx].lang_code ) );
1733         hb_log("transport stream pid 0x%x (type 0x%x) may be %s audio (id 0x%x)",
1734                stream->ts_pids[idx],
1735                stype, st2codec[stype].name, audio->id);
1736
1737     }
1738     else
1739     {
1740         if ( buf )
1741         {
1742             hb_log("transport stream pid 0x%x (type 0x%x, substream 0x%x) "
1743                     "isn't audio", stream->ts_pids[idx],
1744                     stream->ts_stream_type[idx], buf[3]);
1745         }
1746         else
1747         {
1748             hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1749                     stream->ts_pids[idx],
1750                     stream->ts_stream_type[idx]);
1751         }
1752     }
1753     fseeko(stream->file_handle, cur_pos, SEEK_SET);
1754
1755     return audio;
1756 }
1757
1758 static void add_audio_to_title(hb_title_t *title, int id)
1759 {
1760     hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1761
1762     audio->id = id;
1763     switch ( id >> 12 )
1764     {
1765         case 0x0:
1766             audio->config.in.codec = HB_ACODEC_MPGA;
1767             hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1768             break;
1769         case 0x2:
1770             // type 2 is a DVD subtitle stream - just ignore it */
1771             free( audio );
1772             return;
1773         case 0x8:
1774             audio->config.in.codec = HB_ACODEC_AC3;
1775             hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1776             break;
1777         case 0xa:
1778             audio->config.in.codec = HB_ACODEC_LPCM;
1779             hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1780             break;
1781         default:
1782             hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1783             free( audio );
1784             return;
1785
1786     }
1787     set_audio_description( audio, lang_for_code( 0 ) );
1788     hb_list_add( title->list_audio, audio );
1789 }
1790
1791 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1792 {
1793     off_t cur_pos = ftello(stream->file_handle);
1794     hb_buffer_t *buf  = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1795     hb_list_t *list = hb_list_init();
1796     // how many blocks we read while searching for audio streams
1797     int blksleft = 4096;
1798     // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1799     // so we use a bitmap to keep track of the ones we've already seen.
1800     // Bit 'i' of smap is set if we've already added the audio for
1801     // audio substream id 'i' to the title's audio list.
1802     uint32_t smap = 0;
1803
1804     // start looking 20% into the file since there's occasionally no
1805     // audio at the beginning (particularly for vobs).
1806     hb_stream_seek(stream, 0.2f);
1807
1808     while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1809     {
1810         hb_buffer_t *es;
1811
1812         // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1813         hb_demux_ps( buf, list, 0 );
1814
1815         while ( ( es = hb_list_item( list, 0 ) ) )
1816         {
1817             hb_list_rem( list, es );
1818             if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1819             {
1820                 // this PES contains some kind of audio - get the substream id
1821                 // and check if we've seen it already.
1822                 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1823                 if ( (smap & (1 << ssid)) == 0 )
1824                 {
1825                     // we haven't seen this stream before - add it to the
1826                     // title's list of audio streams.
1827                     smap |= (1 << ssid);
1828                     add_audio_to_title(title, es->id);
1829                 }
1830             }
1831             hb_buffer_close( &es );
1832         }
1833     }
1834     hb_list_empty( &list );
1835     hb_buffer_close(&buf);
1836     fseeko(stream->file_handle, cur_pos, SEEK_SET);
1837 }
1838
1839 /***********************************************************************
1840  * hb_ts_stream_init
1841  ***********************************************************************
1842  *
1843  **********************************************************************/
1844
1845 static void hb_ts_stream_init(hb_stream_t *stream)
1846 {
1847     int i;
1848
1849     for (i=0; i < kMaxNumberDecodeStreams; i++)
1850     {
1851         stream->ts_streamcont[i] = -1;
1852         stream-> ts_pids[i] = -1;
1853     }
1854     stream->ts_packet = malloc( stream->packetsize );
1855
1856     // Find the audio and video pids in the stream
1857     hb_ts_stream_find_pids(stream);
1858
1859     for (i = 0; i < stream->ts_number_pids; i++)
1860     {
1861         // demuxing buffer for TS to PS conversion
1862         stream->ts_buf[i] = hb_buffer_init(stream->packetsize);
1863         stream->ts_buf[i]->size = 0;
1864     }
1865 }
1866
1867 #define MAX_HOLE 208*80
1868
1869 static off_t align_to_next_packet(hb_stream_t *stream)
1870 {
1871     uint8_t buf[MAX_HOLE];
1872     off_t pos = 0;
1873     off_t start = ftello(stream->file_handle);
1874     off_t orig;
1875
1876     if ( start >= stream->packetsize ) {
1877         start -= stream->packetsize;
1878         fseeko(stream->file_handle, start, SEEK_SET);
1879     }
1880     orig = start;
1881
1882     while (1)
1883     {
1884         if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1885         {
1886             const uint8_t *bp = buf;
1887             int i;
1888
1889             for ( i = sizeof(buf) - 8 * stream->packetsize; --i >= 0; ++bp )
1890             {
1891                 if ( have_ts_sync( bp, stream->packetsize ) )
1892                 {
1893                     break;
1894                 }
1895             }
1896             if ( i >= 0 )
1897             {
1898                 pos = ( bp - buf ) - stream->packetsize + 188;
1899                 break;
1900             }
1901             fseeko(stream->file_handle, -8 * stream->packetsize, SEEK_CUR);
1902             start = ftello(stream->file_handle);
1903         }
1904         else
1905         {
1906             return 0;
1907         }
1908     }
1909     fseeko(stream->file_handle, start+pos, SEEK_SET);
1910     return start - orig + pos;
1911 }
1912
1913
1914 typedef struct {
1915     uint8_t *buf;
1916     uint32_t val;
1917     int pos;
1918 } bitbuf_t;
1919
1920 static const unsigned int bitmask[] = {
1921     0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1922     0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1923     0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1924     0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1925
1926 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1927 {
1928     bb->pos = 0;
1929     bb->buf = buf;
1930     bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1931               (bb->buf[2] << 8) | bb->buf[3];
1932     if (clear)
1933         memset(bb->buf, 0, bufsize);
1934 }
1935
1936 static inline int buf_size(bitbuf_t *bb)
1937 {
1938     return bb->pos >> 3;
1939 }
1940
1941 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1942 {
1943     unsigned int val;
1944     int left = 32 - (bb->pos & 31);
1945
1946     if (bits < left)
1947     {
1948         val = (bb->val >> (left - bits)) & bitmask[bits];
1949         bb->pos += bits;
1950     }
1951     else
1952     {
1953         val = (bb->val & bitmask[left]) << (bits - left);
1954         bb->pos += left;
1955         bits -= left;
1956
1957         int pos = bb->pos >> 3;
1958         bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1959
1960         if (bits > 0)
1961         {
1962             val |= (bb->val >> (32 - bits)) & bitmask[bits];
1963             bb->pos += bits;
1964         }
1965     }
1966
1967     return val;
1968 }
1969
1970 // extract what useful information we can from the elementary stream
1971 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1972 // Descriptors with info we don't currently use are ignored.
1973 // The descriptor list & descriptor item formats are defined in
1974 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1975 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1976                                        const uint8_t *dp, uint8_t dlen)
1977 {
1978     const uint8_t *ep = dp + dlen;
1979
1980     while (dp < ep)
1981     {
1982         switch (dp[0])
1983         {
1984             case 5:    // Registration descriptor
1985                 stream->ts_format_id[esindx] = (dp[2] << 24) | (dp[3] << 16) |
1986                                                (dp[4] << 8)  | dp[5];
1987                 break;
1988
1989             case 10:    // ISO_639_language descriptor
1990                 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1991                 break;
1992
1993             case 0x6a:  // DVB AC-3 descriptor
1994                 stream->ts_stream_type[esindx] = 0x81;
1995                 break;
1996
1997             case 0x7a:  // DVB EAC-3 descriptor
1998                 stream->ts_stream_type[esindx] = 0x87;
1999                 break;
2000
2001             default:
2002                 break;
2003         }
2004         dp += dp[1] + 2;
2005     }
2006 }
2007
2008 static const char *stream_type_name (uint8_t stream_type)
2009 {
2010     return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
2011 }
2012
2013 int decode_program_map(hb_stream_t* stream)
2014 {
2015     bitbuf_t bb;
2016     set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
2017
2018     get_bits(&bb, 8);  // table_id
2019     get_bits(&bb, 4);
2020     unsigned int section_length = get_bits(&bb, 12);
2021     stream->pmt_info.section_length = section_length;
2022
2023     unsigned int program_number = get_bits(&bb, 16);
2024     stream->pmt_info.program_number = program_number;
2025     get_bits(&bb, 2);
2026     get_bits(&bb, 5);  // version_number
2027     get_bits(&bb, 1);
2028     get_bits(&bb, 8);  // section_number
2029     get_bits(&bb, 8);  // last_section_number
2030     get_bits(&bb, 3);
2031     stream->pmt_info.PCR_PID = get_bits(&bb, 13);
2032     get_bits(&bb, 4);
2033     int program_info_length = get_bits(&bb, 12);
2034     stream->pmt_info.program_info_length = program_info_length;
2035
2036     int i;
2037     for (i = 0; i < program_info_length - 2; )
2038     {
2039         uint8_t tag, len;
2040         tag = get_bits(&bb, 8);
2041         len = get_bits(&bb, 8);
2042         i += 2;
2043         if ( i + len > program_info_length )
2044         {
2045             break;
2046         }
2047         if (tag == 0x05 && len >= 4)
2048         {
2049             // registration descriptor
2050             stream->pmt_info.reg_desc = get_bits(&bb, 32);
2051             i += 4;
2052             len -= 4;
2053         }
2054         int j;
2055         for ( j = 0; j < len; j++ )
2056         {
2057             get_bits(&bb, 8);
2058         }
2059         i += len;
2060     }
2061     for ( ; i < program_info_length; i++ )
2062     {
2063         get_bits(&bb, 8);
2064     }
2065
2066     int cur_pos =  9 /* data after the section length field*/ + program_info_length;
2067     int done_reading_stream_types = 0;
2068     while (!done_reading_stream_types)
2069     {
2070         unsigned char stream_type = get_bits(&bb, 8);
2071         get_bits(&bb, 3);
2072         unsigned int elementary_PID = get_bits(&bb, 13);
2073         get_bits(&bb, 4);
2074         unsigned int ES_info_length = get_bits(&bb, 12);
2075
2076         int i=0;
2077         unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
2078         for (i=0; i < ES_info_length; i++)
2079         {
2080             ES_info_buf[i] = get_bits(&bb, 8);
2081         }
2082
2083         if ( index_of_pid( stream, elementary_PID ) < 0 )
2084         {
2085             // Defined audio stream types are 0x81 for AC-3/A52 audio 
2086             // and 0x03 for mpeg audio. But content producers seem to 
2087             // use other values (0x04 and 0x06 have both been observed) 
2088             // so at this point we say everything that isn't a video 
2089             // pid is audio then at the end of hb_stream_title_scan 
2090             // we'll figure out which are really audio by looking at 
2091             // the PES headers.
2092             i = stream->ts_number_pids;
2093             if (i < kMaxNumberDecodeStreams)
2094             {
2095                 stream->ts_pids[i] = elementary_PID;
2096                 stream->ts_stream_type[i] = stream_type;
2097                 if (ES_info_length > 0)
2098                 {
2099                     decode_element_descriptors(stream, i, ES_info_buf,
2100                                             ES_info_length);
2101                 }
2102                 stream->ts_stream_kind[i] = ts_stream_kind(stream, i);
2103                 ++stream->ts_number_pids;
2104             }
2105         }
2106
2107         cur_pos += 5 /* stream header */ + ES_info_length;
2108
2109         free(ES_info_buf);
2110
2111         if (cur_pos >= section_length - 4 /* stop before the CRC */)
2112             done_reading_stream_types = 1;
2113     }
2114
2115     return 1;
2116 }
2117
2118 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
2119 {
2120     // Get adaption header info
2121     int adapt_len = 0;
2122     int adaption = (buf[3] & 0x30) >> 4;
2123     if (adaption == 0)
2124             return 0;
2125     else if (adaption == 0x2)
2126             adapt_len = 184;
2127     else if (adaption == 0x3)
2128             adapt_len = buf[4] + 1;
2129     if (adapt_len > 184)
2130             return 0;
2131
2132     // Get payload start indicator
2133     int start;
2134     start = (buf[1] & 0x40) != 0;
2135
2136     // Get pointer length - only valid in packets with a start flag
2137     int pointer_len = 0;
2138
2139     if (start)
2140     {
2141         pointer_len = buf[4 + adapt_len] + 1;
2142         stream->pmt_info.tablepos = 0;
2143     }
2144     // Get Continuity Counter
2145     int continuity_counter = buf[3] & 0x0f;
2146     if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
2147     {
2148         hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
2149         return 0;
2150     }
2151     stream->pmt_info.current_continuity_counter = continuity_counter;
2152     stream->pmt_info.reading |= start;
2153
2154     // Add the payload for this packet to the current buffer
2155     int amount_to_copy = 184 - adapt_len - pointer_len;
2156     if (stream->pmt_info.reading && (amount_to_copy > 0))
2157     {
2158             stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
2159
2160             memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
2161             stream->pmt_info.tablepos += amount_to_copy;
2162     }
2163     if (stream->pmt_info.tablepos > 3)
2164     {
2165         // We have enough to check the section length
2166         int length;
2167         length = ((stream->pmt_info.tablebuf[1] << 8) + 
2168                   stream->pmt_info.tablebuf[2]) & 0xFFF;
2169         if (stream->pmt_info.tablepos > length + 1)
2170         {
2171             // We just finished a bunch of packets - parse the program map details
2172             int decode_ok = 0;
2173             if (stream->pmt_info.tablebuf[0] == 0x02)
2174                 decode_ok = decode_program_map(stream);
2175             free(stream->pmt_info.tablebuf);
2176             stream->pmt_info.tablebuf = NULL;
2177             stream->pmt_info.tablepos = 0;
2178             stream->pmt_info.reading = 0;
2179             if (decode_ok)
2180                 return decode_ok;
2181         }
2182
2183     }
2184
2185     return 0;
2186 }
2187
2188 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
2189 {
2190     unsigned char tablebuf[1024];
2191     unsigned int tablepos = 0;
2192
2193     int reading = 0;
2194
2195
2196     // Get adaption header info
2197     int adapt_len = 0;
2198     int adaption = (buf[3] & 0x30) >> 4;
2199     if (adaption == 0)
2200             return 0;
2201     else if (adaption == 0x2)
2202             adapt_len = 184;
2203     else if (adaption == 0x3)
2204             adapt_len = buf[4] + 1;
2205     if (adapt_len > 184)
2206             return 0;
2207
2208     // Get pointer length
2209     int pointer_len = buf[4 + adapt_len] + 1;
2210
2211     // Get payload start indicator
2212     int start;
2213     start = (buf[1] & 0x40) != 0;
2214
2215     if (start)
2216             reading = 1;
2217
2218     // Add the payload for this packet to the current buffer
2219     if (reading && (184 - adapt_len) > 0)
2220     {
2221             if (tablepos + 184 - adapt_len - pointer_len > 1024)
2222             {
2223                     hb_log("decode_PAT - Bad program section length (> 1024)");
2224                     return 0;
2225             }
2226             memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
2227             tablepos += 184 - adapt_len - pointer_len;
2228     }
2229
2230     if (start && reading)
2231     {
2232             memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
2233
2234
2235             unsigned int pos = 0;
2236             //while (pos < tablepos)
2237             {
2238                     bitbuf_t bb;
2239                     set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
2240
2241                     unsigned char section_id    = get_bits(&bb, 8);
2242                     get_bits(&bb, 4);
2243                     unsigned int section_len    = get_bits(&bb, 12);
2244                     get_bits(&bb, 16); // transport_id
2245                     get_bits(&bb, 2);
2246                     get_bits(&bb, 5);  // version_num
2247                     get_bits(&bb, 1);  // current_next
2248                     get_bits(&bb, 8);  // section_num
2249                     get_bits(&bb, 8);  // last_section
2250
2251                     switch (section_id)
2252                     {
2253                       case 0x00:
2254                         {
2255                           // Program Association Section
2256                           section_len -= 5;    // Already read transport stream ID, version num, section num, and last section num
2257                           section_len -= 4;   // Ignore the CRC
2258                           int curr_pos = 0;
2259                           stream->ts_number_pat_entries = 0;
2260                           while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
2261                           {
2262                             unsigned int pkt_program_num = get_bits(&bb, 16);
2263                             stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
2264
2265                             get_bits(&bb, 3);  // Reserved
2266                             if (pkt_program_num == 0)
2267                             {
2268                               get_bits(&bb, 13); // pkt_network_id
2269                             }
2270                             else
2271                             {
2272                               unsigned int pkt_program_map_PID = get_bits(&bb, 13);
2273                                 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
2274                             }
2275                             curr_pos += 4;
2276                             stream->ts_number_pat_entries++;
2277                           }
2278                         }
2279                         break;
2280                       case 0xC7:
2281                             {
2282                                     break;
2283                             }
2284                       case 0xC8:
2285                             {
2286                                     break;
2287                             }
2288                     }
2289
2290                     pos += 3 + section_len;
2291             }
2292
2293             tablepos = 0;
2294     }
2295     return 1;
2296 }
2297
2298 static void hb_ts_stream_find_pids(hb_stream_t *stream)
2299 {
2300     // To be different from every other broadcaster in the world, New Zealand TV
2301     // changes PMTs (and thus video & audio PIDs) when 'programs' change. Since
2302     // we may have the tail of the previous program at the beginning of this
2303     // file, take our PMT from the middle of the file.
2304     fseeko(stream->file_handle, 0, SEEK_END);
2305     uint64_t fsize = ftello(stream->file_handle);
2306     fseeko(stream->file_handle, fsize >> 1, SEEK_SET);
2307     align_to_next_packet(stream);
2308
2309     // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
2310     // to find the program map PID and then decode that to get the list of audio and video PIDs
2311
2312     for (;;)
2313     {
2314         const uint8_t *buf = next_packet( stream );
2315
2316         if ( buf == NULL )
2317         {
2318             hb_log("hb_ts_stream_find_pids - end of file");
2319             break;
2320         }
2321
2322         // Get pid
2323         int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
2324
2325         if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
2326         {
2327           decode_PAT(buf, stream);
2328           continue;
2329         }
2330
2331         int pat_index = 0;
2332         for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
2333         {
2334             // There are some streams where the PAT table has multiple entries as if their are
2335             // multiple programs in the same transport stream, and yet there's actually only one
2336             // program really in the stream. This seems to be true for transport streams that
2337             // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
2338             // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
2339             // but the EyeTV is only recording a single (selected) program number and not rewriting the
2340             // PAT info on export to match what's actually on the stream.
2341             // Until we have a way of handling multiple programs per transport stream elegantly we'll match
2342             // on the first pat entry for which we find a matching program map PID.  The ideal solution would
2343             // be to build a title choice popup from the PAT program number details and then select from
2344             // their - but right now the API's not capable of that.
2345             if (stream->pat_info[pat_index].program_number != 0 &&
2346                 pid == stream->pat_info[pat_index].program_map_PID)
2347             {
2348               if (build_program_map(buf, stream) > 0)
2349                 break;
2350             }
2351         }
2352         // Keep going  until we have a complete set of PIDs
2353         if ( index_of_video( stream ) >= 0 )
2354           break;
2355     }
2356
2357     hb_log("hb_ts_stream_find_pids - found the following PIDS");
2358     hb_log("    Video PIDS : ");
2359     int i;
2360     for (i=0; i < stream->ts_number_pids; i++)
2361     {
2362         if ( stream->ts_stream_kind[i] == V )
2363         {
2364             hb_log( "      0x%x type %s (0x%x)", 
2365                     stream->ts_pids[i],
2366                     stream_type_name(stream->ts_stream_type[i]),
2367                     stream->ts_stream_type[i]);
2368         }
2369     }
2370     hb_log("    Audio PIDS : ");
2371     for (i = 0; i < stream->ts_number_pids; i++)
2372     {
2373         if ( stream->ts_stream_kind[i] != V )
2374         {
2375             hb_log( "      0x%x type %s (0x%x)", 
2376                     stream->ts_pids[i],
2377                     stream_type_name(stream->ts_stream_type[i]),
2378                     stream->ts_stream_type[i] );
2379         }
2380     }
2381  }
2382
2383
2384 static void fwrite64( hb_stream_t *stream, void *buf, int len )
2385 {
2386     if ( len > 0 )
2387     {
2388         int pos = stream->fwrite_buf->size;
2389         if ( pos + len > stream->fwrite_buf->alloc )
2390         {
2391             int size = MAX(stream->fwrite_buf->alloc * 2, pos + len);
2392             hb_buffer_realloc(stream->fwrite_buf, size);
2393         }
2394         memcpy( &(stream->fwrite_buf->data[pos]), buf, len );
2395         stream->fwrite_buf->size += len;
2396     }
2397 }
2398
2399 // convert a PES PTS or DTS to an int64
2400 static int64_t pes_timestamp( const uint8_t *pes )
2401 {
2402     int64_t ts = ( (uint64_t)(pes[0] & 0xe ) << 29 );
2403     ts |= ( pes[1] << 22 ) | ( ( pes[2] >> 1 ) << 15 ) |
2404           ( pes[3] << 7 ) | ( pes[4] >> 1 );
2405     return ts;
2406 }
2407
2408 static void generate_output_data(hb_stream_t *stream, int curstream)
2409 {
2410     hb_buffer_t *buf = stream->fwrite_buf;
2411     uint8_t *tdat = stream->ts_buf[curstream]->data;
2412
2413     buf->id = stream->ts_pids[curstream];
2414     switch (stream->ts_stream_kind[curstream])
2415     {
2416         case A:
2417             buf->type = AUDIO_BUF;
2418             break;
2419
2420         case V:
2421             buf->type = VIDEO_BUF;
2422             break;
2423
2424         default:
2425             buf->type = OTHER_BUF;
2426             break;
2427     }
2428
2429     // check if this packet was referenced to an older pcr and if that
2430     // pcr was significantly different than the one we're using now.
2431     // (the reason for the uint cast on the pcr difference is that the
2432     // difference is significant if it advanced by more than 200ms or if
2433     // it went backwards by any amount. The negative numbers look like huge
2434     // unsigned ints so the cast allows both conditions to be checked at once.
2435     int bufpcr = stream->ts_buf[curstream]->cur;
2436     int curpcr = stream->ts_pcr_out;
2437     if ( bufpcr && bufpcr < curpcr &&
2438          (uint64_t)(stream->ts_pcrhist[curpcr & 3] - stream->ts_pcrhist[bufpcr & 3]) > 200*90LL )
2439     {
2440         // we've sent up a new pcr but have a packet referenced to an
2441         // old pcr and the difference was enough to trigger a discontinuity
2442         // correction. smash the timestamps or we'll mess up the correction.
2443         buf->start = -1;
2444         buf->renderOffset = -1;
2445     }
2446     else
2447     {
2448         if ( stream->ts_pcr_out != stream->ts_pcr_in )
2449         {
2450             // we have a new pcr
2451             stream->ts_pcr_out = stream->ts_pcr_in;
2452             buf->stop = stream->ts_pcr;
2453             stream->ts_pcrhist[stream->ts_pcr_out & 3] = stream->ts_pcr;
2454         }
2455         else
2456         {
2457             buf->stop = -1;
2458         }
2459
2460         // put the PTS & possible DTS into 'start' & 'renderOffset' then strip
2461         // off the PES header.
2462         if ( tdat[7] & 0xc0 )
2463         {
2464             buf->start = pes_timestamp( tdat + 9 );
2465             buf->renderOffset = ( tdat[7] & 0x40 )? pes_timestamp( tdat + 14 ) :
2466                                                     buf->start;
2467         }
2468         else
2469         {
2470             buf->start = -1;
2471             buf->renderOffset = -1;
2472         }
2473     }
2474     int hlen = tdat[8] + 9;
2475
2476     fwrite64( stream,  tdat + hlen, stream->ts_pos[curstream] - hlen );
2477
2478     stream->ts_pos[curstream] = 0;
2479     stream->ts_buf[curstream]->size = 0;
2480 }
2481
2482 static void hb_ts_stream_append_pkt(hb_stream_t *stream, int idx, const uint8_t *buf, int len)
2483 {
2484     if (stream->ts_pos[idx] + len > stream->ts_buf[idx]->alloc)
2485     {
2486         int size;
2487
2488         size = MAX(stream->ts_buf[idx]->alloc * 2, stream->ts_pos[idx] + len);
2489         hb_buffer_realloc(stream->ts_buf[idx], size);
2490     }
2491     memcpy(stream->ts_buf[idx]->data + stream->ts_pos[idx], buf, len);
2492     stream->ts_pos[idx] += len;
2493     stream->ts_buf[idx]->size += len;
2494 }
2495
2496 /***********************************************************************
2497  * hb_ts_stream_decode
2498  ***********************************************************************
2499  *
2500  **********************************************************************/
2501 int hb_ts_decode_pkt( hb_stream_t *stream, const uint8_t * pkt, hb_buffer_t *obuf )
2502 {
2503     /*
2504      * stash the output buffer pointer in our stream so we don't have to
2505      * pass it & its original value to everything we call.
2506      */
2507     obuf->size = 0;
2508     stream->fwrite_buf = obuf;
2509
2510     int video_index = index_of_video(stream);
2511
2512     int curstream;
2513
2514     /* This next section validates the packet */
2515
2516     // Get pid and use it to find stream state.
2517     int pid = ((pkt[1] & 0x1F) << 8) | pkt[2];
2518     if ( ( curstream = index_of_pid( stream, pid ) ) < 0 )
2519     {
2520         return 0;
2521     }
2522
2523     // Get error
2524     int errorbit = (pkt[1] & 0x80) != 0;
2525     if (errorbit)
2526     {
2527         ts_err( stream, curstream,  "packet error bit set");
2528         return 0;
2529     }
2530
2531     // Get adaption header info
2532     int adaption = (pkt[3] & 0x30) >> 4;
2533     int adapt_len = 0;
2534     if (adaption == 0)
2535     {
2536         ts_err( stream, curstream,  "adaptation code 0");
2537         return 0;
2538     }
2539     else if (adaption == 0x2)
2540         adapt_len = 184;
2541     else if (adaption == 0x3)
2542     {
2543         adapt_len = pkt[4] + 1;
2544         if (adapt_len > 184)
2545         {
2546             ts_err( stream, curstream,  "invalid adapt len %d", adapt_len);
2547             return 0;
2548         }
2549     }
2550
2551     if ( adapt_len > 0 )
2552     {
2553         if ( pkt[5] & 0x40 )
2554         {
2555             // found a random access point
2556         }
2557         // if there's an adaptation header & PCR_flag is set
2558         // get the PCR (Program Clock Reference)
2559         if ( adapt_len > 7 && ( pkt[5] & 0x10 ) != 0 )
2560         {
2561             stream->ts_pcr = ( (uint64_t)pkt[6] << (33 - 8) ) |
2562                              ( (uint64_t)pkt[7] << (33 - 16) ) |
2563                              ( (uint64_t)pkt[8] << (33 - 24) ) |
2564                              ( (uint64_t)pkt[9] << (33 - 32) ) |
2565                              ( pkt[10] >> 7 );
2566             ++stream->ts_pcr_in;
2567             stream->ts_found_pcr = 1;
2568             stream->ts_flags |= TS_HAS_PCR;
2569         }
2570     }
2571
2572     // If we don't have a PCR yet but the stream has PCRs just loop
2573     // so we don't process anything until we have a clock reference.
2574     // Unfortunately the HD Home Run appears to null out the PCR so if
2575     // we didn't detect a PCR during scan keep going and we'll use
2576     // the video stream DTS for the PCR.
2577
2578     if ( !stream->ts_found_pcr && ( stream->ts_flags & TS_HAS_PCR ) )
2579     {
2580         return 0;
2581     }
2582
2583     // Get continuity
2584     // Continuity only increments for adaption values of 0x3 or 0x01
2585     // and is not checked for start packets.
2586
2587     int start = (pkt[1] & 0x40) != 0;
2588
2589     if ( (adaption & 0x01) != 0 )
2590     {
2591         int continuity = (pkt[3] & 0xF);
2592         if ( continuity == stream->ts_streamcont[curstream] )
2593         {
2594             // Spliced transport streams can have duplicate 
2595             // continuity counts at the splice boundary.
2596             // Test to see if the packet is really a duplicate
2597             // by comparing packet summaries to see if they
2598             // match.
2599             uint8_t summary[8];
2600
2601             summary[0] = adaption;
2602             summary[1] = adapt_len;
2603             if (adapt_len + 4 + 6 + 9 <= 188)
2604             {
2605                 memcpy(&summary[2], pkt+4+adapt_len+9, 6);
2606             }
2607             else
2608             {
2609                 memset(&summary[2], 0, 6);
2610             }
2611             if ( memcmp( summary, stream->ts_pkt_summary[curstream], 8 ) == 0 )
2612             {
2613                 // we got a duplicate packet (usually used to introduce
2614                 // a PCR when one is needed). The only thing that can
2615                 // change in the dup is the PCR which we grabbed above
2616                 // so ignore the rest.
2617                 return 0;
2618             }
2619         }
2620         if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2621              !stream->ts_skipbad[curstream] &&
2622              (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2623         {
2624             ts_err( stream, curstream,  "continuity error: got %d expected %d",
2625                     (int)continuity,
2626                     (stream->ts_streamcont[curstream] + 1) & 0xf );
2627             stream->ts_streamcont[curstream] = continuity;
2628             return 0;
2629         }
2630         stream->ts_streamcont[curstream] = continuity;
2631
2632         // Save a summary of this packet for later duplicate
2633         // testing.  The summary includes some header information
2634         // and payload bytes.  Should be enough to detect 
2635         // non-duplicates.
2636         stream->ts_pkt_summary[curstream][0] = adaption;
2637         stream->ts_pkt_summary[curstream][1] = adapt_len;
2638         if (adapt_len + 4 + 6 + 9 <= 188)
2639         {
2640             memcpy(&stream->ts_pkt_summary[curstream][2], 
2641                     pkt+4+adapt_len+9, 6);
2642         }
2643         else
2644         {
2645             memset(&stream->ts_pkt_summary[curstream][2], 0, 6);
2646         }
2647     }
2648
2649     /* If we get here the packet is valid - process its data */
2650
2651     if ( start )
2652     {
2653         // Found a random access point (now we can start a frame/audio packet..)
2654
2655         if ( stream->need_keyframe )
2656         {
2657             // we're looking for the first video frame because we're
2658             // doing random access during 'scan'
2659             if ( curstream != video_index || !isIframe( stream, pkt, adapt_len ) )
2660             {
2661                 // not the video stream or didn't find an I frame
2662                 // but we'll only wait 255 video frames for an I frame.
2663                 if ( curstream != video_index || ++stream->need_keyframe )
2664                 {
2665                     return 0;
2666                 }
2667             }
2668             stream->need_keyframe = 0;
2669         }
2670
2671         // If we were skipping a bad packet, start fresh on this new PES packet..
2672         if (stream->ts_skipbad[curstream] == 1)
2673         {
2674             stream->ts_skipbad[curstream] = 0;
2675         }
2676
2677         if ( curstream == video_index )
2678         {
2679             ++stream->frames;
2680
2681             // if we don't have a pcr yet use the dts from this frame
2682             if ( !stream->ts_found_pcr )
2683             {
2684                 // PES must begin with an mpeg start code & contain
2685                 // a DTS or PTS.
2686                 const uint8_t *pes = pkt + adapt_len + 4;
2687                 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2688                      ( pes[7] >> 6 ) == 0 )
2689                 {
2690                     return 0;
2691                 }
2692                 // if we have a dts use it otherwise use the pts
2693                 stream->ts_pcr = pes_timestamp( pes + ( pes[7] & 0x40?14:9 ) );
2694                 ++stream->ts_pcr_in;
2695             }
2696         }
2697
2698         // if this is a multiplexed stream make sure this is the
2699         // substream we want.
2700         if ( stream->ts_multiplexed[curstream] )
2701         {
2702             // PES must begin with an mpeg start code & contain
2703             // a DTS or PTS.
2704             const uint8_t *pes = pkt + adapt_len + 4;
2705             if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2706                  pes[3] != 0xfd )
2707             {
2708                 stream->ts_skipbad[curstream] = 1;
2709                 return 0;
2710             }
2711             // the last byte of the header is the extension id. see if
2712             // it's the one we want.
2713             if ( pes[pes[8]+8] != stream->ts_multiplexed[curstream] )
2714             {
2715                 stream->ts_skipbad[curstream] = 1;
2716                 return 0;
2717             }
2718         }
2719
2720         // If we have some data already on this stream, turn it into
2721         // a program stream packet. Then add the payload for this
2722         // packet to the current pid's buffer.
2723         if ( stream->ts_pos[curstream] )
2724         {
2725             // we have to ship the old packet before updating the pcr
2726             // since the packet we've been accumulating is referenced
2727             // to the old pcr.
2728             generate_output_data(stream, curstream);
2729
2730             // remember the pcr that was in effect when we started
2731             // this packet.
2732             stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2733             hb_ts_stream_append_pkt(stream, curstream, pkt + 4 + adapt_len,
2734                                     184 - adapt_len);
2735             return 1;
2736         }
2737         // remember the pcr that was in effect when we started this packet.
2738         stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2739     }
2740
2741     // Add the payload for this packet to the current buffer
2742     if (!stream->ts_skipbad[curstream] && (184 - adapt_len) > 0)
2743     {
2744         hb_ts_stream_append_pkt(stream, curstream, pkt + 4 + adapt_len,
2745                                 184 - adapt_len);
2746         // see if we've hit the end of this PES packet
2747         const uint8_t *pes = stream->ts_buf[curstream]->data;
2748         int len = ( pes[4] << 8 ) + pes[5] + 6;
2749         if ( len > 6 && stream->ts_pos[curstream] == len &&
2750              pes[0] == 0x00 && pes[1] == 0x00 && pes[2] == 0x01 )
2751         {
2752             generate_output_data(stream, curstream);
2753             return 1;
2754         }
2755     }
2756     return 0;
2757 }
2758
2759 static int hb_ts_stream_decode( hb_stream_t *stream, hb_buffer_t *obuf )
2760 {
2761     // spin until we get a packet of data from some stream or hit eof
2762     while ( 1 )
2763     {
2764         const uint8_t *buf = next_packet(stream);
2765         if ( buf == NULL )
2766         {
2767             // end of file - we didn't finish filling our ps write buffer
2768             // so just discard the remainder (the partial buffer is useless)
2769             hb_log("hb_ts_stream_decode - eof");
2770             return 0;
2771         }
2772
2773         if (hb_ts_decode_pkt( stream, buf, obuf ))
2774         {
2775             return 1;
2776         }
2777     }
2778     return 0;
2779 }
2780
2781 static void hb_ts_stream_reset(hb_stream_t *stream)
2782 {
2783     int i;
2784
2785     for (i=0; i < kMaxNumberDecodeStreams; i++)
2786     {
2787         stream->ts_pos[i] = 0;
2788         stream->ts_skipbad[i] = 1;
2789         stream->ts_streamcont[i] = -1;
2790     }
2791
2792     stream->need_keyframe = 0;
2793
2794     stream->ts_found_pcr = 0;
2795     stream->ts_pcr_out = 0;
2796     stream->ts_pcr_in = 0;
2797     stream->ts_pcr = 0;
2798
2799     stream->frames = 0;
2800     stream->errors = 0;
2801     stream->last_error_frame = -10000;
2802     stream->last_error_count = 0;
2803
2804     align_to_next_packet(stream);
2805 }
2806
2807 // ------------------------------------------------------------------
2808 // Support for reading media files via the ffmpeg libraries.
2809
2810 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2811 {
2812     // add a codec to the context here so it will be there when we
2813     // read the first packet.
2814     AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2815     context->workaround_bugs = FF_BUG_AUTODETECT;
2816     context->error_recognition = 1;
2817     context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2818     AVCodec *codec = avcodec_find_decoder( context->codec_id );
2819     hb_avcodec_open( context, codec );
2820 }
2821
2822 // The ffmpeg stream reader / parser shares a lot of state with the 
2823 // decoder via a codec context kept in the AVStream of the reader's
2824 // AVFormatContext. Since decoding is done in a different thread we
2825 // have to somehow pass this codec context to the decoder and we have
2826 // to do it before the first packet is read (so we can't put the info
2827 // in the buf we'll send downstream). Decoders don't have any way to
2828 // get to the stream directly (they're not passed the title or job
2829 // pointers during a scan) so this is a back door for the decoder to
2830 // get the codec context. We just stick the stream pointer in the next
2831 // slot an array of pointers maintained as a circular list then return
2832 // the index into the list combined with the ffmpeg stream index as the
2833 // codec_param that will be passed to the decoder init routine. We make
2834 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2835 // so that we don't have to do a complicated allocator or worry about
2836 // deleting entries on close. 
2837 //
2838 // Entries can only be added to this list during a scan and are never
2839 // deleted so the list access doesn't require locking.
2840 static hb_stream_t **ffmpeg_streams;    // circular list of stream pointers
2841 static int ffmpeg_stream_cur;           // where we put the last stream pointer
2842 #define ffmpeg_sl_bits (10)             // log2 stream list size (in entries)
2843 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2844
2845 // add a stream to the list & return the appropriate codec_param to access it
2846 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2847 {
2848     if ( !ffmpeg_streams )
2849     {
2850         ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2851     }
2852
2853     // the title scan adds all the ffmpeg media streams at once so we
2854     // only add a new entry to our stream list if the stream is different
2855     // than last time.
2856     int slot = ffmpeg_stream_cur;
2857     if ( ffmpeg_streams[slot] != stream )
2858     {
2859         // new stream - put it in the next slot of the stream list
2860         slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2861         ffmpeg_streams[slot] = stream;
2862     }
2863
2864     ffmpeg_add_codec( stream, stream_index );
2865
2866     return ( stream_index << ffmpeg_sl_bits ) | slot;
2867 }
2868
2869 // we're about to open 'title' to convert it - remap the stream associated
2870 // with the video & audio codec params of the title to refer to 'stream'
2871 // (the original scan stream was closed and no longer exists).
2872 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2873 {
2874     // all the video & audio came from the same stream so remapping
2875     // the video's stream slot takes care of everything.
2876     int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2877     ffmpeg_streams[slot] = stream;
2878
2879     // add codecs for all the streams used by the title
2880     ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2881
2882     int i;
2883     hb_audio_t *audio;
2884     for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2885     {
2886         if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2887         {
2888             ffmpeg_add_codec( stream,
2889                               audio->config.in.codec_param >> ffmpeg_sl_bits );
2890         }
2891     }
2892 }
2893
2894 void *hb_ffmpeg_context( int codec_param )
2895 {
2896     if ( ffmpeg_streams == NULL )
2897         return NULL;
2898
2899     int slot = codec_param & (ffmpeg_sl_size - 1);
2900     int stream_index = codec_param >> ffmpeg_sl_bits;
2901     return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2902 }
2903
2904 void *hb_ffmpeg_avstream( int codec_param )
2905 {
2906     if ( ffmpeg_streams == NULL )
2907         return NULL;
2908
2909     int slot = codec_param & (ffmpeg_sl_size - 1);
2910     int stream_index = codec_param >> ffmpeg_sl_bits;
2911     return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2912 }
2913
2914 static AVFormatContext *ffmpeg_deferred_close;
2915
2916 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2917 {
2918     if ( ffmpeg_deferred_close )
2919     {
2920         av_close_input_file( ffmpeg_deferred_close );
2921         ffmpeg_deferred_close = NULL;
2922     }
2923     AVFormatContext *ic;
2924
2925     av_log_set_level( AV_LOG_ERROR );
2926     if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2927     {
2928         return 0;
2929     }
2930     if ( hb_av_find_stream_info( ic ) < 0 )
2931         goto fail;
2932
2933     stream->ffmpeg_ic = ic;
2934     stream->hb_stream_type = ffmpeg;
2935     stream->ffmpeg_pkt = malloc(sizeof(*stream->ffmpeg_pkt));
2936     av_init_packet( stream->ffmpeg_pkt );
2937     stream->chapter_end = INT64_MAX;
2938
2939     if ( title )
2940     {
2941         // we're opening for read. scan passed out codec params that
2942         // indexed its stream so we need to remap them so they point
2943         // to this stream.
2944         ffmpeg_remap_stream( stream, title );
2945         av_log_set_level( AV_LOG_ERROR );
2946     }
2947     else
2948     {
2949         // we're opening for scan. let ffmpeg put some info into the
2950         // log about what we've got.
2951         av_log_set_level( AV_LOG_INFO );
2952         dump_format( ic, 0, stream->path, 0 );
2953         av_log_set_level( AV_LOG_ERROR );
2954
2955         // accept this file if it has at least one video stream we can decode
2956         int i;
2957         for (i = 0; i < ic->nb_streams; ++i )
2958         {
2959             if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2960             {
2961                 break;
2962             }
2963         }
2964         if ( i >= ic->nb_streams )
2965             goto fail;
2966     }
2967     return 1;
2968
2969   fail:
2970     av_close_input_file( ic );
2971     return 0;
2972 }
2973
2974 static void ffmpeg_close( hb_stream_t *d )
2975 {
2976     // XXX since we're sharing the CodecContext with the downstream
2977     // decoder proc we can't close the stream. We need to reference count
2978     // this so we can close it when both are done with their instance but
2979     // for now just defer the close until the next stream open or close.
2980     if ( ffmpeg_deferred_close )
2981     {
2982         av_close_input_file( ffmpeg_deferred_close );
2983     }
2984     ffmpeg_deferred_close = d->ffmpeg_ic;
2985     if ( d->ffmpeg_pkt != NULL )
2986     {
2987         free( d->ffmpeg_pkt );
2988         d->ffmpeg_pkt = NULL;
2989     }
2990 }
2991
2992 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2993 {
2994     AVStream *st = stream->ffmpeg_ic->streams[id];
2995     AVCodecContext *codec = st->codec;
2996     AVMetadataTag *tag;
2997     int layout;
2998
2999     // scan will ignore any audio without a bitrate. Since we've already
3000     // typed the audio in order to determine its codec we set up the audio
3001     // paramters here.
3002     layout = hb_ff_layout_xlat( codec->channel_layout, codec->channels );
3003     if ( !layout )
3004     {
3005         // Unsupported layout
3006         return;
3007     }
3008     if ( codec->bit_rate || codec->sample_rate )
3009     {
3010         hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
3011
3012         audio->id = id;
3013         if ( codec->codec_id == CODEC_ID_AC3 )
3014         {
3015             audio->config.in.codec = HB_ACODEC_AC3;
3016         }
3017         else if ( codec->codec_id == CODEC_ID_DTS )
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         // XXX the following conditional is to handle avi files that
3436         // use M$ 'packed b-frames' and occasionally have negative
3437         // sizes for the null frames these require.
3438         if ( err != AVERROR_NOMEM || stream->ffmpeg_pkt->size >= 0 )
3439             // eof
3440             return 0;
3441     }
3442     if ( stream->ffmpeg_pkt->size <= 0 )
3443     {
3444         // M$ "invalid and inefficient" packed b-frames require 'null frames'
3445         // following them to preserve the timing (since the packing puts two
3446         // or more frames in what looks like one avi frame). The contents and
3447         // size of these null frames are ignored by the ff_h263_decode_frame
3448         // as long as they're < 20 bytes. We need a positive size so we use
3449         // one byte if we're given a zero or negative size. We don't know
3450         // if the pkt data points anywhere reasonable so we just stick a
3451         // byte of zero in our outbound buf.
3452         buf->size = 1;
3453         *buf->data = 0;
3454     }
3455     else
3456     {
3457         if ( stream->ffmpeg_pkt->size > buf->alloc )
3458         {
3459             // sometimes we get absurd sizes from ffmpeg
3460             if ( stream->ffmpeg_pkt->size >= (1 << 25) )
3461             {
3462                 hb_log( "ffmpeg_read: pkt too big: %d bytes", stream->ffmpeg_pkt->size );
3463                 av_free_packet( stream->ffmpeg_pkt );
3464                 return ffmpeg_read( stream, buf );
3465             }
3466             // need to expand buffer
3467             hb_buffer_realloc( buf, stream->ffmpeg_pkt->size );
3468         }
3469         memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
3470         buf->size = stream->ffmpeg_pkt->size;
3471     }
3472     buf->id = stream->ffmpeg_pkt->stream_index;
3473     if ( buf->id == stream->ffmpeg_video_id )
3474     {
3475         if ( stream->need_keyframe )
3476         {
3477             // we've just done a seek (generally for scan or live preview) and
3478             // want to start at a keyframe. Some ffmpeg codecs seek to a key
3479             // frame but most don't. So we spin until we either get a keyframe
3480             // or we've looked through 50 video frames without finding one.
3481             if ( ! ffmpeg_is_keyframe( stream ) && ++stream->need_keyframe < 50 )
3482             {
3483                 av_free_packet( stream->ffmpeg_pkt );
3484                 goto again;
3485             }
3486             stream->need_keyframe = 0;
3487         }
3488         ++stream->frames;
3489     }
3490
3491     // if we haven't done it already, compute a conversion factor to go
3492     // from the ffmpeg timebase for the stream to HB's 90KHz timebase.
3493     double tsconv = stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index];
3494     if ( ! tsconv )
3495     {
3496         AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index];
3497         tsconv = 90000. * (double)s->time_base.num / (double)s->time_base.den;
3498         stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index] = tsconv;
3499     }
3500
3501     buf->start = av_to_hb_pts( stream->ffmpeg_pkt->pts, tsconv );
3502     buf->renderOffset = av_to_hb_pts( stream->ffmpeg_pkt->dts, tsconv );
3503     if ( buf->renderOffset >= 0 && buf->start == -1 )
3504     {
3505         buf->start = buf->renderOffset;
3506     }
3507     else if ( buf->renderOffset == -1 && buf->start >= 0 )
3508     {
3509         buf->renderOffset = buf->start;
3510     }
3511     
3512     /* 
3513      * Fill out buf->stop for subtitle packets
3514      * 
3515      * libavcodec's MKV demuxer stores the duration of UTF-8 subtitles (CODEC_ID_TEXT)
3516      * in the 'convergence_duration' field for some reason.
3517      * 
3518      * Other subtitles' durations are stored in the 'duration' field.
3519      * 
3520      * VOB subtitles (CODEC_ID_DVD_SUBTITLE) do not have their duration stored in
3521      * either field. This is not a problem because the VOB decoder can extract this
3522      * information from the packet payload itself.
3523      * 
3524      * SSA subtitles (CODEC_ID_SSA) do not have their duration stored in
3525      * either field. This is not a problem because the SSA decoder can extract this
3526      * information from the packet payload itself.
3527      */
3528     enum CodecID ffmpeg_pkt_codec = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index]->codec->codec_id;
3529     if ( ffmpeg_pkt_codec == CODEC_ID_TEXT ) {
3530         int64_t ffmpeg_pkt_duration = stream->ffmpeg_pkt->convergence_duration;
3531         int64_t buf_duration = av_to_hb_pts( ffmpeg_pkt_duration, tsconv );
3532         buf->stop = buf->start + buf_duration;
3533     }
3534     if ( ffmpeg_pkt_codec == CODEC_ID_MOV_TEXT ) {
3535         int64_t ffmpeg_pkt_duration = stream->ffmpeg_pkt->duration;
3536         int64_t buf_duration = av_to_hb_pts( ffmpeg_pkt_duration, tsconv );
3537         buf->stop = buf->start + buf_duration;
3538     }
3539
3540     /*
3541      * Check to see whether this video buffer is on a chapter
3542      * boundary, if so mark it as such in the buffer then advance
3543      * chapter_end to the end of the next chapter.
3544      * If there are no chapters, chapter_end is always initialized to INT64_MAX
3545      * (roughly 3 million years at our 90KHz clock rate) so the test
3546      * below handles both the chapters & no chapters case.
3547      */
3548     if ( buf->id == stream->ffmpeg_video_id && buf->start >= stream->chapter_end )
3549     {
3550         hb_chapter_t *chapter = hb_list_item( stream->title->list_chapter,
3551                                               stream->chapter+1 );
3552         if( chapter )
3553         {
3554             stream->chapter++;
3555             stream->chapter_end += chapter->duration;
3556             buf->new_chap = stream->chapter + 1;
3557             hb_deep_log( 2, "ffmpeg_read starting chapter %i at %"PRId64,
3558                          buf->new_chap, buf->start);
3559         } else {
3560             // Must have run out of chapters, stop looking.
3561             stream->chapter_end = INT64_MAX;
3562         }
3563     } else {
3564         buf->new_chap = 0;
3565     }
3566     av_free_packet( stream->ffmpeg_pkt );
3567     return 1;
3568 }
3569
3570 static int ffmpeg_seek( hb_stream_t *stream, float frac )
3571 {
3572     AVFormatContext *ic = stream->ffmpeg_ic;
3573     if ( frac > 0. )
3574     {
3575         int64_t pos = (double)ic->duration * (double)frac;
3576         if ( ic->start_time != AV_NOPTS_VALUE && ic->start_time > 0 )
3577         {
3578             pos += ic->start_time;
3579         }
3580         av_seek_frame( ic, -1, pos, 0 );
3581         stream->need_keyframe = 1;
3582     }
3583     else
3584     {
3585         av_seek_frame( ic, -1, 0LL, AVSEEK_FLAG_BACKWARD );
3586     }
3587     return 1;
3588 }
3589
3590 // Assumes that we are always seeking forward
3591 static int ffmpeg_seek_ts( hb_stream_t *stream, int64_t ts )
3592 {
3593     AVFormatContext *ic = stream->ffmpeg_ic;
3594     int64_t pos;
3595
3596     pos = ts * AV_TIME_BASE / 90000 + ffmpeg_initial_timestamp( stream );
3597     stream->need_keyframe = 1;
3598     // Seek to the nearest timestamp before that requested where
3599     // there is an I-frame
3600     return av_seek_frame( ic, -1, pos, AVSEEK_FLAG_BACKWARD );
3601 }