OSDN Git Service

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