OSDN Git Service

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