OSDN Git Service

- add John A. Stebbins' changes to handle TrueHD and DTS-HD multiplexed streams.
[handbrake-jp/handbrake-jp-git.git] / libhb / stream.c
1 /* $Id$
2
3    This file is part of the HandBrake source code.
4    Homepage: <http://handbrake.fr/>.
5    It may be used under the terms of the GNU General Public License. */
6
7 #include <string.h>
8 #include <ctype.h>
9 #include <errno.h>
10
11 #include "hb.h"
12 #include "lang.h"
13 #include "a52dec/a52.h"
14 #include "libavcodec/avcodec.h"
15 #include "libavformat/avformat.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  */
28 typedef struct {
29     enum { U = 1, A, V } kind; /* unknown / audio / video */
30     int codec;          /* HB worker object id of codec */
31     int codec_param;    /* param for codec (usually ffmpeg codec id) */
32     const char* name;   /* description of type */
33 } stream2codec_t;
34
35 #define st(id, kind, codec, codec_param, name) \
36  [id] = { kind, codec, codec_param, name }
37
38 static const stream2codec_t st2codec[256] = {
39     st(0x01, V, WORK_DECMPEG2,     0,              "MPEG1"),
40     st(0x02, V, WORK_DECMPEG2,     0,              "MPEG2"),
41     st(0x03, A, HB_ACODEC_MPGA,    CODEC_ID_MP2,   "MPEG1"),
42     st(0x04, A, HB_ACODEC_MPGA,    CODEC_ID_MP2,   "MPEG2"),
43     st(0x05, U, 0,                 0,              "ISO 13818-1 private section"),
44     st(0x06, U, 0,                 0,              "ISO 13818-1 PES private data"),
45     st(0x07, U, 0,                 0,              "ISO 13522 MHEG"),
46     st(0x08, U, 0,                 0,              "ISO 13818-1 DSM-CC"),
47     st(0x09, U, 0,                 0,              "ISO 13818-1 auxiliary"),
48     st(0x0a, U, 0,                 0,              "ISO 13818-6 encap"),
49     st(0x0b, U, 0,                 0,              "ISO 13818-6 DSM-CC U-N msgs"),
50     st(0x0c, U, 0,                 0,              "ISO 13818-6 Stream descriptors"),
51     st(0x0d, U, 0,                 0,              "ISO 13818-6 Sections"),
52     st(0x0e, U, 0,                 0,              "ISO 13818-1 auxiliary"),
53     st(0x0f, A, HB_ACODEC_MPGA,    CODEC_ID_AAC,   "ISO 13818-7 AAC Audio"),
54     st(0x10, V, WORK_DECAVCODECV,  CODEC_ID_MPEG4, "MPEG4"),
55     st(0x11, A, HB_ACODEC_MPGA,    CODEC_ID_AAC_LATM, "MPEG4 LATM AAC"),
56     st(0x12, U, 0,                 0,              "MPEG4 generic"),
57
58     st(0x14, U, 0,                 0,              "ISO 13818-6 DSM-CC download"),
59
60     st(0x1b, V, WORK_DECAVCODECV,  CODEC_ID_H264,  "H.264"),
61
62     //st(0x80, U, 0,                 0,              "DigiCipher II Video"),
63     st(0x81, A, HB_ACODEC_AC3,     0,              "AC-3"),
64     st(0x82, A, HB_ACODEC_DCA,     0,              "HDMV DTS"),
65     st(0x83, A, HB_ACODEC_LPCM,    0,              "LPCM"),
66     st(0x84, A, 0,                 0,              "SDDS"),
67     st(0x85, U, 0,                 0,              "ATSC Program ID"),
68     st(0x86, A, HB_ACODEC_DCA,     0,              "DTS-HD"),
69     st(0x87, A, 0,                 0,              "E-AC-3"),
70
71     st(0x8a, A, HB_ACODEC_DCA,     0,              "DTS"),
72
73     st(0x91, A, HB_ACODEC_AC3,     0,              "AC-3"),
74     st(0x92, U, 0,                 0,              "Subtitle"),
75
76     st(0x94, A, 0,                 0,              "SDDS"),
77     st(0xa0, V, 0,                 0,              "MSCODEC"),
78
79     st(0xea, V, WORK_DECAVCODECV,  CODEC_ID_VC1,   "VC1"),
80 };
81 #undef st
82
83 typedef enum {
84     hb_stream_type_unknown = 0,
85     transport,
86     program,
87     dvd_program,
88     ffmpeg
89 } hb_stream_type_t;
90
91 #define kMaxNumberVideoPIDS 1
92 #define kMaxNumberAudioPIDS 15
93 #define kMaxNumberDecodeStreams (kMaxNumberVideoPIDS+kMaxNumberAudioPIDS)
94 #define kMaxNumberPMTStreams 32
95
96
97 struct hb_stream_s
98 {
99     int     frames;             /* video frames so far */
100     int     errors;             /* total errors so far */
101     int     last_error_frame;   /* frame # at last error message */
102     int     last_error_count;   /* # errors at last error message */
103     int     packetsize;         /* Transport Stream packet size */
104
105     int8_t  need_keyframe;      // non-zero if want to start at a keyframe
106     int8_t  ts_no_RAP;          // non-zero if there are no random access points
107
108     int8_t  ts_found_pcr;       // non-zero if we've found at least one input pcr
109     int     ts_pcr_out;         // sequence number of most recent output pcr
110     int     ts_pcr_in;          // sequence number of most recent input pcr
111     int64_t ts_pcr;             // most recent input pcr
112     int64_t ts_pcrhist[4];      // circular buffer of output pcrs
113
114     uint8_t *ts_packet;         /* buffer for one TS packet */
115     hb_buffer_t *ts_buf[kMaxNumberDecodeStreams];
116     int     ts_pos[kMaxNumberDecodeStreams];
117     int8_t  ts_skipbad[kMaxNumberDecodeStreams];
118     int8_t  ts_streamcont[kMaxNumberDecodeStreams];
119
120     hb_buffer_t *fwrite_buf;      /* PS buffer (set by hb_ts_stream_decode) */
121
122     /*
123      * Stuff before this point is dynamic state updated as we read the
124      * stream. Stuff after this point is stream description state that
125      * we learn during the initial scan but cache so it can be
126      * reused during the conversion read.
127      */
128     uint8_t ts_number_video_pids;
129     uint8_t ts_number_audio_pids;
130
131     int16_t ts_video_pids[kMaxNumberVideoPIDS];
132     int16_t ts_audio_pids[kMaxNumberAudioPIDS];
133
134     uint32_t ts_format_id[kMaxNumberDecodeStreams];
135 #define TS_FORMAT_ID_AC3 (('A' << 24) | ('C' << 16) | ('-' << 8) | '3')
136     uint8_t ts_stream_type[kMaxNumberDecodeStreams];
137     uint8_t ts_multiplexed[kMaxNumberDecodeStreams];
138
139     char    *path;
140     FILE    *file_handle;
141     hb_stream_type_t hb_stream_type;
142     hb_title_t *title;
143
144     AVFormatContext *ffmpeg_ic;
145     AVPacket *ffmpeg_pkt;
146     double ffmpeg_tsconv[MAX_STREAMS];
147     uint8_t ffmpeg_video_id;
148
149     struct {
150         int lang_code;
151         int flags;
152         int rate;
153         int bitrate;
154     } a52_info[kMaxNumberAudioPIDS];
155
156     struct
157     {
158         unsigned short program_number;
159         unsigned short program_map_PID;
160     } pat_info[kMaxNumberPMTStreams];
161     int     ts_number_pat_entries;
162
163     struct
164     {
165         int reading;
166         unsigned char *tablebuf;
167         unsigned int tablepos;
168         unsigned char current_continuity_counter;
169
170         int section_length;
171         int program_number;
172         unsigned int PCR_PID;
173         int program_info_length;
174         unsigned char *progam_info_descriptor_data;
175         struct
176         {
177             unsigned char stream_type;
178             unsigned short elementary_PID;
179             unsigned short ES_info_length;
180             unsigned char *es_info_descriptor_data;
181         } pmt_stream_info[kMaxNumberPMTStreams];
182     } pmt_info;
183 };
184
185 /***********************************************************************
186  * Local prototypes
187  **********************************************************************/
188 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
189 static void hb_ts_stream_init(hb_stream_t *stream);
190 static void hb_ts_stream_find_pids(hb_stream_t *stream);
191 static int hb_ts_stream_decode(hb_stream_t *stream, hb_buffer_t *obuf);
192 static void hb_ts_stream_reset(hb_stream_t *stream);
193 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
194                                                        int aud_pid_index);
195 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title);
196 static off_t align_to_next_packet(hb_stream_t *stream);
197
198 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title );
199 static void ffmpeg_close( hb_stream_t *d );
200 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream );
201 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf );
202 static int ffmpeg_seek( hb_stream_t *stream, float frac );
203
204 /*
205  * streams have a bunch of state that's learned during the scan. We don't
206  * want to throw away the state when scan does a close then relearn
207  * everything when reader does an open. So we save the stream state on
208  * the close following a scan and reuse it when 'reader' does an open.
209  */
210 static hb_list_t *stream_state_list;
211
212 static hb_stream_t *hb_stream_lookup( const char *path )
213 {
214     if ( stream_state_list == NULL )
215         return NULL;
216
217     hb_stream_t *ss;
218     int i = 0;
219
220     while ( ( ss = hb_list_item( stream_state_list, i++ ) ) != NULL )
221     {
222         if ( strcmp( path, ss->path ) == 0 )
223         {
224             break;
225         }
226     }
227     return ss;
228 }
229
230 static void hb_stream_state_delete( hb_stream_t *ss )
231 {
232     hb_list_rem( stream_state_list, ss );
233     free( ss->path );
234     free( ss );
235 }
236
237 /*
238  * logging routines.
239  * these frontend hb_log because transport streams can have a lot of errors
240  * so we want to rate limit messages. this routine limits the number of
241  * messages to at most one per minute of video. other errors that occur
242  * during the minute are counted & the count is output with the next
243  * error msg we print.
244  */
245 static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
246 {
247     // limit error printing to at most one per minute of video (at 30fps)
248     ++stream->errors;
249     if ( stream->frames - stream->last_error_frame >= 30*60 )
250     {
251         char msg[256];
252
253         vsnprintf( msg, sizeof(msg), log, args );
254
255         if ( stream->errors - stream->last_error_count < 10 )
256         {
257             hb_log( "stream: error near frame %d: %s", stream->frames, msg );
258         }
259         else
260         {
261             int Edelta = stream->errors - stream->last_error_count;
262             double Epcnt = (double)Edelta * 100. /
263                             (stream->frames - stream->last_error_frame);
264             hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
265                     Edelta, Epcnt, stream->frames, msg );
266         }
267         stream->last_error_frame = stream->frames;
268         stream->last_error_count = stream->errors;
269     }
270 }
271
272 static void ts_warn( hb_stream_t *stream, char *log, ... )
273 {
274     va_list     args;
275     va_start( args, log );
276     ts_warn_helper( stream, log, args );
277     va_end( args );
278 }
279
280 static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
281 {
282     va_list     args;
283     va_start( args, log );
284     ts_warn_helper( stream, log, args );
285     va_end( args );
286
287     stream->ts_skipbad[curstream] = 1;
288     stream->ts_pos[curstream] = 0;
289     stream->ts_streamcont[curstream] = -1;
290 }
291
292 static int check_ps_sync(const uint8_t *buf)
293 {
294     // a legal MPEG program stream must start with a Pack header in the
295     // first four bytes.
296     return (buf[0] == 0x00) && (buf[1] == 0x00) &&
297            (buf[2] == 0x01) && (buf[3] == 0xba);
298 }
299
300 static int check_ps_sys(const uint8_t *buf)
301 {
302     // a legal MPEG program stream must start with a Pack followed by a
303     // SYS. If we've already verified the pack, this skips over it and checks
304     // for the sys header.
305     int pos = 14 + ( buf[13] & 0x7 );   // skip over the PACK
306     return (buf[pos+0] == 0x00) && (buf[pos+1] == 0x00) &&
307            (buf[pos+2] == 0x01) && (buf[pos+3] == 0xbb);
308 }
309
310 static int check_ts_sync(const uint8_t *buf)
311 {
312     // must have initial sync byte, no scrambling & a legal adaptation ctrl
313     return (buf[0] == 0x47) && ((buf[3] >> 6) == 0) && ((buf[3] >> 4) > 0);
314 }
315
316 static int have_ts_sync(const uint8_t *buf, int psize)
317 {
318     return check_ts_sync(&buf[0*psize]) && check_ts_sync(&buf[1*psize]) &&
319            check_ts_sync(&buf[2*psize]) && check_ts_sync(&buf[3*psize]) &&
320            check_ts_sync(&buf[4*psize]) && check_ts_sync(&buf[5*psize]) &&
321            check_ts_sync(&buf[6*psize]) && check_ts_sync(&buf[7*psize]);
322 }
323
324 static int hb_stream_check_for_ts(const uint8_t *buf)
325 {
326     // transport streams should have a sync byte every 188 bytes.
327     // search the first 8KB of buf looking for at least 8 consecutive
328     // correctly located sync patterns.
329     int offset = 0;
330
331     for ( offset = 0; offset < 8*1024-8*188; ++offset )
332     {
333         if ( have_ts_sync( &buf[offset], 188) )
334             return 188 | (offset << 8);
335         if ( have_ts_sync( &buf[offset], 192) )
336             return 192 | (offset << 8);
337         if ( have_ts_sync( &buf[offset], 204) )
338             return 204 | (offset << 8);
339         if ( have_ts_sync( &buf[offset], 208) )
340             return 208 | (offset << 8);
341     }
342     return 0;
343 }
344
345 static int hb_stream_check_for_ps(const uint8_t *buf)
346 {
347     // program streams should start with a PACK then a SYS header.
348     return check_ps_sync(buf) && check_ps_sys(buf);
349 }
350
351 static int hb_stream_check_for_dvd_ps(const uint8_t *buf)
352 {
353     // DVD program streams should have a Pack header every 2048 bytes.
354     // check that we have 4 of these in a row.
355     return check_ps_sync(&buf[0*2048]) && check_ps_sync(&buf[1*2048]) &&
356            check_ps_sync(&buf[2*2048]) && check_ps_sync(&buf[3*2048]);
357 }
358
359 static int hb_stream_get_type(hb_stream_t *stream)
360 {
361     uint8_t buf[2048*4];
362
363     if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
364     {
365         int psize;
366         if ( ( psize = hb_stream_check_for_ts(buf) ) != 0 )
367         {
368             int offset = psize >> 8;
369             psize &= 0xff;
370             hb_log("file is MPEG Transport Stream with %d byte packets"
371                    " offset %d bytes", psize, offset);
372             stream->packetsize = psize;
373             stream->hb_stream_type = transport;
374             hb_ts_stream_init(stream);
375             if ( !stream->ts_number_video_pids || !stream->ts_number_audio_pids )
376             {
377                 return 0;
378             }
379             return 1;
380         }
381         if ( hb_stream_check_for_dvd_ps(buf) != 0 )
382         {
383             hb_log("file is MPEG DVD Program Stream");
384             stream->hb_stream_type = dvd_program;
385             return 1;
386         }
387         if ( hb_stream_check_for_ps(buf) != 0 )
388         {
389             hb_log("file is MPEG Program Stream");
390             stream->hb_stream_type = program;
391             return 1;
392         }
393     }
394     return 0;
395 }
396
397 static void hb_stream_delete_dynamic( hb_stream_t *d )
398 {
399     if( d->file_handle )
400     {
401         fclose( d->file_handle );
402                 d->file_handle = NULL;
403     }
404
405         int i=0;
406
407     if ( d->ts_packet )
408     {
409         free( d->ts_packet );
410         d->ts_packet = NULL;
411     }
412         for (i = 0; i < kMaxNumberDecodeStreams; i++)
413         {
414                 if (d->ts_buf[i])
415                 {
416                         hb_buffer_close(&(d->ts_buf[i]));
417                         d->ts_buf[i] = NULL;
418                 }
419         }
420 }
421
422 static void hb_stream_delete( hb_stream_t *d )
423 {
424     hb_stream_delete_dynamic( d );
425     free( d->path );
426     free( d );
427 }
428
429 /***********************************************************************
430  * hb_stream_open
431  ***********************************************************************
432  *
433  **********************************************************************/
434 hb_stream_t * hb_stream_open( char *path, hb_title_t *title )
435 {
436     FILE *f = fopen( path, "r" );
437     if ( f == NULL )
438     {
439         hb_log( "hb_stream_open: open %s failed", path );
440         return NULL;
441     }
442
443     hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
444     if ( d == NULL )
445     {
446         fclose( f );
447         hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
448         return NULL;
449     }
450
451     /*
452      * if we're opening the stream to read & convert, we need
453      * the state we saved when we scanned the stream. if we're
454      * opening the stream to scan it we want to rebuild the state
455      * (even if we have saved state, the stream may have changed).
456      */
457     hb_stream_t *ss = hb_stream_lookup( path );
458     if ( title && ss && ss->hb_stream_type != ffmpeg )
459     {
460         /*
461          * copy the saved state since we might be encoding the same stream
462          * multiple times.
463          */
464         memcpy( d, ss, sizeof(*d) );
465         d->file_handle = f;
466         d->title = title;
467         d->path = strdup( path );
468
469         if ( d->hb_stream_type == transport )
470         {
471             d->ts_packet = malloc( d->packetsize );
472
473             int i = 0;
474             for ( ; i < d->ts_number_video_pids + d->ts_number_audio_pids; i++)
475             {
476                 d->ts_buf[i] = hb_buffer_init(d->packetsize);
477                                 d->ts_buf[i]->size = 0;
478             }
479             hb_stream_seek( d, 0. );
480
481             if ( d->packetsize == 188 )
482             {
483                 // Assume that an over-the-air transport stream can lose PCR
484                 // packets and try to filter out the timing inconsistencies.
485                 title->flaky_clock = 1;
486             }
487         }
488         return d;
489     }
490
491     /*
492      * opening for scan - delete any saved state then (re)scan the stream.
493      * If it's something we can deal with (MPEG2 PS or TS) return a stream
494      * reference structure & null otherwise.
495      */
496     if ( ss != NULL )
497     {
498         hb_stream_state_delete( ss );
499     }
500     d->file_handle = f;
501     d->title = title;
502     d->path = strdup( path );
503     if (d->path != NULL )
504     {
505         if ( hb_stream_get_type( d ) != 0 )
506         {
507             return d;
508         }
509         fclose( d->file_handle );
510                 d->file_handle = NULL;
511         if ( ffmpeg_open( d, title ) )
512         {
513             return d;
514         }
515     }
516     if ( d->file_handle )
517     {
518         fclose( d->file_handle );
519     }
520     if (d->path)
521     {
522         free( d->path );
523     }
524     hb_log( "hb_stream_open: open %s failed", path );
525     free( d );
526     return NULL;
527 }
528
529 /***********************************************************************
530  * hb_stream_close
531  ***********************************************************************
532  * Closes and frees everything
533  **********************************************************************/
534 void hb_stream_close( hb_stream_t ** _d )
535 {
536     hb_stream_t *stream = * _d;
537
538     if ( stream->hb_stream_type == ffmpeg )
539     {
540         ffmpeg_close( stream );
541         hb_stream_delete( stream );
542         *_d = NULL;
543         return;
544     }
545
546     if ( stream->frames )
547     {
548         hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
549                 stream->errors, (double)stream->errors * 100. /
550                 (double)stream->frames );
551     }
552
553     /*
554      * if the stream was opened for a scan, cache the result, otherwise delete
555      * the state.
556      */
557     if ( stream->title == NULL )
558     {
559         hb_stream_delete_dynamic( stream );
560         if ( stream_state_list == NULL )
561         {
562             stream_state_list = hb_list_init();
563         }
564         hb_list_add( stream_state_list, stream );
565     }
566     else
567     {
568         hb_stream_delete( stream );
569     }
570     *_d = NULL;
571 }
572
573 /* when the file was first opened we made entries for all the audio elementary
574  * streams we found in it. Streams that were later found during the preview scan
575  * now have an audio codec, type, rate, etc., associated with them. At the end
576  * of the scan we delete all the audio entries that weren't found by the scan
577  * or don't have a format we support. This routine deletes audio entry 'indx'
578  * by setting its PID to an invalid value so no packet will match it. (We can't
579  * move any of the entries since the index of the entry is used as the id
580  * of the media stream for HB. */
581 static void hb_stream_delete_audio_entry(hb_stream_t *stream, int indx)
582 {
583     stream->ts_audio_pids[indx] = -stream->ts_audio_pids[indx];
584 }
585
586 static int index_of_pid(int pid, hb_stream_t *stream)
587 {
588     int i;
589
590     if ( pid == stream->ts_video_pids[0] )
591         return 0;
592
593     for ( i = 0; i < stream->ts_number_audio_pids; ++i )
594         if ( pid == stream->ts_audio_pids[i] )
595             return i + 1;
596
597     return -1;
598 }
599
600 /***********************************************************************
601  * hb_ps_stream_title_scan
602  ***********************************************************************
603  *
604  **********************************************************************/
605 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
606 {
607         if ( stream->hb_stream_type == ffmpeg )
608         return ffmpeg_title_scan( stream );
609
610     // 'Barebones Title'
611     hb_title_t *aTitle = hb_title_init( stream->path, 0 );
612     aTitle->index = 1;
613
614         // Copy part of the stream path to the title name
615         char *sep = strrchr(stream->path, '/');
616         if (sep)
617                 strcpy(aTitle->name, sep+1);
618         char *dot_term = strrchr(aTitle->name, '.');
619         if (dot_term)
620                 *dot_term = '\0';
621
622     // Height, width,  rate and aspect ratio information is filled in when the previews are built
623
624     hb_stream_duration(stream, aTitle);
625
626     // One Chapter
627     hb_chapter_t * chapter;
628     chapter = calloc( sizeof( hb_chapter_t ), 1 );
629     chapter->index = 1;
630     chapter->duration = aTitle->duration;
631     chapter->hours = aTitle->hours;
632     chapter->minutes = aTitle->minutes;
633     chapter->seconds = aTitle->seconds;
634     hb_list_add( aTitle->list_chapter, chapter );
635
636     // Figure out how many audio streams we really have:
637     // - For transport streams, for each PID listed in the PMT (whether
638     //   or not it was an audio stream type) read the bitstream until we
639     //   find an packet from that PID containing a PES header and see if
640     //   the elementary stream is an audio type.
641     // - For program streams read the first 4MB and take every unique
642     //   audio stream we find.
643         if (stream->hb_stream_type == transport)
644         {
645         int i;
646
647         for (i=0; i < stream->ts_number_audio_pids; i++)
648         {
649             hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
650             if (audio->config.in.codec)
651                 hb_list_add( aTitle->list_audio, audio );
652             else
653             {
654                 free(audio);
655                 hb_stream_delete_audio_entry(stream, i);
656             }
657         }
658
659         // make sure we're grabbing the PCR PID
660         if ( index_of_pid( stream->pmt_info.PCR_PID, stream ) < 0 )
661         {
662             stream->ts_audio_pids[stream->ts_number_audio_pids++] =
663                 stream->pmt_info.PCR_PID;
664         }
665
666         // set the video id, codec & muxer
667         aTitle->video_id = 0;
668         aTitle->video_codec = st2codec[stream->ts_stream_type[0]].codec;
669         aTitle->video_codec_param = st2codec[stream->ts_stream_type[0]].codec_param;
670         aTitle->demuxer = HB_MPEG2_TS_DEMUXER;
671         }
672     else
673     {
674         hb_ps_stream_find_audio_ids(stream, aTitle);
675     }
676
677   return aTitle;
678 }
679
680 /*
681  * read the next transport stream packet from 'stream'. Return NULL if
682  * we hit eof & a pointer to the sync byte otherwise.
683  */
684 static const uint8_t *next_packet( hb_stream_t *stream )
685 {
686     uint8_t *buf = stream->ts_packet + stream->packetsize - 188;
687
688     while ( 1 )
689     {
690         if ( fread(stream->ts_packet, 1, stream->packetsize, stream->file_handle) !=
691              stream->packetsize )
692         {
693             return NULL;
694         }
695         if (buf[0] == 0x47)
696         {
697             return buf;
698         }
699         // lost sync - back up to where we started then try to re-establish.
700         off_t pos = ftello(stream->file_handle) - stream->packetsize;
701         off_t pos2 = align_to_next_packet(stream);
702         if ( pos2 == 0 )
703         {
704             hb_log( "next_packet: eof while re-establishing sync @ %lld", pos );
705             return NULL;
706         }
707         ts_warn( stream, "next_packet: sync lost @ %lld, regained after %lld bytes",
708                  pos, pos2 );
709     }
710 }
711
712 /*
713  * skip to the start of the next PACK header in program stream src_stream.
714  */
715 static void skip_to_next_pack( hb_stream_t *src_stream )
716 {
717     // scan forward until we find the start of the next pack
718     uint32_t strt_code = -1;
719     int c;
720
721     flockfile( src_stream->file_handle );
722     while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
723     {
724         strt_code = ( strt_code << 8 ) | c;
725         if ( strt_code == 0x000001ba )
726             // we found the start of the next pack
727             break;
728     }
729     funlockfile( src_stream->file_handle );
730
731     // if we didn't terminate on an eof back up so the next read
732     // starts on the pack boundary.
733     if ( c != EOF )
734     {
735         fseeko( src_stream->file_handle, -4, SEEK_CUR );
736     }
737 }
738
739 /*
740  * scan the next MB of 'stream' to try to find a random access point
741  */
742 static void hb_ts_stream_find_RAP( hb_stream_t *stream )
743 {
744     off_t starting_point = ftello(stream->file_handle);
745     int npack = 300000; // max packets to read
746
747     while (--npack >= 0)
748     {
749         off_t cur = ftello(stream->file_handle);
750         const uint8_t *buf = next_packet( stream );
751         if ( buf == NULL )
752         {
753             break;
754         }
755         switch (buf[3] & 0x30)
756         {
757             case 0x00: // illegal
758                 continue;
759
760             case 0x20: // fill packet
761             case 0x30: // adaptation
762                 if ( buf[5] & 0x40 )
763                 {
764                     // found a random access point
765                     fseeko( stream->file_handle, cur, SEEK_SET );
766                     return;
767                 }
768                 continue;
769         }
770     }
771
772     /* didn't find it */
773     fseeko( stream->file_handle, starting_point, SEEK_SET );
774     stream->ts_no_RAP = 1;
775 }
776
777 /*
778  * scan the next MB of 'stream' to find the next start packet for
779  * the Packetized Elementary Stream associated with TS PID 'pid'.
780  */
781 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
782 {
783     int npack = 300000; // max packets to read
784
785     while (--npack >= 0)
786     {
787         const uint8_t *buf = next_packet( stream );
788         if ( buf == NULL )
789         {
790             hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
791             return 0;
792         }
793
794         /*
795          * The PES header is only in TS packets with 'start' set so we check
796          * that first then check for the right PID.
797          */
798         if ((buf[1] & 0x40) == 0 || (buf[1] & 0x1f) != (pid >> 8) ||
799             buf[2] != (pid & 0xff))
800         {
801             // not a start packet or not the pid we want
802             continue;
803         }
804
805         /* skip over the TS hdr to return a pointer to the PES hdr */
806         int udata = 4;
807         switch (buf[3] & 0x30)
808         {
809             case 0x00: // illegal
810             case 0x20: // fill packet
811                 continue;
812
813             case 0x30: // adaptation
814                 if (buf[4] > 182)
815                 {
816                     hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
817                     continue;
818                 }
819                 udata += buf[4] + 1;
820                 break;
821         }
822         /* PES hdr has to begin with an mpeg start code */
823         if (buf[udata+0] == 0x00 && buf[udata+1] == 0x00 && buf[udata+2] == 0x01)
824         {
825             return &buf[udata];
826         }
827     }
828
829     /* didn't find it */
830     return 0;
831 }
832
833 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
834 {
835     hb_buffer_t *buf  = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
836     hb_list_t *list = hb_list_init();
837     // how many blocks we read while searching for a video PES header
838     int blksleft = 1024;
839     uint64_t pts = 0;
840
841     while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
842     {
843         hb_buffer_t *es;
844
845         // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
846         hb_demux_ps( buf, list, 0 );
847
848         while ( ( es = hb_list_item( list, 0 ) ) )
849         {
850             hb_list_rem( list, es );
851             if ( es->id == 0xe0 )
852             {
853                 // this PES contains video - if there's a PTS we're done
854                 // hb_demux_ps left the PTS in buf_es->start.
855                 if ( es->start != ~0 )
856                 {
857                     pts = es->start;
858                     blksleft = 0;
859                     break;
860                 }
861             }
862             hb_buffer_close( &es );
863         }
864     }
865     hb_list_empty( &list );
866     hb_buffer_close(&buf);
867     return pts;
868 }
869
870 /***********************************************************************
871  * hb_stream_duration
872  ***********************************************************************
873  *
874  * Finding stream duration is difficult.  One issue is that the video file
875  * may have chunks from several different program fragments (main feature,
876  * commercials, station id, trailers, etc.) all with their own base pts
877  * value.  We can't find the piece boundaries without reading the entire
878  * file but if we compute a rate based on time stamps from two different
879  * pieces the result will be meaningless.  The second issue is that the
880  * data rate of compressed video normally varies by 5-10x over the length
881  * of the video. This says that we want to compute the rate over relatively
882  * long segments to get a representative average but long segments increase
883  * the likelihood that we'll cross a piece boundary.
884  *
885  * What we do is take time stamp samples at several places in the file
886  * (currently 16) then compute the average rate (i.e., ticks of video per
887  * byte of the file) for all pairs of samples (N^2 rates computed for N
888  * samples). Some of those rates will be absurd because the samples came
889  * from different segments. Some will be way low or high because the
890  * samples came from a low or high motion part of the segment. But given
891  * that we're comparing *all* pairs the majority of the computed rates
892  * should be near the overall average.  So we median filter the computed
893  * rates to pick the most representative value.
894  *
895  **********************************************************************/
896 struct pts_pos {
897     uint64_t pos;   /* file position of this PTS sample */
898     uint64_t pts;   /* PTS from video stream */
899 };
900
901 #define NDURSAMPLES 16
902
903 // get one (position, timestamp) sampple from a transport or program
904 // stream.
905 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
906 {
907     struct pts_pos pp = { 0, 0 };
908
909     if ( stream->hb_stream_type == transport )
910     {
911         const uint8_t *buf;
912         fseeko( stream->file_handle, fpos, SEEK_SET );
913         align_to_next_packet( stream );
914         buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
915         if ( buf == NULL )
916         {
917             hb_log("hb_sample_pts: couldn't find video packet near %llu", fpos);
918             return pp;
919         }
920         if ( ( buf[7] >> 7 ) != 1 )
921         {
922             hb_log("hb_sample_pts: no PTS in video packet near %llu", fpos);
923             return pp;
924         }
925         pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
926                  ( (uint64_t)buf[10] << 22 ) |
927                  ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
928                  ( (uint64_t)buf[12] << 7 ) |
929                  ( (uint64_t)buf[13] >> 1 );
930     }
931     else
932     {
933         // round address down to nearest dvd sector start
934         fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
935         fseeko( stream->file_handle, fpos, SEEK_SET );
936         if ( stream->hb_stream_type == program )
937         {
938             skip_to_next_pack( stream );
939         }
940         pp.pts = hb_ps_stream_getVideoPTS( stream );
941     }
942     pp.pos = ftello(stream->file_handle);
943     return pp;
944 }
945
946 static int dur_compare( const void *a, const void *b )
947 {
948     const double *aval = a, *bval = b;
949     return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
950 }
951
952 // given an array of (position, time) samples, compute a max-likelihood
953 // estimate of the average rate by computing the rate between all pairs
954 // of samples then taking the median of those rates.
955 static double compute_stream_rate( struct pts_pos *pp, int n )
956 {
957     int i, j;
958     double rates[NDURSAMPLES * NDURSAMPLES / 2];
959     double *rp = rates;
960
961     // the following nested loops compute the rates between all pairs.
962     *rp = 0;
963     for ( i = 0; i < n-1; ++i )
964     {
965         // Bias the median filter by not including pairs that are "far"
966         // from one another. This is to handle cases where the file is
967         // made of roughly equal size pieces where a symmetric choice of
968         // pairs results in having the same number of intra-piece &
969         // inter-piece rate estimates. This would mean that the median
970         // could easily fall in the inter-piece part of the data which
971         // would give a bogus estimate. The 'ns' index creates an
972         // asymmetry that favors locality.
973         int ns = i + ( n >> 1 );
974         if ( ns > n )
975             ns = n;
976         for ( j = i+1; j < ns; ++j )
977         {
978             if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
979             {
980                 *rp = ((double)( pp[j].pts - pp[i].pts )) /
981                       ((double)( pp[j].pos - pp[i].pos ));
982                                 ++rp;
983             }
984         }
985     }
986     // now compute and return the median of all the (n*n/2) rates we computed
987     // above.
988     int nrates = rp - rates;
989     qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
990     return rates[nrates >> 1];
991 }
992
993 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
994 {
995     struct pts_pos ptspos[NDURSAMPLES];
996     struct pts_pos *pp = ptspos;
997     int i;
998
999     fseeko(stream->file_handle, 0, SEEK_END);
1000     uint64_t fsize = ftello(stream->file_handle);
1001     uint64_t fincr = fsize / NDURSAMPLES;
1002     uint64_t fpos = fincr / 2;
1003     for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
1004     {
1005         *pp++ = hb_sample_pts(stream, fpos);
1006     }
1007     uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
1008     inTitle->duration = dur;
1009     dur /= 90000;
1010     inTitle->hours    = dur / 3600;
1011     inTitle->minutes  = ( dur % 3600 ) / 60;
1012     inTitle->seconds  = dur % 60;
1013
1014     rewind(stream->file_handle);
1015 }
1016
1017 /***********************************************************************
1018  * hb_stream_read
1019  ***********************************************************************
1020  *
1021  **********************************************************************/
1022 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
1023 {
1024         if ( src_stream->hb_stream_type == ffmpeg )
1025     {
1026         return ffmpeg_read( src_stream, b );
1027     }
1028     if ( src_stream->hb_stream_type == dvd_program )
1029     {
1030         size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
1031                                 src_stream->file_handle);
1032         return (amt_read > 0);
1033     }
1034     if ( src_stream->hb_stream_type == program )
1035     {
1036         // a general program stream has arbitrary sized pack's. we're
1037         // currently positioned at the start of a pack so read up to but
1038         // not including the start of the next, expanding the buffer
1039         // as necessary.
1040         uint8_t *cp = b->data;
1041         uint8_t *ep = cp + b->alloc;
1042         uint32_t strt_code = -1;
1043         int c;
1044
1045         // consume the first byte of the initial pack so we don't match on
1046         // it in the loop below.
1047         if ( ( c = getc( src_stream->file_handle ) ) == EOF )
1048             return 0;
1049
1050         *cp++ = c;
1051
1052         flockfile( src_stream->file_handle );
1053         while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
1054         {
1055             strt_code = ( strt_code << 8 ) | c;
1056             if ( strt_code == 0x000001ba )
1057                 // we found the start of the next pack
1058                 break;
1059             if ( cp >= ep )
1060             {
1061                 // need to expand the buffer
1062                 int curSize = cp - b->data;
1063                 hb_buffer_realloc( b, curSize * 2 );
1064                 cp = b->data + curSize;
1065                 ep = b->data + b->alloc;
1066             }
1067             *cp++ = c;
1068         }
1069         funlockfile( src_stream->file_handle );
1070
1071         // if we didn't terminate on an eof back up so the next read
1072         // starts on the pack boundary.
1073         b->size = cp - b->data;
1074         if ( c != EOF )
1075         {
1076             fseeko( src_stream->file_handle, -4, SEEK_CUR );
1077             b->size -= 4;
1078         }
1079         return 1;
1080     }
1081     return hb_ts_stream_decode( src_stream, b );
1082 }
1083
1084 /***********************************************************************
1085  * hb_stream_seek
1086  ***********************************************************************
1087  *
1088  **********************************************************************/
1089 int hb_stream_seek( hb_stream_t * stream, float f )
1090 {
1091         if ( stream->hb_stream_type == ffmpeg )
1092     {
1093         return ffmpeg_seek( stream, f );
1094     }
1095     off_t stream_size, cur_pos, new_pos;
1096     double pos_ratio = f;
1097     cur_pos = ftello( stream->file_handle );
1098     fseeko( stream->file_handle, 0, SEEK_END );
1099     stream_size = ftello( stream->file_handle );
1100     new_pos = (off_t) ((double) (stream_size) * pos_ratio);
1101     new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
1102
1103     int r = fseeko( stream->file_handle, new_pos, SEEK_SET );
1104     if (r == -1)
1105     {
1106         fseeko( stream->file_handle, cur_pos, SEEK_SET );
1107         return 0;
1108     }
1109
1110     if ( stream->hb_stream_type == transport )
1111     {
1112         // We need to drop the current decoder output and move
1113         // forwards to the next transport stream packet.
1114         hb_ts_stream_reset(stream);
1115         if ( f > 0 )
1116         {
1117             if ( !stream->ts_no_RAP )
1118             {
1119                 // we're not at the beginning - try to find a random access point
1120                 hb_ts_stream_find_RAP( stream );
1121             }
1122             stream->need_keyframe = 1;
1123         }
1124         else
1125         {
1126             // we're at the beginning - say we have video sync so that we
1127             // won't drop initial SPS & PPS data on an AVC stream.
1128             stream->need_keyframe = 0;
1129         }
1130     }
1131     else if ( stream->hb_stream_type == program )
1132     {
1133         skip_to_next_pack( stream );
1134     }
1135
1136     return 1;
1137 }
1138
1139 static const char* make_upper( const char* s )
1140 {
1141     static char name[8];
1142     char *cp = name;
1143     char *ep = cp + sizeof(name)-1;
1144
1145     while ( *s && cp < ep )
1146     {
1147         *cp++ = islower(*s)? toupper(*s) : *s;
1148         ++s;
1149     }
1150     *cp = 0;
1151     return name;
1152 }
1153
1154 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1155 {
1156     /* XXX
1157      * This is a duplicate of code in dvd.c - it should get factored out
1158      * into a common routine. We probably should only be putting the lang
1159      * code or a lang pointer into the audio config & let the common description
1160      * formatting routine in scan.c do all the stuff below.
1161      */
1162     const char *codec_name;
1163     AVCodecContext *cc;
1164
1165     if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1166          ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1167          avcodec_find_decoder( cc->codec_id ) )
1168     {
1169         codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1170         if ( !strcmp( codec_name, "LIBFAAD" ) )
1171         {
1172             codec_name = "AAC";
1173         }
1174     }
1175     else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1176               avcodec_find_decoder( audio->config.in.codec_param ) )
1177     {
1178         codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1179     }
1180     else
1181     {
1182         codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1183                      audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1184                      audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" : 
1185                      audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" : 
1186                      audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1187                      "Unknown";
1188     }
1189     snprintf( audio->config.lang.description,
1190               sizeof( audio->config.lang.description ), "%s (%s)",
1191               strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1192               codec_name );
1193     snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1194               strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1195     snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1196               "%s", lang->iso639_2);
1197 }
1198
1199 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1200                                                        int aud_pid_index)
1201 {
1202     off_t cur_pos = ftello(stream->file_handle);
1203     hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1204     const uint8_t *buf;
1205
1206     fseeko(stream->file_handle, 0, SEEK_SET);
1207     align_to_next_packet(stream);
1208     buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
1209
1210     /* check that we found a PES header */
1211     uint8_t stype = 0;
1212     if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1213     {
1214         stype = stream->ts_stream_type[1 + aud_pid_index];
1215
1216         // 0xbd ("private stream 1") is the normal container for non-ISO
1217         // media - AC3/DCA/PCM/etc.
1218         if ( buf[3] == 0xbd )
1219         {
1220             if ( st2codec[stype].kind == U )
1221             {
1222                 // XXX assume unknown stream types are AC-3 (if they're not
1223                 // audio we'll find that out during the scan but if they're
1224                 // some other type of audio we'll end up ignoring them).
1225                 stype = 0x81;
1226                 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1227             }
1228         }
1229         else if ( buf[3] == 0xfd )
1230         {
1231             // 0xfd indicates an extended stream id (ISO 13818-1(2007)).
1232             // the blu ray consortium apparently forgot to read the portion
1233             // of the MPEG spec that says one PID should map to one media
1234             // stream and multiplexed multiple types of audio into one PID
1235             // using the extended stream identifier of the PES header to
1236             // distinguish them. So we have to check if that's happening and
1237             // if so tell the runtime what esid we want.
1238             if ( st2codec[stype].kind == A && stype == 0x83 &&
1239                  stream->ts_format_id[1 + aud_pid_index] == TS_FORMAT_ID_AC3 )
1240             {
1241                 // This is an interleaved TrueHD/AC-3 stream and the esid of
1242                 // the AC-3 is 0x76
1243                 stream->ts_multiplexed[1 + aud_pid_index] = 0x76;
1244                 stype = 0x81;
1245                 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1246             }
1247             if ( st2codec[stype].kind == A && stype == 0x86 )
1248             {
1249                 // This is an interleaved DTS-HD/DTS stream and the esid of
1250                 // the DTS is 0x71
1251                 stream->ts_multiplexed[1 + aud_pid_index] = 0x71;
1252                 stype = 0x82;
1253                 stream->ts_stream_type[1 + aud_pid_index] = 0x82;
1254             }
1255         }
1256         else if ((buf[3] & 0xe0) == 0xc0)
1257         {
1258             // 0xC0 - 0xCF are the normal containers for ISO-standard
1259             // media (mpeg2 audio and mpeg4 AAC).
1260             if ( st2codec[stype].kind == U )
1261             {
1262                 // XXX assume unknown stream types are MPEG audio
1263                 stype = 0x03;
1264                 stream->ts_stream_type[1 + aud_pid_index] = 0x03;
1265             }
1266         }
1267         else
1268         {
1269             stype = 0;
1270         }
1271     }
1272     // if we found an audio stream type & HB has a codec that can decode it
1273     // finish configuring the audio so we'll add it to the title's list.
1274     if ( st2codec[stype].kind == A && st2codec[stype].codec )
1275     {
1276         audio->id = 1 + aud_pid_index;
1277         audio->config.in.codec = st2codec[stype].codec;
1278         audio->config.in.codec_param = st2codec[stype].codec_param;
1279                 set_audio_description( audio,
1280                   lang_for_code( stream->a52_info[aud_pid_index].lang_code ) );
1281         hb_log("transport stream pid 0x%x (type 0x%x) is %s audio id 0x%x",
1282                stream->ts_audio_pids[aud_pid_index],
1283                stype, st2codec[stype].name, audio->id);
1284     }
1285     else
1286     {
1287         if ( buf )
1288         {
1289             hb_log("transport stream pid 0x%x (type 0x%x, substream 0x%x) "
1290                     "isn't audio", stream->ts_audio_pids[aud_pid_index],
1291                     stream->ts_stream_type[1 + aud_pid_index], buf[3]);
1292         }
1293         else
1294         {
1295             hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1296                     stream->ts_audio_pids[aud_pid_index],
1297                     stream->ts_stream_type[1 + aud_pid_index]);
1298         }
1299         }
1300     fseeko(stream->file_handle, cur_pos, SEEK_SET);
1301     return audio;
1302 }
1303
1304 static void add_audio_to_title(hb_title_t *title, int id)
1305 {
1306     hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1307
1308     audio->id = id;
1309     switch ( id >> 12 )
1310     {
1311         case 0x0:
1312             audio->config.in.codec = HB_ACODEC_MPGA;
1313             hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1314             break;
1315         case 0x2:
1316             // type 2 is a DVD subtitle stream - just ignore it */
1317             free( audio );
1318             return;
1319         case 0x8:
1320             audio->config.in.codec = HB_ACODEC_AC3;
1321             hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1322             break;
1323         case 0xa:
1324             audio->config.in.codec = HB_ACODEC_LPCM;
1325             hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1326             break;
1327         default:
1328             hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1329             free( audio );
1330             return;
1331
1332     }
1333     set_audio_description( audio, lang_for_code( 0 ) );
1334     hb_list_add( title->list_audio, audio );
1335 }
1336
1337 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1338 {
1339     off_t cur_pos = ftello(stream->file_handle);
1340     hb_buffer_t *buf  = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1341     hb_list_t *list = hb_list_init();
1342     // how many blocks we read while searching for audio streams
1343     int blksleft = 4096;
1344     // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1345     // so we use a bitmap to keep track of the ones we've already seen.
1346     // Bit 'i' of smap is set if we've already added the audio for
1347     // audio substream id 'i' to the title's audio list.
1348     uint32_t smap = 0;
1349
1350     // start looking 20% into the file since there's occasionally no
1351     // audio at the beginning (particularly for vobs).
1352     hb_stream_seek(stream, 0.2f);
1353
1354     while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1355     {
1356         hb_buffer_t *es;
1357
1358         // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1359         hb_demux_ps( buf, list, 0 );
1360
1361         while ( ( es = hb_list_item( list, 0 ) ) )
1362         {
1363             hb_list_rem( list, es );
1364             if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1365             {
1366                 // this PES contains some kind of audio - get the substream id
1367                 // and check if we've seen it already.
1368                 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1369                 if ( (smap & (1 << ssid)) == 0 )
1370                 {
1371                     // we haven't seen this stream before - add it to the
1372                     // title's list of audio streams.
1373                     smap |= (1 << ssid);
1374                     add_audio_to_title(title, es->id);
1375                 }
1376             }
1377             hb_buffer_close( &es );
1378         }
1379     }
1380     hb_list_empty( &list );
1381     hb_buffer_close(&buf);
1382     fseeko(stream->file_handle, cur_pos, SEEK_SET);
1383 }
1384
1385 /***********************************************************************
1386  * hb_ts_stream_init
1387  ***********************************************************************
1388  *
1389  **********************************************************************/
1390
1391 static void hb_ts_stream_init(hb_stream_t *stream)
1392 {
1393         int i;
1394
1395         for (i=0; i < kMaxNumberDecodeStreams; i++)
1396         {
1397                 stream->ts_streamcont[i] = -1;
1398         }
1399         stream->ts_video_pids[0] = -1;
1400     for ( i = 0; i < stream->ts_number_audio_pids; i++ )
1401     {
1402         stream-> ts_audio_pids[i] = -1;
1403     }
1404
1405     stream->ts_packet = malloc( stream->packetsize );
1406
1407         // Find the audio and video pids in the stream
1408         hb_ts_stream_find_pids(stream);
1409
1410         for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1411         {
1412         // demuxing buffer for TS to PS conversion
1413                 stream->ts_buf[i] = hb_buffer_init(stream->packetsize);
1414                 stream->ts_buf[i]->size = 0;
1415         }
1416 }
1417
1418 #define MAX_HOLE 208*80
1419
1420 static off_t align_to_next_packet(hb_stream_t *stream)
1421 {
1422     uint8_t buf[MAX_HOLE];
1423         off_t pos = 0;
1424     off_t start = ftello(stream->file_handle);
1425
1426     if ( start >= stream->packetsize ) {
1427         start -= stream->packetsize;
1428         fseeko(stream->file_handle, start, SEEK_SET);
1429     }
1430
1431     if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1432         {
1433         const uint8_t *bp = buf;
1434         int i;
1435
1436         for ( i = sizeof(buf); --i >= 0; ++bp )
1437         {
1438             if ( have_ts_sync( bp, stream->packetsize ) )
1439             {
1440                 break;
1441             }
1442         }
1443         if ( i >= 0 )
1444         {
1445             pos = ( bp - buf ) - stream->packetsize + 188;
1446             if ( pos < 0 )
1447                 pos = 0;
1448         }
1449         }
1450     fseeko(stream->file_handle, start+pos, SEEK_SET);
1451         return pos;
1452 }
1453
1454
1455 typedef struct {
1456     uint8_t *buf;
1457     uint32_t val;
1458     int pos;
1459 } bitbuf_t;
1460
1461 static const unsigned int bitmask[] = {
1462         0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1463         0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1464         0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1465         0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1466
1467 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1468 {
1469         bb->pos = 0;
1470         bb->buf = buf;
1471         bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1472               (bb->buf[2] << 8) | bb->buf[3];
1473         if (clear)
1474                 memset(bb->buf, 0, bufsize);
1475 }
1476
1477 static inline int buf_size(bitbuf_t *bb)
1478 {
1479         return bb->pos >> 3;
1480 }
1481
1482 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1483 {
1484         unsigned int val;
1485         int left = 32 - (bb->pos & 31);
1486
1487         if (bits < left)
1488         {
1489                 val = (bb->val >> (left - bits)) & bitmask[bits];
1490                 bb->pos += bits;
1491         }
1492         else
1493         {
1494                 val = (bb->val & bitmask[left]) << (bits - left);
1495                 bb->pos += left;
1496                 bits -= left;
1497
1498                 int pos = bb->pos >> 3;
1499                 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1500
1501                 if (bits > 0)
1502                 {
1503                         val |= (bb->val >> (32 - bits)) & bitmask[bits];
1504                         bb->pos += bits;
1505                 }
1506         }
1507
1508         return val;
1509 }
1510
1511 // extract what useful information we can from the elementary stream
1512 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1513 // Descriptors with info we don't currently use are ignored.
1514 // The descriptor list & descriptor item formats are defined in
1515 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1516 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1517                                        const uint8_t *dp, uint8_t dlen)
1518 {
1519     const uint8_t *ep = dp + dlen;
1520
1521     while (dp < ep)
1522     {
1523         switch (dp[0])
1524         {
1525             case 5:    // Registration descriptor
1526                 stream->ts_format_id[esindx] = (dp[2] << 24) | (dp[3] << 16) |
1527                                                (dp[4] << 8)  | dp[5];
1528                 break;
1529
1530             case 10:    // ISO_639_language descriptor
1531                 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1532                 break;
1533
1534             default:
1535                 break;
1536         }
1537         dp += dp[1] + 2;
1538     }
1539 }
1540
1541 static const char *stream_type_name (uint8_t stream_type)
1542 {
1543     return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
1544 }
1545
1546 int decode_program_map(hb_stream_t* stream)
1547 {
1548     bitbuf_t bb;
1549         set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1550
1551     get_bits(&bb, 8);  // table_id
1552     get_bits(&bb, 4);
1553     unsigned int section_length = get_bits(&bb, 12);
1554     stream->pmt_info.section_length = section_length;
1555
1556     unsigned int program_number = get_bits(&bb, 16);
1557     stream->pmt_info.program_number = program_number;
1558     get_bits(&bb, 2);
1559     get_bits(&bb, 5);  // version_number
1560     get_bits(&bb, 1);
1561     get_bits(&bb, 8);  // section_number
1562     get_bits(&bb, 8);  // last_section_number
1563     get_bits(&bb, 3);
1564     unsigned int PCR_PID = get_bits(&bb, 13);
1565     stream->pmt_info.PCR_PID = PCR_PID;
1566     get_bits(&bb, 4);
1567     unsigned int program_info_length = get_bits(&bb, 12);
1568     stream->pmt_info.program_info_length = program_info_length;
1569
1570         int i=0;
1571         unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
1572         for (i = 0; i < program_info_length; i++)
1573         {
1574           descriptor_buf[i] = get_bits(&bb, 8);
1575         }
1576
1577         int cur_pos =  9 /* data after the section length field*/ + program_info_length;
1578         int done_reading_stream_types = 0;
1579         while (!done_reading_stream_types)
1580     {
1581         unsigned char stream_type = get_bits(&bb, 8);
1582         get_bits(&bb, 3);
1583         unsigned int elementary_PID = get_bits(&bb, 13);
1584         get_bits(&bb, 4);
1585         unsigned int ES_info_length = get_bits(&bb, 12);
1586
1587         int i=0;
1588         unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1589         for (i=0; i < ES_info_length; i++)
1590         {
1591             ES_info_buf[i] = get_bits(&bb, 8);
1592         }
1593
1594
1595         if ( index_of_pid( elementary_PID, stream ) < 0 )
1596         {
1597             // already have this pid - do nothing
1598         }
1599         if (stream->ts_number_video_pids == 0 && st2codec[stream_type].kind == V )
1600         {
1601             stream->ts_video_pids[0] = elementary_PID;
1602             stream->ts_stream_type[0] = stream_type;
1603             stream->ts_number_video_pids = 1;
1604         }
1605         else
1606         {
1607             // Defined audio stream types are 0x81 for AC-3/A52 audio and 0x03
1608             // for mpeg audio. But content producers seem to use other
1609             // values (0x04 and 0x06 have both been observed) so at this point
1610             // we say everything that isn't a video pid is audio then at the end
1611             // of hb_stream_title_scan we'll figure out which are really audio
1612             // by looking at the PES headers.
1613             i = stream->ts_number_audio_pids;
1614             if (i < kMaxNumberAudioPIDS)
1615             {
1616                 stream->ts_audio_pids[i] = elementary_PID;
1617                 stream->ts_stream_type[1 + i] = stream_type;
1618                 if (ES_info_length > 0)
1619                 {
1620                     decode_element_descriptors(stream, i, ES_info_buf,
1621                                                ES_info_length);
1622                 }
1623                 ++stream->ts_number_audio_pids;
1624             }
1625         }
1626
1627         cur_pos += 5 /* stream header */ + ES_info_length;
1628
1629         free(ES_info_buf);
1630
1631         if (cur_pos >= section_length - 4 /* stop before the CRC */)
1632         done_reading_stream_types = 1;
1633     }
1634
1635         free(descriptor_buf);
1636         return 1;
1637 }
1638
1639 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
1640 {
1641     // Get adaption header info
1642     int adapt_len = 0;
1643     int adaption = (buf[3] & 0x30) >> 4;
1644     if (adaption == 0)
1645             return 0;
1646     else if (adaption == 0x2)
1647             adapt_len = 184;
1648     else if (adaption == 0x3)
1649             adapt_len = buf[4] + 1;
1650     if (adapt_len > 184)
1651             return 0;
1652
1653     // Get payload start indicator
1654     int start;
1655     start = (buf[1] & 0x40) != 0;
1656
1657     // Get pointer length - only valid in packets with a start flag
1658     int pointer_len = 0;
1659
1660         if (start)
1661         {
1662                 pointer_len = buf[4 + adapt_len] + 1;
1663                 stream->pmt_info.tablepos = 0;
1664         }
1665         // Get Continuity Counter
1666         int continuity_counter = buf[3] & 0x0f;
1667         if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1668         {
1669                 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1670                 return 0;
1671         }
1672         stream->pmt_info.current_continuity_counter = continuity_counter;
1673         stream->pmt_info.reading |= start;
1674
1675     // Add the payload for this packet to the current buffer
1676         int amount_to_copy = 184 - adapt_len - pointer_len;
1677     if (stream->pmt_info.reading && (amount_to_copy > 0))
1678     {
1679                         stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1680
1681             memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1682             stream->pmt_info.tablepos += amount_to_copy;
1683     }
1684     if (stream->pmt_info.tablepos > 3)
1685     {
1686         // We have enough to check the section length
1687         int length;
1688         length = ((stream->pmt_info.tablebuf[1] << 8) + 
1689                   stream->pmt_info.tablebuf[2]) & 0xFFF;
1690         if (stream->pmt_info.tablepos > length + 1)
1691         {
1692             // We just finished a bunch of packets - parse the program map details
1693             int decode_ok = 0;
1694             if (stream->pmt_info.tablebuf[0] == 0x02)
1695                 decode_ok = decode_program_map(stream);
1696             free(stream->pmt_info.tablebuf);
1697             stream->pmt_info.tablebuf = NULL;
1698             stream->pmt_info.tablepos = 0;
1699             stream->pmt_info.reading = 0;
1700             if (decode_ok)
1701                 return decode_ok;
1702         }
1703
1704     }
1705
1706     return 0;
1707 }
1708
1709 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
1710 {
1711     unsigned char tablebuf[1024];
1712     unsigned int tablepos = 0;
1713
1714     int reading = 0;
1715
1716
1717     // Get adaption header info
1718     int adapt_len = 0;
1719     int adaption = (buf[3] & 0x30) >> 4;
1720     if (adaption == 0)
1721             return 0;
1722     else if (adaption == 0x2)
1723             adapt_len = 184;
1724     else if (adaption == 0x3)
1725             adapt_len = buf[4] + 1;
1726     if (adapt_len > 184)
1727             return 0;
1728
1729     // Get pointer length
1730     int pointer_len = buf[4 + adapt_len] + 1;
1731
1732     // Get payload start indicator
1733     int start;
1734     start = (buf[1] & 0x40) != 0;
1735
1736     if (start)
1737             reading = 1;
1738
1739     // Add the payload for this packet to the current buffer
1740     if (reading && (184 - adapt_len) > 0)
1741     {
1742             if (tablepos + 184 - adapt_len - pointer_len > 1024)
1743             {
1744                     hb_log("decode_PAT - Bad program section length (> 1024)");
1745                     return 0;
1746             }
1747             memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1748             tablepos += 184 - adapt_len - pointer_len;
1749     }
1750
1751     if (start && reading)
1752     {
1753             memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1754
1755
1756             unsigned int pos = 0;
1757             //while (pos < tablepos)
1758             {
1759                     bitbuf_t bb;
1760                     set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
1761
1762                     unsigned char section_id    = get_bits(&bb, 8);
1763                     get_bits(&bb, 4);
1764                     unsigned int section_len    = get_bits(&bb, 12);
1765                     get_bits(&bb, 16); // transport_id
1766                     get_bits(&bb, 2);
1767                     get_bits(&bb, 5);  // version_num
1768                     get_bits(&bb, 1);  // current_next
1769                     get_bits(&bb, 8);  // section_num
1770                     get_bits(&bb, 8);  // last_section
1771
1772                     switch (section_id)
1773                     {
1774                       case 0x00:
1775                         {
1776                           // Program Association Section
1777                           section_len -= 5;    // Already read transport stream ID, version num, section num, and last section num
1778                           section_len -= 4;   // Ignore the CRC
1779                           int curr_pos = 0;
1780                                                   stream->ts_number_pat_entries = 0;
1781                           while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
1782                           {
1783                             unsigned int pkt_program_num = get_bits(&bb, 16);
1784                                                         stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
1785
1786                             get_bits(&bb, 3);  // Reserved
1787                             if (pkt_program_num == 0)
1788                             {
1789                               get_bits(&bb, 13); // pkt_network_id
1790                             }
1791                             else
1792                             {
1793                               unsigned int pkt_program_map_PID = get_bits(&bb, 13);
1794                                 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
1795                             }
1796                             curr_pos += 4;
1797                                                         stream->ts_number_pat_entries++;
1798                           }
1799                         }
1800                         break;
1801                       case 0xC7:
1802                             {
1803                                     break;
1804                             }
1805                       case 0xC8:
1806                             {
1807                                     break;
1808                             }
1809                     }
1810
1811                     pos += 3 + section_len;
1812             }
1813
1814             tablepos = 0;
1815     }
1816     return 1;
1817 }
1818
1819 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1820 {
1821         // align to first packet
1822     align_to_next_packet(stream);
1823
1824         // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1825         // to find the program map PID and then decode that to get the list of audio and video PIDs
1826
1827         for (;;)
1828         {
1829         const uint8_t *buf = next_packet( stream );
1830
1831         if ( buf == NULL )
1832         {
1833                         hb_log("hb_ts_stream_find_pids - end of file");
1834                         break;
1835                 }
1836
1837                 // Get pid
1838                 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1839
1840         if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
1841                 {
1842                   decode_PAT(buf, stream);
1843                   continue;
1844                 }
1845
1846                 int pat_index = 0;
1847                 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
1848                 {
1849                         // There are some streams where the PAT table has multiple entries as if their are
1850                         // multiple programs in the same transport stream, and yet there's actually only one
1851                         // program really in the stream. This seems to be true for transport streams that
1852                         // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
1853                         // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
1854                         // but the EyeTV is only recording a single (selected) program number and not rewriting the
1855                         // PAT info on export to match what's actually on the stream.
1856                         // Until we have a way of handling multiple programs per transport stream elegantly we'll match
1857                         // on the first pat entry for which we find a matching program map PID.  The ideal solution would
1858                         // be to build a title choice popup from the PAT program number details and then select from
1859                         // their - but right now the API's not capable of that.
1860             if (stream->pat_info[pat_index].program_number != 0 &&
1861                 pid == stream->pat_info[pat_index].program_map_PID)
1862                         {
1863                           if (build_program_map(buf, stream) > 0)
1864                                 break;
1865                         }
1866                 }
1867                 // Keep going  until we have a complete set of PIDs
1868                 if ((stream->ts_number_video_pids > 0) && (stream->ts_number_audio_pids > 0))
1869                   break;
1870         }
1871     // XXX - until we figure out how to handle VC1 just bail when we find it so
1872     // that ffmpeg will claim the input stream.
1873     if ( stream->ts_stream_type[0] == 0xea )
1874     {
1875         stream->ts_number_video_pids = 0;
1876         stream->ts_number_audio_pids = 0;
1877         return;
1878     }
1879
1880         hb_log("hb_ts_stream_find_pids - found the following PIDS");
1881         hb_log("    Video PIDS : ");
1882     int i;
1883         for (i=0; i < stream->ts_number_video_pids; i++)
1884         {
1885         hb_log( "      0x%x type %s (0x%x)", 
1886                 stream->ts_video_pids[i],
1887                 stream_type_name(stream->ts_stream_type[i]),
1888                 stream->ts_stream_type[i]);
1889         }
1890         hb_log("    Audio PIDS : ");
1891         for (i = 0; i < stream->ts_number_audio_pids; i++)
1892         {
1893         hb_log( "      0x%x type %s (0x%x)", 
1894                 stream->ts_audio_pids[i],
1895                 stream_type_name(stream->ts_stream_type[i+1]),
1896                 stream->ts_stream_type[i+1] );
1897         }
1898  }
1899
1900
1901 static void fwrite64( hb_stream_t *stream, void *buf, int len )
1902 {
1903     int pos;
1904
1905     pos = stream->fwrite_buf->size;
1906     if ( pos + len > stream->fwrite_buf->alloc )
1907     {
1908         int size = MAX(stream->fwrite_buf->alloc * 2, pos + len);
1909         hb_buffer_realloc(stream->fwrite_buf, size);
1910     }
1911     memcpy( &(stream->fwrite_buf->data[pos]), buf, len );
1912     stream->fwrite_buf->size += len;
1913 }
1914
1915 // convert a PES PTS or DTS to an int64
1916 static int64_t pes_timestamp( const uint8_t *pes )
1917 {
1918     int64_t ts = ( (uint64_t)(pes[0] & 0xe ) << 29 );
1919     ts |= ( pes[1] << 22 ) | ( ( pes[2] >> 1 ) << 15 ) |
1920           ( pes[3] << 7 ) | ( pes[4] >> 1 );
1921     return ts;
1922 }
1923
1924 static void generate_output_data(hb_stream_t *stream, int curstream)
1925 {
1926     hb_buffer_t *buf = stream->fwrite_buf;
1927     uint8_t *tdat = stream->ts_buf[curstream]->data;
1928
1929     buf->id = curstream;
1930
1931     // check if this packet was referenced to an older pcr and if that
1932     // pcr was significantly different than the one we're using now.
1933     // (the reason for the uint cast on the pcr difference is that the
1934     // difference is significant if it advanced by more than 200ms or if
1935     // it went backwards by any amount. The negative numbers look like huge
1936     // unsigned ints so the cast allows both conditions to be checked at once.
1937     int bufpcr = stream->ts_buf[curstream]->cur;
1938     int curpcr = stream->ts_pcr_out;
1939     if ( bufpcr && bufpcr < curpcr &&
1940          (uint64_t)(stream->ts_pcrhist[curpcr & 3] - stream->ts_pcrhist[bufpcr & 3]) > 200*90LL )
1941     {
1942         // we've sent up a new pcr but have a packet referenced to an
1943         // old pcr and the difference was enough to trigger a discontinuity
1944         // correction. smash the timestamps or we'll mess up the correction.
1945         buf->start = -1;
1946         buf->renderOffset = -1;
1947     }
1948     else
1949     {
1950         if ( stream->ts_pcr_out != stream->ts_pcr_in )
1951         {
1952             // we have a new pcr
1953             stream->ts_pcr_out = stream->ts_pcr_in;
1954             buf->stop = stream->ts_pcr;
1955             stream->ts_pcrhist[stream->ts_pcr_out & 3] = stream->ts_pcr;
1956         }
1957         else
1958         {
1959             buf->stop = -1;
1960         }
1961
1962         // put the PTS & possible DTS into 'start' & 'renderOffset' then strip
1963         // off the PES header.
1964         if ( tdat[7] & 0xc0 )
1965         {
1966             buf->start = pes_timestamp( tdat + 9 );
1967             buf->renderOffset = ( tdat[7] & 0x40 )? pes_timestamp( tdat + 14 ) :
1968                                                     buf->start;
1969         }
1970         else
1971         {
1972             buf->start = -1;
1973             buf->renderOffset = -1;
1974         }
1975     }
1976     int hlen = tdat[8] + 9;
1977
1978     fwrite64( stream,  tdat + hlen, stream->ts_pos[curstream] - hlen );
1979
1980     stream->ts_pos[curstream] = 0;
1981     stream->ts_buf[curstream]->size = 0;
1982 }
1983
1984 static int isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
1985 {
1986     // For mpeg2: look for a gop start or i-frame picture start
1987     // for h.264: look for idr nal type or a slice header for an i-frame
1988     // for vc1:   ???
1989     int i;
1990     uint32_t strid = 0;
1991
1992
1993     if ( stream->ts_stream_type[0] <= 2 )
1994     {
1995         // This section of the code handles MPEG-1 and MPEG-2 video streams
1996         for (i = 13 + adapt_len; i < 188; i++)
1997         {
1998             strid = (strid << 8) | buf[i];
1999             if ( ( strid >> 8 ) == 1 )
2000             {
2001                 // we found a start code
2002                 uint8_t id = strid;
2003                 switch ( id )
2004                 {
2005                     case 0xB8: // group_start_code (GOP header)
2006                     case 0xB3: // sequence_header code
2007                         return 1;
2008
2009                     case 0x00: // picture_start_code
2010                         // picture_header, let's see if it's an I-frame
2011                         if (i<185)
2012                         {
2013                             // check if picture_coding_type == 1
2014                             if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
2015                             {
2016                                 // found an I-frame picture
2017                                 return 1;
2018                             }
2019                         }
2020                         break;
2021                 }
2022             }
2023         }
2024         // didn't find an I-frame
2025         return 0;
2026     }
2027     if ( stream->ts_stream_type[0] == 0x1b )
2028     {
2029         // we have an h.264 stream 
2030         for (i = 13 + adapt_len; i < 188; i++)
2031         {
2032             strid = (strid << 8) | buf[i];
2033             if ( ( strid >> 8 ) == 1 )
2034             {
2035                 // we found a start code - remove the ref_idc from the nal type
2036                 uint8_t nal_type = strid & 0x1f;
2037                 if ( nal_type == 0x05 )
2038                     // h.264 IDR picture start
2039                     return 1;
2040
2041                 if ( stream->packetsize == 192 )
2042                 {
2043                     // m2ts files have idr frames so keep looking for one
2044                     continue;
2045                 }
2046
2047                 // h.264 in ts files (ATSC or DVB video) often seem to be
2048                 // missing IDR frames so look for at least an I
2049                 if ( nal_type == 0x01 )
2050                 {
2051                     // h.264 slice: has to be start MB 0 & type I (2, 4, 7 or 9)
2052                     uint8_t id = buf[i+1];
2053                     if ( ( id >> 4 ) == 0x0b || ( id >> 2 ) == 0x25 ||
2054                          id == 0x88 || id == 0x8a )
2055                     {
2056                         return 1;
2057                     }
2058                 }
2059             }
2060         }
2061         // didn't find an I-frame
2062         return 0;
2063     }
2064
2065     // we don't understand the stream type so just say "yes" otherwise
2066     // we'll discard all the video.
2067     return 1;
2068 }
2069
2070 static void hb_ts_stream_append_pkt(hb_stream_t *stream, int idx, const uint8_t *buf, int len)
2071 {
2072     if (stream->ts_pos[idx] + len > stream->ts_buf[idx]->alloc)
2073     {
2074         int size;
2075
2076         size = MAX(stream->ts_buf[idx]->alloc * 2, stream->ts_pos[idx] + len);
2077         hb_buffer_realloc(stream->ts_buf[idx], size);
2078     }
2079     memcpy(stream->ts_buf[idx]->data + stream->ts_pos[idx], buf, len);
2080     stream->ts_pos[idx] += len;
2081     stream->ts_buf[idx]->size += len;
2082 }
2083
2084 /***********************************************************************
2085  * hb_ts_stream_decode
2086  ***********************************************************************
2087  *
2088  **********************************************************************/
2089 static int hb_ts_stream_decode( hb_stream_t *stream, hb_buffer_t *obuf )
2090 {
2091     /*
2092      * stash the output buffer pointer in our stream so we don't have to
2093      * pass it & its original value to everything we call.
2094      */
2095     obuf->size = 0;
2096     stream->fwrite_buf = obuf;
2097
2098         // spin until we get a packet of data from some stream or hit eof
2099         while ( 1 )
2100         {
2101         int curstream;
2102
2103         const uint8_t *buf = next_packet(stream);
2104         if ( buf == NULL )
2105         {
2106             // end of file - we didn't finish filling our ps write buffer
2107             // so just discard the remainder (the partial buffer is useless)
2108             hb_log("hb_ts_stream_decode - eof");
2109             return 0;
2110                 }
2111
2112         /* This next section validates the packet */
2113
2114                 // Get pid and use it to find stream state.
2115                 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
2116         if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
2117             continue;
2118
2119                 // Get error
2120                 int errorbit = (buf[1] & 0x80) != 0;
2121                 if (errorbit)
2122                 {
2123                         ts_err( stream, curstream,  "packet error bit set");
2124                         continue;
2125                 }
2126
2127                 // Get adaption header info
2128                 int adaption = (buf[3] & 0x30) >> 4;
2129                 int adapt_len = 0;
2130                 if (adaption == 0)
2131                 {
2132                         ts_err( stream, curstream,  "adaptation code 0");
2133                         continue;
2134                 }
2135                 else if (adaption == 0x2)
2136                         adapt_len = 184;
2137                 else if (adaption == 0x3)
2138                 {
2139                         adapt_len = buf[4] + 1;
2140                         if (adapt_len > 184)
2141                         {
2142                                 ts_err( stream, curstream,  "invalid adapt len %d", adapt_len);
2143                 continue;
2144                         }
2145                 }
2146
2147         if ( adapt_len > 0 )
2148         {
2149             if ( buf[5] & 0x40 )
2150             {
2151                 // found a random access point
2152             }
2153             // if there's an adaptation header & PCR_flag is set
2154             // get the PCR (Program Clock Reference)
2155             if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
2156             {
2157                 stream->ts_pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
2158                                  ( (uint64_t)buf[7] << (33 - 16) ) |
2159                                  ( (uint64_t)buf[8] << (33 - 24) ) |
2160                                  ( (uint64_t)buf[9] << (33 - 32) ) |
2161                                  ( buf[10] >> 7 );
2162                 ++stream->ts_pcr_in;
2163                 stream->ts_found_pcr = 1;
2164             }
2165         }
2166
2167         // If we don't have a pcr yet, the right thing to do here would
2168         // be a 'continue' so we don't process anything until we have a
2169         // clock reference. Unfortunately the HD Home Run appears to null
2170         // out the pcr field of some streams so we keep going & substitute
2171         // the video stream dts for the pcr when there's no pcr.
2172
2173                 // Get continuity
2174         // Continuity only increments for adaption values of 0x3 or 0x01
2175         // and is not checked for start packets.
2176
2177                 int start = (buf[1] & 0x40) != 0;
2178
2179         if ( (adaption & 0x01) != 0 )
2180                 {
2181             int continuity = (buf[3] & 0xF);
2182             if ( continuity == stream->ts_streamcont[curstream] )
2183             {
2184                 // we got a duplicate packet (usually used to introduce
2185                 // a PCR when one is needed). The only thing that can
2186                 // change in the dup is the PCR which we grabbed above
2187                 // so ignore the rest.
2188                 continue;
2189             }
2190             if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2191                  !stream->ts_skipbad[curstream] &&
2192                  (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2193                         {
2194                                 ts_err( stream, curstream,  "continuity error: got %d expected %d",
2195                         (int)continuity,
2196                         (stream->ts_streamcont[curstream] + 1) & 0xf );
2197                 stream->ts_streamcont[curstream] = continuity;
2198                                 continue;
2199                         }
2200                         stream->ts_streamcont[curstream] = continuity;
2201                 }
2202
2203         /* If we get here the packet is valid - process its data */
2204
2205         if ( start )
2206         {
2207             // Found a random access point (now we can start a frame/audio packet..)
2208
2209             if ( stream->need_keyframe )
2210             {
2211                 // we're looking for the first video frame because we're
2212                 // doing random access during 'scan'
2213                 if (curstream != 0 || !isIframe( stream, buf, adapt_len ) )
2214                 {
2215                     // not the video stream or didn't find an I frame
2216                     continue;
2217                 }
2218                 stream->need_keyframe = 0;
2219             }
2220
2221                         // If we were skipping a bad packet, start fresh on this new PES packet..
2222                         if (stream->ts_skipbad[curstream] == 1)
2223                         {
2224                                 stream->ts_skipbad[curstream] = 0;
2225                         }
2226
2227                         if ( curstream == 0 )
2228             {
2229                 ++stream->frames;
2230
2231                 // if we don't have a pcr yet use the dts from this frame
2232                 if ( !stream->ts_found_pcr )
2233                 {
2234                     // PES must begin with an mpeg start code & contain
2235                     // a DTS or PTS.
2236                     const uint8_t *pes = buf + adapt_len + 4;
2237                     if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2238                          ( pes[7] >> 6 ) == 0 )
2239                     {
2240                         continue;
2241                     }
2242                     // if we have a dts use it otherwise use the pts
2243                     stream->ts_pcr = pes_timestamp( pes + ( pes[7] & 0x40? 14 : 9 ) );
2244                     ++stream->ts_pcr_in;
2245                 }
2246             }
2247
2248             // if this is a multiplexed stream make sure this is the
2249             // substream we want.
2250             if ( stream->ts_multiplexed[curstream] )
2251             {
2252                 // PES must begin with an mpeg start code & contain
2253                 // a DTS or PTS.
2254                 const uint8_t *pes = buf + adapt_len + 4;
2255                 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2256                      pes[3] != 0xfd )
2257                 {
2258                     stream->ts_skipbad[curstream] = 1;
2259                     continue;
2260                 }
2261                 // the last byte of the header is the extension id. see if
2262                 // it's the one we want.
2263                 if ( pes[pes[8]+8] != stream->ts_multiplexed[curstream] )
2264                 {
2265                     stream->ts_skipbad[curstream] = 1;
2266                     continue;
2267                 }
2268             }
2269
2270             // If we have some data already on this stream, turn it into
2271             // a program stream packet. Then add the payload for this
2272             // packet to the current pid's buffer.
2273             if ( stream->ts_pos[curstream] )
2274             {
2275                 // we have to ship the old packet before updating the pcr
2276                 // since the packet we've been accumulating is referenced
2277                 // to the old pcr.
2278                 generate_output_data(stream, curstream);
2279
2280                 // remember the pcr that was in effect when we started
2281                 // this packet.
2282                 stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2283                 hb_ts_stream_append_pkt(stream, curstream, buf + 4 + adapt_len,
2284                                         184 - adapt_len);
2285                 return 1;
2286             }
2287             // remember the pcr that was in effect when we started this packet.
2288             stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2289         }
2290
2291                 // Add the payload for this packet to the current buffer
2292                 if (!stream->ts_skipbad[curstream] && (184 - adapt_len) > 0)
2293                 {
2294             hb_ts_stream_append_pkt(stream, curstream, buf + 4 + adapt_len,
2295                                     184 - adapt_len);
2296             // see if we've hit the end of this PES packet
2297             const uint8_t *pes = stream->ts_buf[curstream]->data;
2298             int len = ( pes[4] << 8 ) + pes[5] + 6;
2299             if ( len > 6 && stream->ts_pos[curstream] == len &&
2300                  pes[0] == 0x00 && pes[1] == 0x00 && pes[2] == 0x01 )
2301             {
2302                 generate_output_data(stream, curstream);
2303                 return 1;
2304             }
2305                 }
2306         }
2307 }
2308
2309 static void hb_ts_stream_reset(hb_stream_t *stream)
2310 {
2311         int i;
2312
2313         for (i=0; i < kMaxNumberDecodeStreams; i++)
2314         {
2315                 stream->ts_pos[i] = 0;
2316                 stream->ts_skipbad[i] = 1;
2317                 stream->ts_streamcont[i] = -1;
2318         }
2319
2320     stream->need_keyframe = 0;
2321
2322     stream->ts_found_pcr = 0;
2323     stream->ts_pcr_out = 0;
2324     stream->ts_pcr_in = 0;
2325     stream->ts_pcr = 0;
2326
2327     stream->frames = 0;
2328     stream->errors = 0;
2329     stream->last_error_frame = -10000;
2330     stream->last_error_count = 0;
2331
2332     align_to_next_packet(stream);
2333 }
2334
2335 // ------------------------------------------------------------------
2336 // Support for reading media files via the ffmpeg libraries.
2337
2338 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2339 {
2340     // add a codec to the context here so it will be there when we
2341     // read the first packet.
2342     AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2343     context->workaround_bugs = FF_BUG_AUTODETECT;
2344     context->error_recognition = 1;
2345     context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2346     AVCodec *codec = avcodec_find_decoder( context->codec_id );
2347     avcodec_open( context, codec );
2348 }
2349
2350 // The ffmpeg stream reader / parser shares a lot of state with the 
2351 // decoder via a codec context kept in the AVStream of the reader's
2352 // AVFormatContext. Since decoding is done in a different thread we
2353 // have to somehow pass this codec context to the decoder and we have
2354 // to do it before the first packet is read (so we can't put the info
2355 // in the buf we'll send downstream). Decoders don't have any way to
2356 // get to the stream directly (they're not passed the title or job
2357 // pointers during a scan) so this is a back door for the decoder to
2358 // get the codec context. We just stick the stream pointer in the next
2359 // slot an array of pointers maintained as a circular list then return
2360 // the index into the list combined with the ffmpeg stream index as the
2361 // codec_param that will be passed to the decoder init routine. We make
2362 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2363 // so that we don't have to do a complicated allocator or worry about
2364 // deleting entries on close. 
2365 //
2366 // Entries can only be added to this list during a scan and are never
2367 // deleted so the list access doesn't require locking.
2368 static hb_stream_t **ffmpeg_streams;    // circular list of stream pointers
2369 static int ffmpeg_stream_cur;           // where we put the last stream pointer
2370 #define ffmpeg_sl_bits (10)             // log2 stream list size (in entries)
2371 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2372
2373 // add a stream to the list & return the appropriate codec_param to access it
2374 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2375 {
2376     if ( !ffmpeg_streams )
2377     {
2378         ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2379     }
2380
2381     // the title scan adds all the ffmpeg media streams at once so we
2382     // only add a new entry to our stream list if the stream is different
2383     // than last time.
2384     int slot = ffmpeg_stream_cur;
2385     if ( ffmpeg_streams[slot] != stream )
2386     {
2387         // new stream - put it in the next slot of the stream list
2388         slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2389         ffmpeg_streams[slot] = stream;
2390     }
2391
2392     ffmpeg_add_codec( stream, stream_index );
2393
2394     return ( stream_index << ffmpeg_sl_bits ) | slot;
2395 }
2396
2397 // we're about to open 'title' to convert it - remap the stream associated
2398 // with the video & audio codec params of the title to refer to 'stream'
2399 // (the original scan stream was closed and no longer exists).
2400 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2401 {
2402     // tell ffmpeg we want a pts on every frame it returns
2403     stream->ffmpeg_ic->flags |= AVFMT_FLAG_GENPTS;
2404
2405     // all the video & audio came from the same stream so remapping
2406     // the video's stream slot takes care of everything.
2407     int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2408     ffmpeg_streams[slot] = stream;
2409
2410     // add codecs for all the streams used by the title
2411     ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2412
2413     int i;
2414     hb_audio_t *audio;
2415     for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2416     {
2417         if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2418         {
2419             ffmpeg_add_codec( stream,
2420                               audio->config.in.codec_param >> ffmpeg_sl_bits );
2421         }
2422     }
2423 }
2424
2425 void *hb_ffmpeg_context( int codec_param )
2426 {
2427     int slot = codec_param & (ffmpeg_sl_size - 1);
2428     int stream_index = codec_param >> ffmpeg_sl_bits;
2429     return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2430 }
2431
2432 void *hb_ffmpeg_avstream( int codec_param )
2433 {
2434     int slot = codec_param & (ffmpeg_sl_size - 1);
2435     int stream_index = codec_param >> ffmpeg_sl_bits;
2436     return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2437 }
2438
2439 static AVFormatContext *ffmpeg_deferred_close;
2440
2441 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2442 {
2443     if ( ffmpeg_deferred_close )
2444     {
2445         av_close_input_file( ffmpeg_deferred_close );
2446         ffmpeg_deferred_close = NULL;
2447     }
2448     AVFormatContext *ic;
2449
2450     av_log_set_level( AV_LOG_ERROR );
2451     if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2452     {
2453         return 0;
2454     }
2455     if ( av_find_stream_info( ic ) < 0 )
2456         goto fail;
2457
2458     stream->ffmpeg_ic = ic;
2459     stream->hb_stream_type = ffmpeg;
2460     stream->ffmpeg_pkt = malloc(sizeof(*stream->ffmpeg_pkt));
2461     av_init_packet( stream->ffmpeg_pkt );
2462
2463     if ( title )
2464     {
2465         // we're opening for read. scan passed out codec params that
2466         // indexed its stream so we need to remap them so they point
2467         // to this stream.
2468         ffmpeg_remap_stream( stream, title );
2469         av_log_set_level( AV_LOG_ERROR );
2470     }
2471     else
2472     {
2473         // we're opening for scan. let ffmpeg put some info into the
2474         // log about what we've got.
2475         av_log_set_level( AV_LOG_INFO );
2476         dump_format( ic, 0, stream->path, 0 );
2477         av_log_set_level( AV_LOG_ERROR );
2478
2479         // accept this file if it has at least one video stream we can decode
2480         int i;
2481         for (i = 0; i < ic->nb_streams; ++i )
2482         {
2483             if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2484             {
2485                 break;
2486             }
2487         }
2488         if ( i >= ic->nb_streams )
2489             goto fail;
2490     }
2491     return 1;
2492
2493   fail:
2494     av_close_input_file( ic );
2495     return 0;
2496 }
2497
2498 static void ffmpeg_close( hb_stream_t *d )
2499 {
2500     // XXX since we're sharing the CodecContext with the downstream
2501     // decoder proc we can't close the stream. We need to reference count
2502     // this so we can close it when both are done with their instance but
2503     // for now just defer the close until the next stream open or close.
2504     if ( ffmpeg_deferred_close )
2505     {
2506         av_close_input_file( ffmpeg_deferred_close );
2507     }
2508     ffmpeg_deferred_close = d->ffmpeg_ic;
2509     if ( d->ffmpeg_pkt != NULL )
2510     {
2511         free( d->ffmpeg_pkt );
2512         d->ffmpeg_pkt = NULL;
2513     }
2514 }
2515
2516 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2517 {
2518     AVStream *st = stream->ffmpeg_ic->streams[id];
2519     AVCodecContext *codec = st->codec;
2520
2521     // scan will ignore any audio without a bitrate. Since we've already
2522     // typed the audio in order to determine its codec we set up the audio
2523     // paramters here.
2524     if ( codec->bit_rate || codec->sample_rate )
2525     {
2526         static const int chan2layout[] = {
2527             HB_INPUT_CH_LAYOUT_MONO,  // We should allow no audio really.
2528             HB_INPUT_CH_LAYOUT_MONO,   
2529             HB_INPUT_CH_LAYOUT_STEREO,
2530             HB_INPUT_CH_LAYOUT_2F1R,   
2531             HB_INPUT_CH_LAYOUT_2F2R,
2532             HB_INPUT_CH_LAYOUT_3F2R,   
2533             HB_INPUT_CH_LAYOUT_4F2R,
2534             HB_INPUT_CH_LAYOUT_STEREO, 
2535             HB_INPUT_CH_LAYOUT_STEREO,
2536         };
2537
2538         hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
2539
2540         audio->id = id;
2541         if ( codec->codec_id == CODEC_ID_AC3 )
2542         {
2543             audio->config.in.codec = HB_ACODEC_AC3;
2544         }
2545         else if ( codec->codec_id == CODEC_ID_DTS )
2546         {
2547             audio->config.in.codec = HB_ACODEC_DCA;
2548         }
2549         else
2550         {
2551             audio->config.in.codec = HB_ACODEC_FFMPEG;
2552             audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
2553
2554             audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
2555             audio->config.in.samplerate = codec->sample_rate;
2556             audio->config.in.channel_layout = chan2layout[codec->channels & 7];
2557         }
2558
2559         set_audio_description( audio, lang_for_code2( st->language ) );
2560
2561         hb_list_add( title->list_audio, audio );
2562     }
2563 }
2564
2565 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
2566 {
2567     AVFormatContext *ic = stream->ffmpeg_ic;
2568
2569     // 'Barebones Title'
2570     hb_title_t *title = hb_title_init( stream->path, 0 );
2571     title->index = 1;
2572
2573         // Copy part of the stream path to the title name
2574         char *sep = strrchr(stream->path, '/');
2575         if (sep)
2576                 strcpy(title->name, sep+1);
2577         char *dot_term = strrchr(title->name, '.');
2578         if (dot_term)
2579                 *dot_term = '\0';
2580
2581     uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
2582     title->duration = dur;
2583     dur /= 90000;
2584     title->hours    = dur / 3600;
2585     title->minutes  = ( dur % 3600 ) / 60;
2586     title->seconds  = dur % 60;
2587
2588     // One Chapter
2589     hb_chapter_t * chapter;
2590     chapter = calloc( sizeof( hb_chapter_t ), 1 );
2591     chapter->index = 1;
2592     chapter->duration = title->duration;
2593     chapter->hours = title->hours;
2594     chapter->minutes = title->minutes;
2595     chapter->seconds = title->seconds;
2596     hb_list_add( title->list_chapter, chapter );
2597
2598     // set the title to decode the first video stream in the file
2599     title->demuxer = HB_NULL_DEMUXER;
2600     title->video_codec = 0;
2601     int i;
2602     for (i = 0; i < ic->nb_streams; ++i )
2603     {
2604         if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
2605              avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
2606              title->video_codec == 0 )
2607         {
2608             title->video_id = i;
2609             stream->ffmpeg_video_id = i;
2610
2611             // We have to use the 'internal' avcodec decoder because
2612             // it needs to share the codec context from this video
2613             // stream. The parser internal to av_read_frame
2614             // passes a bunch of state info to the decoder via the context.
2615             title->video_codec = WORK_DECAVCODECVI;
2616             title->video_codec_param = ffmpeg_codec_param( stream, i );
2617         }
2618         else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
2619                   avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
2620         {
2621             add_ffmpeg_audio( title, stream, i );
2622         }
2623     }
2624
2625     title->container_name = strdup( ic->iformat->name );
2626     title->data_rate = ic->bit_rate;
2627
2628     return title;
2629 }
2630
2631 static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
2632 {
2633     if ( pts == AV_NOPTS_VALUE )
2634         return -1;
2635     return (int64_t)( (double)pts * conv_factor );
2636 }
2637
2638 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
2639 {
2640     int err;
2641   again:
2642     if ( ( err = av_read_frame( stream->ffmpeg_ic, stream->ffmpeg_pkt )) < 0 )
2643     {
2644         // XXX the following conditional is to handle avi files that
2645         // use M$ 'packed b-frames' and occasionally have negative
2646         // sizes for the null frames these require.
2647         if ( err != AVERROR_NOMEM || stream->ffmpeg_pkt->size >= 0 )
2648             // eof
2649             return 0;
2650     }
2651     if ( stream->ffmpeg_pkt->size <= 0 )
2652     {
2653         // M$ "invalid and inefficient" packed b-frames require 'null frames'
2654         // following them to preserve the timing (since the packing puts two
2655         // or more frames in what looks like one avi frame). The contents and
2656         // size of these null frames are ignored by the ff_h263_decode_frame
2657         // as long as they're < 20 bytes. We need a positive size so we use
2658         // one byte if we're given a zero or negative size. We don't know
2659         // if the pkt data points anywhere reasonable so we just stick a
2660         // byte of zero in our outbound buf.
2661         buf->size = 1;
2662         *buf->data = 0;
2663     }
2664     else
2665     {
2666         if ( stream->ffmpeg_pkt->size > buf->alloc )
2667         {
2668             // sometimes we get absurd sizes from ffmpeg
2669             if ( stream->ffmpeg_pkt->size >= (1 << 25) )
2670             {
2671                 hb_log( "ffmpeg_read: pkt too big: %d bytes", stream->ffmpeg_pkt->size );
2672                 av_free_packet( stream->ffmpeg_pkt );
2673                 return ffmpeg_read( stream, buf );
2674             }
2675             // need to expand buffer
2676             hb_buffer_realloc( buf, stream->ffmpeg_pkt->size );
2677         }
2678         memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
2679         buf->size = stream->ffmpeg_pkt->size;
2680     }
2681     buf->id = stream->ffmpeg_pkt->stream_index;
2682     if ( buf->id == stream->ffmpeg_video_id )
2683     {
2684         if ( stream->need_keyframe &&
2685              stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->codec_id == 
2686                CODEC_ID_VC1 )
2687         {
2688             // XXX the VC1 codec doesn't seek to key frames so to get previews
2689             // we do it ourselves here. The decoder gets messed up if it
2690             // doesn't get a SEQ header first so we consider that to be a key frame.
2691             uint8_t *pkt = stream->ffmpeg_pkt->data;
2692             if ( pkt[0] || pkt[1] || pkt[2] != 1 || pkt[3] != 0x0f )
2693             {
2694                 goto again;
2695             }
2696             stream->need_keyframe = 0;
2697         }
2698         ++stream->frames;
2699     }
2700
2701     // if we haven't done it already, compute a conversion factor to go
2702     // from the ffmpeg timebase for the stream to HB's 90KHz timebase.
2703     double tsconv = stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index];
2704     if ( ! tsconv )
2705     {
2706         AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index];
2707         tsconv = 90000. * (double)s->time_base.num / (double)s->time_base.den;
2708         stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index] = tsconv;
2709     }
2710
2711     buf->start = av_to_hb_pts( stream->ffmpeg_pkt->pts, tsconv );
2712     buf->renderOffset = av_to_hb_pts( stream->ffmpeg_pkt->dts, tsconv );
2713     if ( buf->renderOffset >= 0 && buf->start == -1 )
2714     {
2715         buf->start = buf->renderOffset;
2716     }
2717     av_free_packet( stream->ffmpeg_pkt );
2718     return 1;
2719 }
2720
2721 static int ffmpeg_seek( hb_stream_t *stream, float frac )
2722 {
2723     AVFormatContext *ic = stream->ffmpeg_ic;
2724     int64_t pos = (double)ic->duration * (double)frac;
2725     if ( pos )
2726     {
2727         av_seek_frame( ic, -1, pos, 0 );
2728         stream->need_keyframe = 1;
2729     }
2730     else
2731     {
2732         av_seek_frame( ic, -1, pos, AVSEEK_FLAG_BACKWARD );
2733     }
2734     return 1;
2735 }