OSDN Git Service

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