OSDN Git Service

Added Paul Kendalls ffmpeg AAC-LATM codec. Allows HB to decode AAC-LATM
[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 = 100000; // 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         return &buf[udata];
770     }
771
772     /* didn't find it */
773     return 0;
774 }
775
776 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
777 {
778     hb_buffer_t *buf  = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
779     hb_list_t *list = hb_list_init();
780     // how many blocks we read while searching for a video PES header
781     int blksleft = 1024;
782     uint64_t pts = 0;
783
784     while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
785     {
786         hb_buffer_t *es;
787
788         // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
789         hb_demux_ps( buf, list, 0 );
790
791         while ( ( es = hb_list_item( list, 0 ) ) )
792         {
793             hb_list_rem( list, es );
794             if ( es->id == 0xe0 )
795             {
796                 // this PES contains video - if there's a PTS we're done
797                 // hb_demux_ps left the PTS in buf_es->start.
798                 if ( es->start != ~0 )
799                 {
800                     pts = es->start;
801                     blksleft = 0;
802                     break;
803                 }
804             }
805             hb_buffer_close( &es );
806         }
807     }
808     hb_list_empty( &list );
809     hb_buffer_close(&buf);
810     return pts;
811 }
812
813 /***********************************************************************
814  * hb_stream_duration
815  ***********************************************************************
816  *
817  * Finding stream duration is difficult.  One issue is that the video file
818  * may have chunks from several different program fragments (main feature,
819  * commercials, station id, trailers, etc.) all with their own base pts
820  * value.  We can't find the piece boundaries without reading the entire
821  * file but if we compute a rate based on time stamps from two different
822  * pieces the result will be meaningless.  The second issue is that the
823  * data rate of compressed video normally varies by 5-10x over the length
824  * of the video. This says that we want to compute the rate over relatively
825  * long segments to get a representative average but long segments increase
826  * the likelihood that we'll cross a piece boundary.
827  *
828  * What we do is take time stamp samples at several places in the file
829  * (currently 16) then compute the average rate (i.e., ticks of video per
830  * byte of the file) for all pairs of samples (N^2 rates computed for N
831  * samples). Some of those rates will be absurd because the samples came
832  * from different segments. Some will be way low or high because the
833  * samples came from a low or high motion part of the segment. But given
834  * that we're comparing *all* pairs the majority of the computed rates
835  * should be near the overall average.  So we median filter the computed
836  * rates to pick the most representative value.
837  *
838  **********************************************************************/
839 struct pts_pos {
840     uint64_t pos;   /* file position of this PTS sample */
841     uint64_t pts;   /* PTS from video stream */
842 };
843
844 #define NDURSAMPLES 16
845
846 // get one (position, timestamp) sampple from a transport or program
847 // stream.
848 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
849 {
850     struct pts_pos pp = { 0, 0 };
851
852     if ( stream->hb_stream_type == transport )
853     {
854         const uint8_t *buf;
855         fseeko( stream->file_handle, fpos, SEEK_SET );
856         align_to_next_packet( stream );
857         buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
858         if ( buf == NULL )
859         {
860             hb_log("hb_sample_pts: couldn't find video packet near %llu", fpos);
861             return pp;
862         }
863         if ( ( buf[7] >> 7 ) != 1 )
864         {
865             hb_log("hb_sample_pts: no PTS in video packet near %llu", fpos);
866             return pp;
867         }
868         pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
869                  ( (uint64_t)buf[10] << 22 ) |
870                  ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
871                  ( (uint64_t)buf[12] << 7 ) |
872                  ( (uint64_t)buf[13] >> 1 );
873     }
874     else
875     {
876         // round address down to nearest dvd sector start
877         fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
878         fseeko( stream->file_handle, fpos, SEEK_SET );
879         if ( stream->hb_stream_type == program )
880         {
881             skip_to_next_pack( stream );
882         }
883         pp.pts = hb_ps_stream_getVideoPTS( stream );
884     }
885     pp.pos = ftello(stream->file_handle);
886     return pp;
887 }
888
889 static int dur_compare( const void *a, const void *b )
890 {
891     const double *aval = a, *bval = b;
892     return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
893 }
894
895 // given an array of (position, time) samples, compute a max-likelihood
896 // estimate of the average rate by computing the rate between all pairs
897 // of samples then taking the median of those rates.
898 static double compute_stream_rate( struct pts_pos *pp, int n )
899 {
900     int i, j;
901     double rates[NDURSAMPLES * NDURSAMPLES / 2];
902     double *rp = rates;
903
904     // the following nested loops compute the rates between all pairs.
905     *rp = 0;
906     for ( i = 0; i < n-1; ++i )
907     {
908         // Bias the median filter by not including pairs that are "far"
909         // from one another. This is to handle cases where the file is
910         // made of roughly equal size pieces where a symmetric choice of
911         // pairs results in having the same number of intra-piece &
912         // inter-piece rate estimates. This would mean that the median
913         // could easily fall in the inter-piece part of the data which
914         // would give a bogus estimate. The 'ns' index creates an
915         // asymmetry that favors locality.
916         int ns = i + ( n >> 1 );
917         if ( ns > n )
918             ns = n;
919         for ( j = i+1; j < ns; ++j )
920         {
921             if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
922             {
923                 *rp = ((double)( pp[j].pts - pp[i].pts )) /
924                       ((double)( pp[j].pos - pp[i].pos ));
925                                 ++rp;
926             }
927         }
928     }
929     // now compute and return the median of all the (n*n/2) rates we computed
930     // above.
931     int nrates = rp - rates;
932     qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
933     return rates[nrates >> 1];
934 }
935
936 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
937 {
938     struct pts_pos ptspos[NDURSAMPLES];
939     struct pts_pos *pp = ptspos;
940     int i;
941
942     fseeko(stream->file_handle, 0, SEEK_END);
943     uint64_t fsize = ftello(stream->file_handle);
944     uint64_t fincr = fsize / NDURSAMPLES;
945     uint64_t fpos = fincr / 2;
946     for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
947     {
948         *pp++ = hb_sample_pts(stream, fpos);
949     }
950     uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
951     inTitle->duration = dur;
952     dur /= 90000;
953     inTitle->hours    = dur / 3600;
954     inTitle->minutes  = ( dur % 3600 ) / 60;
955     inTitle->seconds  = dur % 60;
956
957     rewind(stream->file_handle);
958 }
959
960 /***********************************************************************
961  * hb_stream_read
962  ***********************************************************************
963  *
964  **********************************************************************/
965 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
966 {
967         if ( src_stream->hb_stream_type == ffmpeg )
968     {
969         return ffmpeg_read( src_stream, b );
970     }
971     if ( src_stream->hb_stream_type == dvd_program )
972     {
973         size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
974                                 src_stream->file_handle);
975         return (amt_read > 0);
976     }
977     if ( src_stream->hb_stream_type == program )
978     {
979         // a general program stream has arbitrary sized pack's. we're
980         // currently positioned at the start of a pack so read up to but
981         // not including the start of the next, expanding the buffer
982         // as necessary.
983         uint8_t *cp = b->data;
984         uint8_t *ep = cp + b->alloc;
985         uint32_t strt_code = -1;
986         int c;
987
988         // consume the first byte of the initial pack so we don't match on
989         // it in the loop below.
990         if ( ( c = getc( src_stream->file_handle ) ) == EOF )
991             return 0;
992
993         *cp++ = c;
994
995         flockfile( src_stream->file_handle );
996         while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
997         {
998             strt_code = ( strt_code << 8 ) | c;
999             if ( strt_code == 0x000001ba )
1000                 // we found the start of the next pack
1001                 break;
1002             if ( cp >= ep )
1003             {
1004                 // need to expand the buffer
1005                 int curSize = cp - b->data;
1006                 hb_buffer_realloc( b, curSize * 2 );
1007                 cp = b->data + curSize;
1008                 ep = b->data + b->alloc;
1009             }
1010             *cp++ = c;
1011         }
1012         funlockfile( src_stream->file_handle );
1013
1014         // if we didn't terminate on an eof back up so the next read
1015         // starts on the pack boundary.
1016         b->size = cp - b->data;
1017         if ( c != EOF )
1018         {
1019             fseeko( src_stream->file_handle, -4, SEEK_CUR );
1020             b->size -= 4;
1021         }
1022         return 1;
1023     }
1024     return hb_ts_stream_decode( src_stream, b->data );
1025 }
1026
1027 /***********************************************************************
1028  * hb_stream_seek
1029  ***********************************************************************
1030  *
1031  **********************************************************************/
1032 int hb_stream_seek( hb_stream_t * src_stream, float f )
1033 {
1034         if ( src_stream->hb_stream_type == ffmpeg )
1035     {
1036         return ffmpeg_seek( src_stream, f );
1037     }
1038     off_t stream_size, cur_pos, new_pos;
1039     double pos_ratio = f;
1040     cur_pos = ftello( src_stream->file_handle );
1041     fseeko( src_stream->file_handle, 0, SEEK_END );
1042     stream_size = ftello( src_stream->file_handle );
1043     new_pos = (off_t) ((double) (stream_size) * pos_ratio);
1044     new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
1045
1046     int r = fseeko( src_stream->file_handle, new_pos, SEEK_SET );
1047     if (r == -1)
1048     {
1049         fseeko( src_stream->file_handle, cur_pos, SEEK_SET );
1050         return 0;
1051     }
1052
1053     if ( src_stream->hb_stream_type == transport )
1054     {
1055         // We need to drop the current decoder output and move
1056         // forwards to the next transport stream packet.
1057         hb_ts_stream_reset(src_stream);
1058     }
1059     else if ( src_stream->hb_stream_type == program )
1060     {
1061         skip_to_next_pack( src_stream );
1062     }
1063
1064     return 1;
1065 }
1066
1067 static const char* make_upper( const char* s )
1068 {
1069     static char name[8];
1070     char *cp = name;
1071     char *ep = cp + sizeof(name)-1;
1072
1073     while ( *s && cp < ep )
1074     {
1075         *cp++ = islower(*s)? toupper(*s) : *s;
1076         ++s;
1077     }
1078     *cp = 0;
1079     return name;
1080 }
1081
1082 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1083 {
1084     /* XXX
1085      * This is a duplicate of code in dvd.c - it should get factored out
1086      * into a common routine. We probably should only be putting the lang
1087      * code or a lang pointer into the audio config & let the common description
1088      * formatting routine in scan.c do all the stuff below.
1089      */
1090     const char *codec_name;
1091     AVCodecContext *cc;
1092
1093     if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1094          ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1095          avcodec_find_decoder( cc->codec_id ) )
1096     {
1097         codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1098         if ( !strcmp( codec_name, "LIBFAAD" ) )
1099         {
1100             codec_name = "AAC";
1101         }
1102     }
1103     else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1104               avcodec_find_decoder( audio->config.in.codec_param ) )
1105     {
1106         codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1107     }
1108     else
1109     {
1110         codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1111                      audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1112                      audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" : 
1113                      audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" : 
1114                      audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1115                      "Unknown";
1116     }
1117     snprintf( audio->config.lang.description,
1118               sizeof( audio->config.lang.description ), "%s (%s)",
1119               strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1120               codec_name );
1121     snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1122               strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1123     snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1124               "%s", lang->iso639_2);
1125 }
1126
1127 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1128                                                        int aud_pid_index)
1129 {
1130     off_t cur_pos = ftello(stream->file_handle);
1131     hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1132     const uint8_t *buf;
1133
1134     fseeko(stream->file_handle, 0, SEEK_SET);
1135     align_to_next_packet(stream);
1136     buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
1137
1138     /* check that we found a PES header */
1139     uint8_t stype = 0;
1140     if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1141     {
1142         // 0xbd is the normal container for AC3/DCA/PCM/etc. 0xfd indicates an
1143         // extended stream id (ISO 13818-1(2007)). If we cared about the
1144         // real id we'd have to look inside the PES extension to find it.
1145         // But since we remap stream id's when we generate PS packets from
1146         // the TS packets we can just ignore the actual id.
1147         if ( buf[3] == 0xbd || buf[3] == 0xfd )
1148         {
1149             audio->id = 0x80bd | (aud_pid_index << 8);
1150             stype = stream->ts_stream_type[1 + aud_pid_index];
1151             if ( st2codec[stype].kind == U )
1152             {
1153                 // XXX assume unknown stream types are AC-3 (if they're not
1154                 // audio we'll find that out during the scan but if they're
1155                 // some other type of audio we'll end up ignoring them).
1156                 stype = 0x81;
1157                 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1158             }
1159             stream->ts_streamid[1 + aud_pid_index] = 0xbd;
1160         }
1161         else if ((buf[3] & 0xe0) == 0xc0)
1162         {
1163             audio->id = 0xc0 | aud_pid_index;
1164             stype = stream->ts_stream_type[1 + aud_pid_index];
1165             if ( st2codec[stype].kind == U )
1166             {
1167                 // XXX assume unknown stream types are MPEG audio
1168                 stype = 0x03;
1169                 stream->ts_stream_type[1 + aud_pid_index] = 0x03;
1170             }
1171         }
1172     }
1173     // if we found an audio stream type & HB has a codec that can decode it
1174     // finish configuring the audio so we'll add it to the title's list.
1175     if ( st2codec[stype].kind == A && st2codec[stype].codec )
1176     {
1177         stream->ts_streamid[1 + aud_pid_index] = audio->id;
1178         audio->config.in.codec = st2codec[stype].codec;
1179         audio->config.in.codec_param = st2codec[stype].codec_param;
1180                 set_audio_description( audio,
1181                   lang_for_code( stream->a52_info[aud_pid_index].lang_code ) );
1182         hb_log("transport stream pid 0x%x (type 0x%x) is %s audio id 0x%x",
1183                stream->ts_audio_pids[aud_pid_index],
1184                stype, st2codec[stype].name, audio->id);
1185     }
1186     else
1187     {
1188         hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1189                 stream->ts_audio_pids[aud_pid_index],
1190                 stream->ts_stream_type[1 + aud_pid_index]);
1191         }
1192     fseeko(stream->file_handle, cur_pos, SEEK_SET);
1193     return audio;
1194 }
1195
1196 static void add_audio_to_title(hb_title_t *title, int id)
1197 {
1198     hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1199
1200     audio->id = id;
1201     switch ( id >> 12 )
1202     {
1203         case 0x0:
1204             audio->config.in.codec = HB_ACODEC_MPGA;
1205             hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1206             break;
1207         case 0x2:
1208             // type 2 is a DVD subtitle stream - just ignore it */
1209             free( audio );
1210             return;
1211         case 0x8:
1212             audio->config.in.codec = HB_ACODEC_AC3;
1213             hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1214             break;
1215         case 0xa:
1216             audio->config.in.codec = HB_ACODEC_LPCM;
1217             hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1218             break;
1219         default:
1220             hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1221             free( audio );
1222             return;
1223
1224     }
1225     set_audio_description( audio, lang_for_code( 0 ) );
1226     hb_list_add( title->list_audio, audio );
1227 }
1228
1229 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1230 {
1231     off_t cur_pos = ftello(stream->file_handle);
1232     hb_buffer_t *buf  = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1233     hb_list_t *list = hb_list_init();
1234     // how many blocks we read while searching for audio streams
1235     int blksleft = 4096;
1236     // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1237     // so we use a bitmap to keep track of the ones we've already seen.
1238     // Bit 'i' of smap is set if we've already added the audio for
1239     // audio substream id 'i' to the title's audio list.
1240     uint32_t smap = 0;
1241
1242     // start looking 20% into the file since there's occasionally no
1243     // audio at the beginning (particularly for vobs).
1244     hb_stream_seek(stream, 0.2f);
1245
1246     while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1247     {
1248         hb_buffer_t *es;
1249
1250         // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1251         hb_demux_ps( buf, list, 0 );
1252
1253         while ( ( es = hb_list_item( list, 0 ) ) )
1254         {
1255             hb_list_rem( list, es );
1256             if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1257             {
1258                 // this PES contains some kind of audio - get the substream id
1259                 // and check if we've seen it already.
1260                 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1261                 if ( (smap & (1 << ssid)) == 0 )
1262                 {
1263                     // we haven't seen this stream before - add it to the
1264                     // title's list of audio streams.
1265                     smap |= (1 << ssid);
1266                     add_audio_to_title(title, es->id);
1267                 }
1268             }
1269             hb_buffer_close( &es );
1270         }
1271     }
1272     hb_list_empty( &list );
1273     hb_buffer_close(&buf);
1274     fseeko(stream->file_handle, cur_pos, SEEK_SET);
1275 }
1276
1277 /***********************************************************************
1278  * hb_ts_stream_init
1279  ***********************************************************************
1280  *
1281  **********************************************************************/
1282
1283 static void hb_ts_stream_init(hb_stream_t *stream)
1284 {
1285         int i;
1286
1287         for (i=0; i < kMaxNumberDecodeStreams; i++)
1288         {
1289                 stream->ts_streamcont[i] = -1;
1290         }
1291         stream->ts_video_pids[0] = -1;
1292     for ( i = 0; i < stream->ts_number_audio_pids; i++ )
1293     {
1294         stream-> ts_audio_pids[i] = -1;
1295     }
1296
1297     stream->ts_packet = malloc( stream->packetsize );
1298
1299         // Find the audio and video pids in the stream
1300         hb_ts_stream_find_pids(stream);
1301
1302         for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1303         {
1304         // demuxing buffer for TS to PS conversion
1305                 stream->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
1306         }
1307
1308     stream->ts_streamid[0] = 0xE0;              // stream 0 must be video
1309 }
1310
1311 #define MAX_HOLE 208*80
1312
1313 static off_t align_to_next_packet(hb_stream_t *stream)
1314 {
1315     uint8_t buf[MAX_HOLE];
1316         off_t pos = 0;
1317     off_t start = ftello(stream->file_handle);
1318
1319     if ( start >= stream->packetsize ) {
1320         start -= stream->packetsize;
1321         fseeko(stream->file_handle, start, SEEK_SET);
1322     }
1323
1324     if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1325         {
1326         const uint8_t *bp = buf;
1327         int i;
1328
1329         for ( i = sizeof(buf); --i >= 0; ++bp )
1330         {
1331             if ( have_ts_sync( bp, stream->packetsize ) )
1332             {
1333                 break;
1334             }
1335         }
1336         if ( i >= 0 )
1337         {
1338             pos = ( bp - buf ) - stream->packetsize + 188;
1339             if ( pos < 0 )
1340                 pos = 0;
1341         }
1342         }
1343     fseeko(stream->file_handle, start+pos, SEEK_SET);
1344         return pos;
1345 }
1346
1347
1348 typedef struct {
1349     uint8_t *buf;
1350     uint32_t val;
1351     int pos;
1352 } bitbuf_t;
1353
1354 static const unsigned int bitmask[] = {
1355         0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1356         0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1357         0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1358         0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1359
1360 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1361 {
1362         bb->pos = 0;
1363         bb->buf = buf;
1364         bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1365               (bb->buf[2] << 8) | bb->buf[3];
1366         if (clear)
1367                 memset(bb->buf, 0, bufsize);
1368 }
1369
1370 static inline int buf_size(bitbuf_t *bb)
1371 {
1372         return bb->pos >> 3;
1373 }
1374
1375 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1376 {
1377         unsigned int val;
1378         int left = 32 - (bb->pos & 31);
1379
1380         if (bits < left)
1381         {
1382                 val = (bb->val >> (left - bits)) & bitmask[bits];
1383                 bb->pos += bits;
1384         }
1385         else
1386         {
1387                 val = (bb->val & bitmask[left]) << (bits - left);
1388                 bb->pos += left;
1389                 bits -= left;
1390
1391                 int pos = bb->pos >> 3;
1392                 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1393
1394                 if (bits > 0)
1395                 {
1396                         val |= (bb->val >> (32 - bits)) & bitmask[bits];
1397                         bb->pos += bits;
1398                 }
1399         }
1400
1401         return val;
1402 }
1403
1404 // extract what useful information we can from the elementary stream
1405 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1406 // Descriptors with info we don't currently use are ignored.
1407 // The descriptor list & descriptor item formats are defined in
1408 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1409 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1410                                        const uint8_t *dp, uint8_t dlen)
1411 {
1412     const uint8_t *ep = dp + dlen;
1413
1414     while (dp < ep)
1415     {
1416         switch (dp[0])
1417         {
1418             case 10:    // ISO_639_language descriptor
1419                 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1420                 break;
1421
1422             default:
1423                 break;
1424         }
1425         dp += dp[1] + 2;
1426     }
1427 }
1428
1429 static const char *stream_type_name (uint8_t stream_type)
1430 {
1431     return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
1432 }
1433
1434 int decode_program_map(hb_stream_t* stream)
1435 {
1436     bitbuf_t bb;
1437         set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1438
1439     get_bits(&bb, 8);  // table_id
1440     get_bits(&bb, 4);
1441     unsigned int section_length = get_bits(&bb, 12);
1442     stream->pmt_info.section_length = section_length;
1443
1444     unsigned int program_number = get_bits(&bb, 16);
1445     stream->pmt_info.program_number = program_number;
1446     get_bits(&bb, 2);
1447     get_bits(&bb, 5);  // version_number
1448     get_bits(&bb, 1);
1449     get_bits(&bb, 8);  // section_number
1450     get_bits(&bb, 8);  // last_section_number
1451     get_bits(&bb, 3);
1452     unsigned int PCR_PID = get_bits(&bb, 13);
1453     stream->pmt_info.PCR_PID = PCR_PID;
1454     get_bits(&bb, 4);
1455     unsigned int program_info_length = get_bits(&bb, 12);
1456     stream->pmt_info.program_info_length = program_info_length;
1457
1458         int i=0;
1459         unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
1460         for (i = 0; i < program_info_length; i++)
1461         {
1462           descriptor_buf[i] = get_bits(&bb, 8);
1463         }
1464
1465         int cur_pos =  9 /* data after the section length field*/ + program_info_length;
1466         int done_reading_stream_types = 0;
1467         while (!done_reading_stream_types)
1468     {
1469         unsigned char stream_type = get_bits(&bb, 8);
1470         get_bits(&bb, 3);
1471         unsigned int elementary_PID = get_bits(&bb, 13);
1472         get_bits(&bb, 4);
1473         unsigned int ES_info_length = get_bits(&bb, 12);
1474
1475         int i=0;
1476         unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1477         for (i=0; i < ES_info_length; i++)
1478         {
1479             ES_info_buf[i] = get_bits(&bb, 8);
1480         }
1481
1482
1483         if (stream->ts_number_video_pids == 0 && st2codec[stream_type].kind == V )
1484         {
1485             stream->ts_video_pids[0] = elementary_PID;
1486             stream->ts_stream_type[0] = stream_type;
1487             stream->ts_number_video_pids = 1;
1488         }
1489         else
1490         {
1491             // Defined audio stream types are 0x81 for AC-3/A52 audio and 0x03
1492             // for mpeg audio. But content producers seem to use other
1493             // values (0x04 and 0x06 have both been observed) so at this point
1494             // we say everything that isn't a video pid is audio then at the end
1495             // of hb_stream_title_scan we'll figure out which are really audio
1496             // by looking at the PES headers.
1497             i = stream->ts_number_audio_pids;
1498             if (i < kMaxNumberAudioPIDS)
1499             {
1500                 stream->ts_audio_pids[i] = elementary_PID;
1501                 stream->ts_stream_type[1 + i] = stream_type;
1502                 if (ES_info_length > 0)
1503                 {
1504                     decode_element_descriptors(stream, i, ES_info_buf,
1505                                                ES_info_length);
1506                 }
1507                 ++stream->ts_number_audio_pids;
1508             }
1509         }
1510
1511         cur_pos += 5 /* stream header */ + ES_info_length;
1512
1513         free(ES_info_buf);
1514
1515         if (cur_pos >= section_length - 4 /* stop before the CRC */)
1516         done_reading_stream_types = 1;
1517     }
1518
1519         free(descriptor_buf);
1520         return 1;
1521 }
1522
1523 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
1524 {
1525     // Get adaption header info
1526     int adapt_len = 0;
1527     int adaption = (buf[3] & 0x30) >> 4;
1528     if (adaption == 0)
1529             return 0;
1530     else if (adaption == 0x2)
1531             adapt_len = 184;
1532     else if (adaption == 0x3)
1533             adapt_len = buf[4] + 1;
1534     if (adapt_len > 184)
1535             return 0;
1536
1537     // Get payload start indicator
1538     int start;
1539     start = (buf[1] & 0x40) != 0;
1540
1541     // Get pointer length - only valid in packets with a start flag
1542     int pointer_len = 0;
1543         if (start && stream->pmt_info.reading)
1544         {
1545                 // We just finished a bunch of packets - parse the program map details
1546                 int decode_ok = 0;
1547                 if (stream->pmt_info.tablebuf[0] == 0x02)
1548                         decode_ok = decode_program_map(stream);
1549                 free(stream->pmt_info.tablebuf);
1550                 stream->pmt_info.tablebuf = NULL;
1551                 stream->pmt_info.tablepos = 0;
1552         stream->pmt_info.reading = 0;
1553         if (decode_ok)
1554                         return decode_ok;
1555         }
1556
1557         if (start)
1558         {
1559                 pointer_len = buf[4 + adapt_len] + 1;
1560                 stream->pmt_info.tablepos = 0;
1561         }
1562         // Get Continuity Counter
1563         int continuity_counter = buf[3] & 0x0f;
1564         if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1565         {
1566                 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1567                 return 0;
1568         }
1569         stream->pmt_info.current_continuity_counter = continuity_counter;
1570         stream->pmt_info.reading |= start;
1571
1572     // Add the payload for this packet to the current buffer
1573         int amount_to_copy = 184 - adapt_len - pointer_len;
1574     if (stream->pmt_info.reading && (amount_to_copy > 0))
1575     {
1576                         stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1577
1578             memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1579             stream->pmt_info.tablepos += amount_to_copy;
1580     }
1581
1582     return 0;
1583 }
1584
1585 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
1586 {
1587     unsigned char tablebuf[1024];
1588     unsigned int tablepos = 0;
1589
1590     int reading = 0;
1591
1592
1593     // Get adaption header info
1594     int adapt_len = 0;
1595     int adaption = (buf[3] & 0x30) >> 4;
1596     if (adaption == 0)
1597             return 0;
1598     else if (adaption == 0x2)
1599             adapt_len = 184;
1600     else if (adaption == 0x3)
1601             adapt_len = buf[4] + 1;
1602     if (adapt_len > 184)
1603             return 0;
1604
1605     // Get pointer length
1606     int pointer_len = buf[4 + adapt_len] + 1;
1607
1608     // Get payload start indicator
1609     int start;
1610     start = (buf[1] & 0x40) != 0;
1611
1612     if (start)
1613             reading = 1;
1614
1615     // Add the payload for this packet to the current buffer
1616     if (reading && (184 - adapt_len) > 0)
1617     {
1618             if (tablepos + 184 - adapt_len - pointer_len > 1024)
1619             {
1620                     hb_log("decode_PAT - Bad program section length (> 1024)");
1621                     return 0;
1622             }
1623             memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1624             tablepos += 184 - adapt_len - pointer_len;
1625     }
1626
1627     if (start && reading)
1628     {
1629             memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1630
1631
1632             unsigned int pos = 0;
1633             //while (pos < tablepos)
1634             {
1635                     bitbuf_t bb;
1636                     set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
1637
1638                     unsigned char section_id    = get_bits(&bb, 8);
1639                     get_bits(&bb, 4);
1640                     unsigned int section_len    = get_bits(&bb, 12);
1641                     get_bits(&bb, 16); // transport_id
1642                     get_bits(&bb, 2);
1643                     get_bits(&bb, 5);  // version_num
1644                     get_bits(&bb, 1);  // current_next
1645                     get_bits(&bb, 8);  // section_num
1646                     get_bits(&bb, 8);  // last_section
1647
1648                     switch (section_id)
1649                     {
1650                       case 0x00:
1651                         {
1652                           // Program Association Section
1653                           section_len -= 5;    // Already read transport stream ID, version num, section num, and last section num
1654                           section_len -= 4;   // Ignore the CRC
1655                           int curr_pos = 0;
1656                                                   stream->ts_number_pat_entries = 0;
1657                           while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
1658                           {
1659                             unsigned int pkt_program_num = get_bits(&bb, 16);
1660                                                         stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
1661
1662                             get_bits(&bb, 3);  // Reserved
1663                             if (pkt_program_num == 0)
1664                             {
1665                               get_bits(&bb, 13); // pkt_network_id
1666                             }
1667                             else
1668                             {
1669                               unsigned int pkt_program_map_PID = get_bits(&bb, 13);
1670                                 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
1671                             }
1672                             curr_pos += 4;
1673                                                         stream->ts_number_pat_entries++;
1674                           }
1675                         }
1676                         break;
1677                       case 0xC7:
1678                             {
1679                                     break;
1680                             }
1681                       case 0xC8:
1682                             {
1683                                     break;
1684                             }
1685                     }
1686
1687                     pos += 3 + section_len;
1688             }
1689
1690             tablepos = 0;
1691     }
1692     return 1;
1693 }
1694
1695 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1696 {
1697         // align to first packet
1698     align_to_next_packet(stream);
1699
1700         // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1701         // to find the program map PID and then decode that to get the list of audio and video PIDs
1702
1703         for (;;)
1704         {
1705         const uint8_t *buf = next_packet( stream );
1706         if ( buf == NULL )
1707         {
1708                         hb_log("hb_ts_stream_find_pids - end of file");
1709                         break;
1710                 }
1711
1712                 // Get pid
1713                 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1714
1715         if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
1716                 {
1717                   decode_PAT(buf, stream);
1718                   continue;
1719                 }
1720
1721                 int pat_index = 0;
1722                 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
1723                 {
1724                         // There are some streams where the PAT table has multiple entries as if their are
1725                         // multiple programs in the same transport stream, and yet there's actually only one
1726                         // program really in the stream. This seems to be true for transport streams that
1727                         // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
1728                         // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
1729                         // but the EyeTV is only recording a single (selected) program number and not rewriting the
1730                         // PAT info on export to match what's actually on the stream.
1731                         // Until we have a way of handling multiple programs per transport stream elegantly we'll match
1732                         // on the first pat entry for which we find a matching program map PID.  The ideal solution would
1733                         // be to build a title choice popup from the PAT program number details and then select from
1734                         // their - but right now the API's not capable of that.
1735                         if (pid == stream->pat_info[pat_index].program_map_PID)
1736                         {
1737                           if (build_program_map(buf, stream) > 0)
1738                                 break;
1739                         }
1740                 }
1741                 // Keep going  until we have a complete set of PIDs
1742                 if ((stream->ts_number_video_pids > 0) && (stream->ts_number_audio_pids > 0))
1743                   break;
1744         }
1745
1746         hb_log("hb_ts_stream_find_pids - found the following PIDS");
1747         hb_log("    Video PIDS : ");
1748     int i;
1749         for (i=0; i < stream->ts_number_video_pids; i++)
1750         {
1751         hb_log( "      0x%x type %s (0x%x)", 
1752                 stream->ts_video_pids[i],
1753                 stream_type_name(stream->ts_stream_type[i]),
1754                 stream->ts_stream_type[i]);
1755         }
1756         hb_log("    Audio PIDS : ");
1757         for (i = 0; i < stream->ts_number_audio_pids; i++)
1758         {
1759         hb_log( "      0x%x type %s (0x%x)", 
1760                 stream->ts_audio_pids[i],
1761                 stream_type_name(stream->ts_stream_type[i+1]),
1762                 stream->ts_stream_type[i+1] );
1763         }
1764  }
1765
1766
1767 static void fwrite64( hb_stream_t *stream, void *buf, int size )
1768 {
1769     if ( (stream->fwrite_buf - stream->fwrite_buf_orig) + size > 2048 )
1770     {
1771         hb_log( "steam fwrite64 buffer overflow - writing %d with %d already",
1772                 size, stream->fwrite_buf - stream->fwrite_buf_orig );
1773         return;
1774     }
1775     memcpy( stream->fwrite_buf, buf, size );
1776     stream->fwrite_buf += size;
1777 }
1778
1779 static void write_pack(hb_stream_t* stream, uint64_t time, int stuffing)
1780 {
1781         uint8_t buf[24];
1782
1783     buf[0] = 0x00;      // pack id
1784     buf[1] = 0x00;
1785     buf[2] = 0x01;
1786     buf[3] = 0xba;
1787
1788     buf[4] = 0x44 |     // SCR
1789              ( ( ( time >> 30 ) & 7 ) << 3 ) |
1790              ( ( time >> 28 ) & 3 );
1791     buf[5] = time >> 20;
1792     buf[6] = 0x04 |
1793              ( ( ( time >> 15 ) & 0x1f ) << 3 ) |
1794              ( ( time >> 13 ) & 3 );
1795     buf[7] = time >> 5;
1796     buf[8] = 0x04 | ( time << 3 );
1797
1798     buf[9] = 0x01;      // SCR extension
1799
1800     buf[10] = 384000 >> (22 - 8);     // program mux rate
1801     buf[11] = (uint8_t)( 384000 >> (22 - 16) );
1802     buf[12] = (uint8_t)( 384000 << 2 ) | 0x03;
1803
1804     buf[13] = 0xf8 | stuffing;
1805
1806     int i;
1807     for (i = 0; i < stuffing; ++i )
1808         buf[14+i] = 0xff;
1809
1810         fwrite64(stream, buf, 14 + stuffing );
1811 }
1812
1813 static void pad_buffer(hb_stream_t* stream, int pad)
1814 {
1815         pad -= 6;
1816
1817         uint8_t buf[6];
1818         buf[0] = 0;
1819     buf[1] = 0;
1820     buf[2] = 0;
1821     buf[3] = 0xbe;
1822         buf[4] = pad >> 8;
1823     buf[5] = pad;
1824
1825         fwrite64(stream, buf, 6);
1826
1827         buf[0] = 0xff;
1828     while ( --pad >= 0 )
1829     {
1830                 fwrite64(stream, buf, 1);
1831         }
1832 }
1833
1834 static void make_pes_header(hb_stream_t* stream, int len, uint8_t streamid)
1835 {
1836         uint8_t buf[9];
1837
1838     memset(buf, 0, sizeof(buf) );
1839     buf[2] = 1;
1840     buf[3] = streamid;
1841     buf[4] = ( len + 3 ) >> 8;
1842     buf[5] = len + 3;
1843     buf[6] = 0x88;
1844
1845     fwrite64(stream, buf, 9);
1846 }
1847
1848 static void generate_output_data(hb_stream_t *stream, int curstream)
1849 {
1850     uint8_t *tdat = stream->ts_buf[curstream];
1851     int len;
1852
1853     // we always ship a PACK header plus all the data in our demux buf.
1854     // AC3 audio also always needs its substream header.
1855     len = 14 + stream->ts_pos[curstream];
1856     if ( stream->ts_stream_type[curstream] == 0x81)
1857     {
1858         len += 4;
1859     }
1860
1861     if ( ! stream->ts_start[curstream] )
1862     {
1863         // we're in the middle of a chunk of PES data - we need to add
1864         // a 'continuation' PES header after the PACK header.
1865         len += 9;
1866     }
1867
1868     // Write out pack header
1869     // If we don't have 2048 bytes we need to pad to 2048. We can
1870     // add a padding frame after our data but we need at least 7
1871     // bytes of space to do it (6 bytes of header & 1 of pad). If
1872     // we have fewer than 7 bytes left we need to fill the excess
1873     // space with stuffing bytes added to the pack header.
1874     int stuffing = 0;
1875     if ( len > HB_DVD_READ_BUFFER_SIZE )
1876     {
1877         hb_log( "stream ts length botch %d", len );
1878     }
1879     if ( HB_DVD_READ_BUFFER_SIZE - len < 8)
1880     {
1881         stuffing = HB_DVD_READ_BUFFER_SIZE - len;
1882     }
1883     write_pack(stream, stream->ts_nextpcr, stuffing );
1884     stream->ts_nextpcr += 10;
1885
1886     if ( stream->ts_start[curstream] )
1887     {
1888         // Start frames already have a PES header but we have modify it
1889         // to map from TS PID to PS stream id. Also, if the stream is AC3
1890         // audio we have to insert an AC3 stream header between the end of
1891         // the PES header and the start of the stream data.
1892
1893         stream->ts_start[curstream] = 0;
1894         tdat[3] = stream->ts_streamid[curstream];
1895
1896         uint16_t plen = stream->ts_pos[curstream] - 6;
1897         if ( stream->ts_stream_type[curstream] == 0x81)
1898         {
1899             // We have to add an AC3 header in front of the data. Add its
1900             // size to the PES packet length.
1901             plen += 4;
1902             tdat[4] = plen >> 8;
1903             tdat[5] = plen;
1904
1905             // Write out the PES header
1906             int hdrsize = 9 + tdat[8];
1907             fwrite64(stream, tdat, hdrsize);
1908
1909             // add a four byte DVD ac3 stream header
1910             uint8_t ac3_substream_id[4];
1911             int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1912             ac3_substream_id[0] = 0x80 | ssid;  // substream id
1913             ac3_substream_id[1] = 0x01;         // number of sync words
1914             ac3_substream_id[2] = 0x00;         // first offset (16 bits)
1915             ac3_substream_id[3] = 0x02;
1916             fwrite64(stream, ac3_substream_id, 4);
1917
1918             // add the rest of the data
1919             fwrite64(stream, tdat + hdrsize, stream->ts_pos[curstream] - hdrsize);
1920         }
1921         else
1922         {
1923             // not audio - don't need to modify the stream so write what we've got
1924             tdat[4] = plen >> 8;
1925             tdat[5] = plen;
1926             fwrite64( stream,  tdat, stream->ts_pos[curstream] );
1927         }
1928     }
1929     else
1930     {
1931         // data without a PES start header needs a simple 'continuation'
1932         // PES header. AC3 audio also needs its substream header.
1933         if ( stream->ts_stream_type[curstream] != 0x81)
1934         {
1935             make_pes_header(stream, stream->ts_pos[curstream],
1936                             stream->ts_streamid[curstream]);
1937         }
1938         else
1939         {
1940             make_pes_header(stream, stream->ts_pos[curstream] + 4,
1941                             stream->ts_streamid[curstream]);
1942
1943             // add a four byte DVD ac3 stream header
1944             uint8_t ac3_substream_id[4];
1945             int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1946             ac3_substream_id[0] = 0x80 | ssid;  // substream id
1947             ac3_substream_id[1] = 0x01;         // number of sync words
1948             ac3_substream_id[2] = 0x00;         // first offset (16 bits)
1949             ac3_substream_id[3] = 0x02;
1950             fwrite64(stream, ac3_substream_id, 4);
1951         }
1952         fwrite64( stream, tdat, stream->ts_pos[curstream] );
1953     }
1954
1955     // Write padding
1956     int left = HB_DVD_READ_BUFFER_SIZE - len;
1957     if ( left >= 8 )
1958     {
1959         pad_buffer(stream, left);
1960     }
1961
1962     stream->ts_pos[curstream] = 0;
1963 }
1964
1965 static int isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
1966 {
1967     // For mpeg2: look for a gop start or i-frame picture start
1968     // for h.264: look for idr nal type or a slice header for an i-frame
1969     // for vc1:   ???
1970     int i;
1971     uint32_t strid = 0;
1972
1973
1974     if ( stream->ts_stream_type[0] <= 2 )
1975     {
1976         // This section of the code handles MPEG-1 and MPEG-2 video streams
1977         for (i = 13 + adapt_len; i < 188; i++)
1978         {
1979             strid = (strid << 8) | buf[i];
1980             if ( ( strid >> 8 ) == 1 )
1981             {
1982                 // we found a start code
1983                 uint8_t id = strid;
1984                 switch ( id )
1985                 {
1986                     case 0xB8: // group_start_code (GOP header)
1987                     case 0xB3: // sequence_header code
1988                         return 1;
1989
1990                     case 0x00: // picture_start_code
1991                         // picture_header, let's see if it's an I-frame
1992                         if (i<185)
1993                         {
1994                             // check if picture_coding_type == 1
1995                             if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
1996                             {
1997                                 // found an I-frame picture
1998                                 return 1;
1999                             }
2000                         }
2001                         break;
2002                 }
2003             }
2004         }
2005         // didn't find an I-frame
2006         return 0;
2007     }
2008     if ( stream->ts_stream_type[0] == 0x1b )
2009     {
2010         // we have an h.264 stream 
2011         for (i = 13 + adapt_len; i < 188; i++)
2012         {
2013             strid = (strid << 8) | buf[i];
2014             if ( ( strid >> 8 ) == 1 )
2015             {
2016                 // we found a start code - remove the ref_idc from the nal type
2017                 uint8_t nal_type = strid & 0x1f;
2018                 if ( nal_type == 0x05 )
2019                     // h.264 IDR picture start
2020                     return 1;
2021
2022                 if ( nal_type == 0x01 )
2023                 {
2024                     // h.264 slice: has to be start MB 0 & type I (2, 4, 7 or 9)
2025                     uint8_t id = buf[i+1];
2026                     if ( ( id >> 4 ) == 0x0b || ( id >> 2 ) == 0x25 ||
2027                          id == 0x88 || id == 0x8a )
2028                     {
2029                         return 1;
2030                     }
2031                 }
2032             }
2033         }
2034         // didn't find an I-frame
2035         return 0;
2036     }
2037
2038     // we don't understand the stream type so just say "yes" otherwise
2039     // we'll discard all the video.
2040     return 1;
2041 }
2042
2043 /***********************************************************************
2044  * hb_ts_stream_decode
2045  ***********************************************************************
2046  *
2047  **********************************************************************/
2048 static int hb_ts_stream_decode( hb_stream_t *stream, uint8_t *obuf )
2049 {
2050     /*
2051      * stash the output buffer pointer in our stream so we don't have to
2052      * pass it & its original value to everything we call.
2053      */
2054     stream->fwrite_buf = obuf;
2055     stream->fwrite_buf_orig = obuf;
2056
2057         // spin until we get a packet of data from some stream or hit eof
2058         while ( 1 )
2059         {
2060         int64_t pcr = stream->ts_lastpcr;
2061         int curstream;
2062
2063         const uint8_t *buf = next_packet(stream);
2064         if ( buf == NULL )
2065         {
2066             // end of file - we didn't finish filling our ps write buffer
2067             // so just discard the remainder (the partial buffer is useless)
2068             hb_log("hb_ts_stream_decode - eof");
2069             return 0;
2070                 }
2071
2072         /* This next section validates the packet */
2073
2074                 // Get pid and use it to find stream state.
2075                 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
2076         if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
2077             continue;
2078
2079                 // Get error
2080                 int errorbit = (buf[1] & 0x80) != 0;
2081                 if (errorbit)
2082                 {
2083                         ts_err( stream, curstream,  "packet error bit set");
2084                         continue;
2085                 }
2086
2087                 // Get adaption header info
2088                 int adaption = (buf[3] & 0x30) >> 4;
2089                 int adapt_len = 0;
2090                 if (adaption == 0)
2091                 {
2092                         ts_err( stream, curstream,  "adaptation code 0");
2093                         continue;
2094                 }
2095                 else if (adaption == 0x2)
2096                         adapt_len = 184;
2097                 else if (adaption == 0x3)
2098                 {
2099                         adapt_len = buf[4] + 1;
2100                         if (adapt_len > 184)
2101                         {
2102                                 ts_err( stream, curstream,  "invalid adapt len %d", adapt_len);
2103                 continue;
2104                         }
2105                 }
2106
2107         // if there's an adaptation header & PCR_flag is set
2108         // get the PCR (Program Clock Reference)
2109         if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
2110         {
2111             pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
2112                   ( (uint64_t)buf[7] << (33 - 16) ) |
2113                   ( (uint64_t)buf[8] << (33 - 24) ) |
2114                   ( (uint64_t)buf[9] << (33 - 32) ) |
2115                   ( buf[10] >> 7 );
2116             stream->ts_nextpcr = pcr;
2117
2118             // remember the pcr across calls to this routine
2119             stream->ts_lastpcr = pcr;
2120         }
2121
2122                 if ( pcr == -1 )
2123                 {
2124             // don't accumulate data until we get a pcr
2125                     continue;
2126                 }
2127
2128                 // Get continuity
2129         // Continuity only increments for adaption values of 0x3 or 0x01
2130         // and is not checked for start packets.
2131
2132                 int start = (buf[1] & 0x40) != 0;
2133
2134         if ( (adaption & 0x01) != 0 )
2135                 {
2136             int continuity = (buf[3] & 0xF);
2137             if ( continuity == stream->ts_streamcont[curstream] )
2138             {
2139                 // we got a duplicate packet (usually used to introduce
2140                 // a PCR when one is needed). The only thing that can
2141                 // change in the dup is the PCR which we grabbed above
2142                 // so ignore the rest.
2143                 continue;
2144             }
2145             if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2146                  (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2147                         {
2148                                 ts_err( stream, curstream,  "continuity error: got %d expected %d",
2149                         (int)continuity,
2150                         (stream->ts_streamcont[curstream] + 1) & 0xf );
2151                 stream->ts_streamcont[curstream] = continuity;
2152                                 continue;
2153                         }
2154                         stream->ts_streamcont[curstream] = continuity;
2155                 }
2156
2157         /* If we get here the packet is valid - process its data */
2158
2159         if ( start )
2160         {
2161             // Found a random access point (now we can start a frame/audio packet..)
2162
2163                         // If we were skipping a bad packet, start fresh on this new PES packet..
2164                         if (stream->ts_skipbad[curstream] == 1)
2165                         {
2166                 // video skips to an iframe after a bad packet to minimize
2167                 // screen corruption
2168                 if ( curstream == 0 && !isIframe( stream, buf, adapt_len ) )
2169                 {
2170                     continue;
2171                 }
2172                                 stream->ts_skipbad[curstream] = 0;
2173                         }
2174
2175                         // If we don't have video yet, check to see if this is an
2176             // i_frame (group of picture start)
2177                         if ( curstream == 0 )
2178             {
2179                 if ( !stream->ts_foundfirst[0] )
2180                 {
2181                     if ( !isIframe( stream, buf, adapt_len ) )
2182                     {
2183                         // didn't find an I frame
2184                         continue;
2185                     }
2186                     stream->ts_foundfirst[0] = 1;
2187                 }
2188                 ++stream->frames;
2189             }
2190                         else if ( ! stream->ts_foundfirst[curstream] )
2191             {
2192                 // start other streams only after first video frame found.
2193                 if ( ! stream->ts_foundfirst[0] )
2194                 {
2195                     continue;
2196                 }
2197                 stream->ts_foundfirst[curstream] = 1;
2198                         }
2199
2200             // If we have some data already on this stream, turn it into
2201             // a program stream packet. Then add the payload for this
2202             // packet to the current pid's buffer.
2203             if ( stream->ts_pos[curstream] )
2204             {
2205                 generate_output_data(stream, curstream);
2206                 stream->ts_start[curstream] = 1;
2207                 memcpy(stream->ts_buf[curstream],
2208                        buf + 4 + adapt_len, 184 - adapt_len);
2209                 stream->ts_pos[curstream] = 184 - adapt_len;
2210                 return 1;
2211             }
2212             stream->ts_start[curstream] = 1;
2213         }
2214
2215                 // Add the payload for this packet to the current buffer
2216                 if (!stream->ts_skipbad[curstream] && stream->ts_foundfirst[curstream] &&
2217             (184 - adapt_len) > 0)
2218                 {
2219                         memcpy(stream->ts_buf[curstream] + stream->ts_pos[curstream],
2220                    buf + 4 + adapt_len, 184 - adapt_len);
2221                         stream->ts_pos[curstream] += 184 - adapt_len;
2222
2223             // if the next TS packet could possibly overflow our 2K output buffer
2224             // we need to generate a packet now. Overflow would be 184 bytes of
2225             // data + the 9 byte PES hdr + the 14 byte PACK hdr = 211 bytes.
2226             if ( stream->ts_pos[curstream] >= (HB_DVD_READ_BUFFER_SIZE - 216) )
2227             {
2228                 // we have enough data to make a PS packet
2229                 generate_output_data(stream, curstream);
2230                 return 1;
2231             }
2232                 }
2233         }
2234 }
2235
2236 static void hb_ts_stream_reset(hb_stream_t *stream)
2237 {
2238         int i;
2239
2240         for (i=0; i < kMaxNumberDecodeStreams; i++)
2241         {
2242                 stream->ts_pos[i] = 0;
2243                 stream->ts_foundfirst[i] = 0;
2244                 stream->ts_skipbad[i] = 0;
2245                 stream->ts_streamcont[i] = -1;
2246                 stream->ts_start[i] = 0;
2247         }
2248
2249     stream->ts_lastpcr = -1;
2250     stream->ts_nextpcr = -1;
2251
2252     stream->frames = 0;
2253     stream->errors = 0;
2254     stream->last_error_frame = -10000;
2255     stream->last_error_count = 0;
2256
2257     align_to_next_packet(stream);
2258 }
2259
2260 // ------------------------------------------------------------------
2261 // Support for reading media files via the ffmpeg libraries.
2262
2263 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2264 {
2265     // add a codec to the context here so it will be there when we
2266     // read the first packet.
2267     AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2268     context->workaround_bugs = FF_BUG_AUTODETECT;
2269     context->error_resilience = 1;
2270     context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2271     AVCodec *codec = avcodec_find_decoder( context->codec_id );
2272     avcodec_open( context, codec );
2273 }
2274
2275 // The ffmpeg stream reader / parser shares a lot of state with the 
2276 // decoder via a codec context kept in the AVStream of the reader's
2277 // AVFormatContext. Since decoding is done in a different thread we
2278 // have to somehow pass this codec context to the decoder and we have
2279 // to do it before the first packet is read (so we can't put the info
2280 // in the buf we'll send downstream). Decoders don't have any way to
2281 // get to the stream directly (they're not passed the title or job
2282 // pointers during a scan) so this is a back door for the decoder to
2283 // get the codec context. We just stick the stream pointer in the next
2284 // slot an array of pointers maintained as a circular list then return
2285 // the index into the list combined with the ffmpeg stream index as the
2286 // codec_param that will be passed to the decoder init routine. We make
2287 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2288 // so that we don't have to do a complicated allocator or worry about
2289 // deleting entries on close. 
2290 //
2291 // Entries can only be added to this list during a scan and are never
2292 // deleted so the list access doesn't require locking.
2293 static hb_stream_t **ffmpeg_streams;    // circular list of stream pointers
2294 static int ffmpeg_stream_cur;           // where we put the last stream pointer
2295 #define ffmpeg_sl_bits (10)             // log2 stream list size (in entries)
2296 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2297
2298 // add a stream to the list & return the appropriate codec_param to access it
2299 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2300 {
2301     if ( !ffmpeg_streams )
2302     {
2303         ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2304     }
2305
2306     // the title scan adds all the ffmpeg media streams at once so we
2307     // only add a new entry to our stream list if the stream is different
2308     // than last time.
2309     int slot = ffmpeg_stream_cur;
2310     if ( ffmpeg_streams[slot] != stream )
2311     {
2312         // new stream - put it in the next slot of the stream list
2313         slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2314         ffmpeg_streams[slot] = stream;
2315     }
2316
2317     ffmpeg_add_codec( stream, stream_index );
2318
2319     return ( stream_index << ffmpeg_sl_bits ) | slot;
2320 }
2321
2322 // we're about to open 'title' to convert it - remap the stream associated
2323 // with the video & audio codec params of the title to refer to 'stream'
2324 // (the original scan stream was closed and no longer exists).
2325 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2326 {
2327     // all the video & audio came from the same stream so remapping
2328     // the video's stream slot takes care of everything.
2329     int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2330     ffmpeg_streams[slot] = stream;
2331
2332     // add codecs for all the streams used by the title
2333     ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2334
2335     int i;
2336     hb_audio_t *audio;
2337     for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2338     {
2339         if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2340         {
2341             ffmpeg_add_codec( stream,
2342                               audio->config.in.codec_param >> ffmpeg_sl_bits );
2343         }
2344     }
2345 }
2346
2347 void *hb_ffmpeg_context( int codec_param )
2348 {
2349     int slot = codec_param & (ffmpeg_sl_size - 1);
2350     int stream_index = codec_param >> ffmpeg_sl_bits;
2351     return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2352 }
2353
2354 void *hb_ffmpeg_avstream( int codec_param )
2355 {
2356     int slot = codec_param & (ffmpeg_sl_size - 1);
2357     int stream_index = codec_param >> ffmpeg_sl_bits;
2358     return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2359 }
2360
2361 static AVFormatContext *ffmpeg_deferred_close;
2362
2363 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2364 {
2365     if ( ffmpeg_deferred_close )
2366     {
2367         av_close_input_file( ffmpeg_deferred_close );
2368         ffmpeg_deferred_close = NULL;
2369     }
2370     AVFormatContext *ic;
2371
2372     av_log_set_level( AV_LOG_ERROR );
2373     if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2374     {
2375         return 0;
2376     }
2377     if ( av_find_stream_info( ic ) < 0 )
2378         goto fail;
2379
2380     stream->ffmpeg_ic = ic;
2381     stream->hb_stream_type = ffmpeg;
2382
2383     if ( title )
2384     {
2385         // we're opening for read. scan passed out codec params that
2386         // indexed its stream so we need to remap them so they point
2387         // to this stream.
2388         ffmpeg_remap_stream( stream, title );
2389         ffmpeg_seek( stream, 0. );
2390         av_log_set_level( AV_LOG_ERROR );
2391     }
2392     else
2393     {
2394         // we're opening for scan. let ffmpeg put some info into the
2395         // log about what we've got.
2396         av_log_set_level( AV_LOG_INFO );
2397         dump_format( ic, 0, stream->path, 0 );
2398         av_log_set_level( AV_LOG_ERROR );
2399
2400         // accept this file if it has at least one video stream we can decode
2401         int i;
2402         for (i = 0; i < ic->nb_streams; ++i )
2403         {
2404             if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2405             {
2406                 break;
2407             }
2408         }
2409         if ( i >= ic->nb_streams )
2410             goto fail;
2411     }
2412     return 1;
2413
2414   fail:
2415     av_close_input_file( ic );
2416     return 0;
2417 }
2418
2419 static void ffmpeg_close( hb_stream_t *d )
2420 {
2421     // XXX since we're sharing the CodecContext with the downstream
2422     // decoder proc we can't close the stream. We need to reference count
2423     // this so we can close it when both are done with their instance but
2424     // for now just defer the close until the next stream open or close.
2425     if ( ffmpeg_deferred_close )
2426     {
2427         av_close_input_file( ffmpeg_deferred_close );
2428     }
2429     ffmpeg_deferred_close = d->ffmpeg_ic;
2430 }
2431
2432 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2433 {
2434     AVStream *st = stream->ffmpeg_ic->streams[id];
2435     AVCodecContext *codec = st->codec;
2436
2437     // scan will ignore any audio without a bitrate. Since we've already
2438     // typed the audio in order to determine its codec we set up the audio
2439     // paramters here.
2440     if ( codec->bit_rate || codec->sample_rate )
2441     {
2442         static const int chan2layout[] = {
2443             HB_INPUT_CH_LAYOUT_MONO,  // We should allow no audio really.
2444             HB_INPUT_CH_LAYOUT_MONO,   
2445             HB_INPUT_CH_LAYOUT_STEREO,
2446             HB_INPUT_CH_LAYOUT_2F1R,   
2447             HB_INPUT_CH_LAYOUT_2F2R,
2448             HB_INPUT_CH_LAYOUT_3F2R,   
2449             HB_INPUT_CH_LAYOUT_4F2R,
2450             HB_INPUT_CH_LAYOUT_STEREO, 
2451             HB_INPUT_CH_LAYOUT_STEREO,
2452         };
2453
2454         hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
2455
2456         audio->id = id;
2457         if ( codec->codec_id == CODEC_ID_AC3 )
2458         {
2459             audio->config.in.codec = HB_ACODEC_AC3;
2460         }
2461         else
2462         {
2463             audio->config.in.codec = HB_ACODEC_FFMPEG;
2464             audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
2465
2466             audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
2467             audio->config.in.samplerate = codec->sample_rate;
2468             audio->config.in.channel_layout = chan2layout[codec->channels & 7];
2469         }
2470
2471         set_audio_description( audio, lang_for_code2( st->language ) );
2472
2473         hb_list_add( title->list_audio, audio );
2474     }
2475 }
2476
2477 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
2478 {
2479     AVFormatContext *ic = stream->ffmpeg_ic;
2480
2481     // 'Barebones Title'
2482     hb_title_t *title = hb_title_init( stream->path, 0 );
2483     title->index = 1;
2484
2485         // Copy part of the stream path to the title name
2486         char *sep = strrchr(stream->path, '/');
2487         if (sep)
2488                 strcpy(title->name, sep+1);
2489         char *dot_term = strrchr(title->name, '.');
2490         if (dot_term)
2491                 *dot_term = '\0';
2492
2493     uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
2494     title->duration = dur;
2495     dur /= 90000;
2496     title->hours    = dur / 3600;
2497     title->minutes  = ( dur % 3600 ) / 60;
2498     title->seconds  = dur % 60;
2499
2500     // One Chapter
2501     hb_chapter_t * chapter;
2502     chapter = calloc( sizeof( hb_chapter_t ), 1 );
2503     chapter->index = 1;
2504     chapter->duration = title->duration;
2505     chapter->hours = title->hours;
2506     chapter->minutes = title->minutes;
2507     chapter->seconds = title->seconds;
2508     hb_list_add( title->list_chapter, chapter );
2509
2510     // set the title to decode the first video stream in the file
2511     title->demuxer = HB_NULL_DEMUXER;
2512     title->video_codec = 0;
2513     int i;
2514     for (i = 0; i < ic->nb_streams; ++i )
2515     {
2516         if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
2517              avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
2518              title->video_codec == 0 )
2519         {
2520             title->video_id = i;
2521
2522             // We have to use the 'internal' avcodec decoder because
2523             // it needs to share the codec context from this video
2524             // stream. The parser internal to av_read_frame
2525             // passes a bunch of state info to the decoder via the context.
2526             title->video_codec = WORK_DECAVCODECVI;
2527             title->video_codec_param = ffmpeg_codec_param( stream, i );
2528         }
2529         else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
2530                   avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
2531         {
2532             add_ffmpeg_audio( title, stream, i );
2533         }
2534     }
2535
2536     return title;
2537 }
2538
2539 static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
2540 {
2541     if ( pts == AV_NOPTS_VALUE )
2542         return -1;
2543     return (int64_t)( (double)pts * conv_factor );
2544 }
2545
2546 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
2547 {
2548     AVPacket pkt;
2549
2550     if ( av_read_frame( stream->ffmpeg_ic, &pkt ) < 0 )
2551     {
2552         return 0;
2553     }
2554     if ( pkt.size > buf->alloc )
2555     {
2556         // need to expand buffer
2557         hb_buffer_realloc( buf, pkt.size );
2558     }
2559     memcpy( buf->data, pkt.data, pkt.size );
2560     buf->id = pkt.stream_index;
2561     buf->size = pkt.size;
2562     int64_t pts = pkt.pts != AV_NOPTS_VALUE? pkt.pts : 
2563                          pkt.dts != AV_NOPTS_VALUE? pkt.dts : -1;
2564     buf->start = av_to_hb_pts( pts,
2565                   av_q2d(stream->ffmpeg_ic->streams[pkt.stream_index]->time_base)*90000. );
2566     buf->renderOffset = av_to_hb_pts( pkt.pts,
2567                   av_q2d(stream->ffmpeg_ic->streams[pkt.stream_index]->time_base)*90000. );
2568     av_free_packet( &pkt );
2569     return 1;
2570 }
2571
2572 static int ffmpeg_seek( hb_stream_t *stream, float frac )
2573 {
2574     AVFormatContext *ic = stream->ffmpeg_ic;
2575     int64_t pos = (double)ic->duration * (double)frac;
2576     av_seek_frame( ic, -1, pos, pos? 0 : AVSEEK_FLAG_BACKWARD );
2577     return 1;
2578 }