OSDN Git Service

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