OSDN Git Service

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