OSDN Git Service

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