172baa0c629a358a38239266d5a6616d6e6f87d0
[goodguy/history.git] / cinelerra-5.1 / libzmpeg3 / demux.C
1 #include "libzmpeg3.h"
2
3 #define ABS(x) ((x) >= 0 ? (x) : -(x))
4
5 #if 0
6 #define rowsz 16
7
8 static void
9 dmp(unsigned char *bp,int l)
10 {
11    int i, c, n, fad;
12    unsigned char ch[rowsz];
13    fad = 0;
14    c = *bp++;  --l;
15    while( l >= 0 ) {
16       printf(" %04x -",fad);
17       for( i=0; i<rowsz && l>=0; ++i ) {
18          printf(" %02x",c);
19          c &= 0x7f;
20          ch[i] = c>=' ' && c<='~' ? c : ' ';
21          c = *bp++;  --l;
22       }
23       for( n=i; i<rowsz; ++i ) printf("   ");
24       printf("   ");
25       for( i=0; i<n; ++i ) printf("%c", ch[i]);
26       printf("\n");  fad += n;
27    }
28 }
29 #endif
30
31 int zdemuxer_t::
32 get_adaptation_field()
33 {
34 //zmsgs("get_adaptation_field %d\n", adaptation_field_control);
35   ++adaptation_fields;
36   /* get adaptation field length */
37   int length = packet_read_char();
38   int avail = raw_size - raw_offset;
39   if( length > avail ) length = avail;
40   if( length > 0 ) {
41     int flags = packet_read_char();
42     if( ((flags >> 7) & 1) != 0 )
43       discontinuity = 1;
44     int pcr_flag = (flags >> 4) & 1;           
45     if( pcr_flag ) {
46       uint32_t clk_ref_base = packet_read_int32();
47       uint32_t clk_ref_ext = packet_read_int16();
48       if (clk_ref_base > 0x7fffffff ) { /* correct for invalid numbers */
49         clk_ref_base = 0;               /* ie. longer than 32 bits when multiplied by 2 */
50         clk_ref_ext = 0;                /* multiplied by 2 corresponds to shift left 1 (<<=1) */
51       }
52       else {                            /* Create space for bit */
53         clk_ref_base <<= 1; 
54         clk_ref_base |= (clk_ref_ext >> 15); /* Take bit */
55         clk_ref_ext &= 0x01ff;             /* Only lower 9 bits */
56       }
57       time = ((double)clk_ref_base + clk_ref_ext / 300) / 90000;
58       if( length )
59         packet_skip(length-7);
60       if( dump ) zmsgs(" pcr_flag=%x time=%f\n", pcr_flag, time);
61     }
62     else
63       packet_skip(length-1);
64   }
65   return 0;
66 }
67
68 int zdemuxer_t::
69 get_program_association_table()
70 {
71   ++program_association_tables;
72   table_id = packet_read_char();
73   section_length = packet_read_int16() & 0xfff;
74   transport_stream_id = packet_read_int16();
75   packet_skip(raw_size - raw_offset);
76   if( dump ) {
77     zmsgs("table_id=0x%x section_length=%d transport_stream_id=0x%x\n",
78       table_id, section_length, transport_stream_id);
79   }
80   return 0;
81 }
82
83 int zdemuxer_t::
84 get_transport_payload(int is_audio, int is_video)
85 {
86   int bytes = raw_size - raw_offset;
87   if( bytes < 0 ) {
88 //    zerr("got negative payload size!\n");
89     return 1;
90   }
91 /*  if( zdata.size + bytes > RAW_SIZE )
92       bytes = RAW_SIZE - zdata.size; */
93 //zmsgs("2 %d %d %d\n", bytes, read_all, is_audio);
94
95   if( read_all && is_audio ) {
96 // if( pid == 0x1100 )
97 //   zmsgs("1 0x%x %d\n", audio_pid, bytes);
98     memcpy(zaudio.buffer+zaudio.size, raw_data+raw_offset, bytes);
99     zaudio.size += bytes;
100   }
101   else if( read_all && is_video ) {
102 //zmsgs("2 0x%x %d\n", video_pid, bytes);
103     memcpy(zvideo.buffer+zvideo.size, raw_data+raw_offset, bytes);
104     zvideo.size += bytes;
105   }
106   else {
107     memcpy(zdata.buffer+zdata.size, raw_data+raw_offset, bytes);
108     zdata.size += bytes;
109 //zmsgs("10 pid=0x%x bytes=0x%x zdata.size=0x%x\n", pid, bytes, zdata.size);
110   }
111   raw_offset += bytes;
112   return 0;
113 }
114
115 int zdemuxer_t::
116 get_pes_packet_header(uint64_t *pts, uint64_t *dts)
117 {
118   uint32_t pes_header_bytes = 0;
119
120   /* drop first 8 bits */
121   packet_read_char();  
122   uint32_t pts_dts_flags = (packet_read_char() >> 6) & 0x3;
123   int pes_header_data_length = packet_read_char();
124
125   /* Get Presentation Time stamps and Decoding Time Stamps */
126   if( pts_dts_flags & 2 )  {
127     uint64_t tpts = (packet_read_char() >> 1) & 7;  /* Only low 4 bits (7==1111) */
128     tpts <<= 15;
129     tpts |= (packet_read_int16() >> 1);
130     tpts <<= 15;
131     tpts |= (packet_read_int16() >> 1);
132     *pts = tpts;
133     if( pts_dts_flags & 1 ) {
134       uint64_t tdts = (packet_read_char() >> 1) & 7;  /* Only low 4 bits (7==1111) */
135       tdts <<= 15;
136       tdts |= (packet_read_int16() >> 1);
137       tdts <<= 15;
138       tdts |= (packet_read_int16() >> 1);
139       *dts = tdts;
140       pes_header_bytes = 10;
141     }
142     else
143       pes_header_bytes = 5;
144   }
145   /* extract other stuff here! */
146   packet_skip(pes_header_data_length-pes_header_bytes);
147   time = (double)*pts / 90000;
148   if( dump ) {
149     zmsgs("pos=0x%012jx pid=%04x  pts=%f dts=%f pts_dts_flags=0x%02x\n",
150       absolute_position(), pid, (double)*pts / 90000, (double)*dts / 90000, pts_dts_flags);
151   }
152   return 0;
153 }
154
155 int zdemuxer_t::
156 get_unknown_data()
157 {
158   int bytes = raw_size - raw_offset;
159   memcpy(zdata.buffer+zdata.size, raw_data+raw_offset, bytes);
160   zdata.size += bytes;
161   raw_offset += bytes;
162   return 0;
163 }
164
165 int zdemuxer_t::
166 get_transport_pes_packet()
167 {
168   uint64_t pts = 0, dts = 0;
169   get_pes_packet_header(&pts, &dts);
170 //zmsgs("get_transport_pes_packet: stream_id=%x\n", stream_id);
171   /* check ac3 audio (0xbd) or Blu-Ray audio (0xfd) */
172   if( stream_id == 0xbd || stream_id == 0xfd ) {
173 //zmsgs("get_transport_pes_packet %x\n", pid);
174     /* AC3 audio */
175     stream_id = 0x0;
176     got_audio = 1;
177     custom_id = pid;
178
179     if( read_all ) astream_table[custom_id] = afmt_AC3;
180     if( astream == -1 ) astream = custom_id;
181     if( dump ) {
182       zmsgs("offset=0x%jx 0x%x bytes AC3 custom_id=0x%x astream=0x%x do_audio=%p\n", 
183         absolute_position(), raw_size - raw_offset,
184         custom_id, astream, do_audio);
185     }
186     if( (custom_id == astream && do_audio) || read_all ) {
187       audio_pid = pid;
188       set_audio_pts(pts, 90000.);
189       return get_transport_payload(1, 0);
190     }
191   }
192   else if( (stream_id >> 4) == 0x0c || (stream_id >> 4) == 0x0d ) {
193     /* MPEG audio */
194     custom_id = pid;
195     got_audio = 1;
196     /* Just pick the first available stream if no ID is set */
197     if( read_all ) astream_table[custom_id] = afmt_MPEG;
198     if( astream == -1 ) astream = custom_id;
199     if( dump ) zmsgs("   0x%x bytes MP2 audio\n", raw_size-raw_offset);
200     if( (custom_id == astream && do_audio) || read_all ) {
201       audio_pid = pid;
202       set_audio_pts(pts, 90000.);
203       return get_transport_payload(1, 0);
204     }
205   }
206   else if( (stream_id >> 4) == 0x0e ) {
207     /* Video */
208     custom_id = pid;
209     got_video = 1;
210
211     /* Just pick the first available stream if no ID is set */
212     if( read_all )
213       vstream_table[custom_id] = 1;
214     else if( vstream == -1 )
215       vstream = custom_id;
216     if( dump ) zmsgs("   0x%x bytes video data\n", raw_size - raw_offset);
217     if( (custom_id == vstream && do_video) || read_all ) {
218       video_pid = pid;
219       set_video_pts(pts, 90000.);
220       return get_transport_payload(0, 1);
221     }
222   }
223   packet_skip(raw_size - raw_offset);
224   return 0;
225 }
226
227 int zdemuxer_t::
228 get_pes_packet()
229 {
230   ++pes_packets;
231   /* Skip startcode */
232   packet_read_int24();
233   stream_id = packet_read_char();
234   if( dump ) zmsgs("  stream_id=0x%02x\n", stream_id);
235
236   /* Skip pes packet length */
237   packet_read_int16();
238
239   if( (stream_id >= 0xc0 && stream_id < 0xf0) ||
240       stream_id == 0x0bd || stream_id == 0x0fd )
241     return get_transport_pes_packet();
242
243   switch( stream_id ) {
244   case PRIVATE_STREAM_2:
245     zmsg("stream_id == PRIVATE_STREAM_2\n");
246   case PADDING_STREAM:
247     packet_skip(raw_size-raw_offset);
248     return 0;
249   }
250
251   if( src->log_errs )
252     zmsgs("unknown stream_id (0x%02x) in pes packet\n", stream_id);
253   packet_skip(raw_size-raw_offset);
254   return 1;
255 }
256
257 int zdemuxer_t::
258 get_payload()
259 {
260 //zmsgs("get_payload 1 pid=0x%x unit_start=%d\n", pid, payload_unit_start_indicator);
261   if( payload_unit_start_indicator ) {
262     if( pid == 0 )
263       get_program_association_table();
264 #ifdef ZDVB
265     else if( read_all && src->dvb.atsc_pid(pid) )
266       get_transport_payload(0, 0);
267 #endif
268     else if( packet_next_int24() == PACKET_START_CODE_PREFIX )
269       get_pes_packet();
270     else
271       packet_skip(raw_size-raw_offset);
272   }
273   else {
274     if( dump ) zmsgs(" 0x%x bytes elementary data\n", raw_size-raw_offset);
275 // if( pid == 0x1100 ) zmsgs("get_payload 1 0x%x\n", audio_pid);
276     if( pid == audio_pid && (do_audio || read_all) ) {
277       if( do_audio ) got_audio = 1;
278       if( dump ) {
279         zmsgs(" offset=0x%jx 0x%x bytes AC3 pid=0x%x\n", 
280           absolute_position(), raw_size-raw_offset, pid);
281       }
282       get_transport_payload(1, 0);
283     }
284     else if( pid == video_pid && (do_video || read_all) ) {
285       if( do_video ) got_video = 1;
286       get_transport_payload(0, 1);
287     }
288     else {
289       if( read_all ) {
290         get_transport_payload(0, 0);
291       }
292 /*    packet_skip(raw_size-raw_offset); */
293     }
294   }
295   return 0;
296 }
297
298 /* Read a transport packet */
299 int zdemuxer_t::
300 read_transport()
301 {
302   uint32_t bits = 0;
303   int table_entry;
304   title_t *title = titles[current_title];
305   //dump = 1;
306
307   /* Packet size is known for transport streams */
308   raw_size = src->packet_size;
309   raw_offset = 0;
310   stream_id = 0;
311   got_audio = 0;
312   got_video = 0;
313   custom_id = -1;
314
315 //zerrs("read transport 1 %jx %jx\n", title->fs->current_byte, title->fs->total_bytes);
316
317   /* Skip BD or AVC-HD header */
318   if( src->is_bd() )
319     title->fs->read_uint32();
320
321   /* Search for Sync byte */
322   for( int i=0x10000; --i>=0 && !title->fs->eof(); ) {
323     if( (bits=title->fs->read_char()) == SYNC_BYTE ) break;
324   }
325
326   program_byte = absolute_position();
327   /* Store byte just read as first byte */
328   if( !title->fs->eof() && bits == SYNC_BYTE ) {
329     last_packet_start = program_byte-1;
330     raw_data[0] = SYNC_BYTE;
331     /* Read packet */
332     int fragment_size = src->packet_size - 1;
333     /* Skip BD header */
334     if( src->is_bd() ) {
335       fragment_size -= 4;
336       raw_size -= 4;
337     }
338     title->fs->read_data(raw_data+1, fragment_size);
339   }
340   else {
341     /* Failed */
342     return 1;
343   }
344
345   /* Sync byte */
346   packet_read_char();
347   bits =  packet_read_int24() & 0x00ffffff;
348   transport_error_indicator = (bits >> 23) & 0x1;
349   payload_unit_start_indicator = (bits >> 22) & 0x1;
350   pid = custom_id = (bits >> 8) & 0x00001fff;
351
352   transport_scrambling_control = (bits >> 6) & 0x3;
353   adaptation_field_control = (bits >> 4) & 0x3;
354   continuity_counter = bits & 0xf;
355
356   is_padding = pid == 0x1fff ? 1 : 0;
357   if( dump ) {
358     zmsgs("offset=0x%jx pid=0x%02x continuity=0x%02x padding=%d adaptation=%d unit_start=%d\n", 
359       last_packet_start, pid, continuity_counter, is_padding,
360       adaptation_field_control, payload_unit_start_indicator);
361   }
362
363   /* Abort if padding.  Should abort after pid == 0x1fff for speed. */
364   if( is_padding || transport_error_indicator || (!read_all && (
365        (do_video && do_video->pid != pid) ||
366        (do_audio && do_audio->pid != pid))) ) {
367     program_byte = absolute_position();
368     return 0;
369   }
370
371   /* Get pid from table */
372   int result = 0;
373   for( table_entry=0; table_entry<total_pids; ++table_entry ) {
374     if( pid == pid_table[table_entry] ) {
375       result = 1;
376       break;
377     }
378   }
379
380   /* Not in pid table */
381   if( !result && total_pids<PIDMAX ) {
382     pid_table[table_entry] = pid;
383     continuity_counters[table_entry] = continuity_counter;  /* init */
384     total_pids++;
385   }
386
387   result = 0;
388   if( adaptation_field_control & 0x2 )
389     result = get_adaptation_field();
390
391   /* Need to enter in astream and vstream table: */
392   /* PID ored with stream_id */
393   if( adaptation_field_control & 0x1 )
394     result = get_payload();
395
396   program_byte = absolute_position();
397   return result;
398 }
399
400 int zdemuxer_t::
401 get_system_header()
402 {
403   title_t *title = titles[current_title];
404   int length = title->fs->read_uint16();
405   title->fs->seek_relative(length);
406   return 0;
407 }
408
409 uint64_t zdemuxer_t::
410 get_timestamp()
411 {
412   uint64_t timestamp;
413   title_t *title = titles[current_title];
414   /* Only low 4 bits (7==1111) */
415   timestamp = (title->fs->read_char() >> 1) & 7;  
416   timestamp <<= 15;
417   timestamp |= (title->fs->read_uint16() >> 1);
418   timestamp <<= 15;
419   timestamp |= (title->fs->read_uint16() >> 1);
420   return timestamp;
421 }
422
423 int zdemuxer_t::
424 get_pack_header()
425 {
426   uint32_t i, j;
427   uint32_t clock_ref, clock_ref_ext;
428   title_t *title = titles[current_title];
429
430   /* Get the time code */
431   if( (title->fs->next_char() >> 4) == 2 ) {
432     time = (double)get_timestamp() / 90000; /* MPEG-1 */
433     title->fs->read_uint24();               /* Skip 3 bytes */
434   }
435   else if( (title->fs->next_char() & 0x40) ) {
436     i = title->fs->read_uint32();
437     j = title->fs->read_uint16();
438     if( (i & 0x40000000) || (i >> 28) == 2 ) {
439       clock_ref = ((i & 0x38000000) << 3);
440       clock_ref |= ((i & 0x03fff800) << 4);
441       clock_ref |= ((i & 0x000003ff) << 5);
442       clock_ref |= ((j & 0xf800) >> 11);
443       clock_ref_ext = (j >> 1) & 0x1ff;
444       time = (double)(clock_ref + clock_ref_ext / 300) / 90000;
445       /* Skip 3 bytes */
446       title->fs->read_uint24();
447       i = title->fs->read_char() & 0x7;
448       /* stuffing */
449       title->fs->seek_relative(i);  
450     }
451   }
452   else {
453     title->fs->seek_relative(2);
454   }
455   return 0;
456 }
457
458 int zdemuxer_t::
459 get_program_payload(int bytes, int is_audio, int is_video)
460 {
461   title_t *title = titles[current_title];
462   int n = 0;
463   if( read_all && is_audio ) {
464     if( (n=zaudio.allocated-zaudio.size) > bytes ) n = bytes;
465     title->fs->read_data(zaudio.buffer+zaudio.size, n);
466     zaudio.size += n;
467   }
468   else if( read_all && is_video ) {
469     if( (n=zvideo.allocated-zvideo.size) > bytes ) n = bytes;
470     title->fs->read_data(zvideo.buffer+zvideo.size, n);
471     zvideo.size += n;
472   }
473   else {
474     if( (n=zdata.allocated-zdata.size) > bytes ) n = bytes;
475     title->fs->read_data(zdata.buffer+zdata.size, n);
476     zdata.size += n;
477   }
478   if( bytes > n )
479     title->fs->seek_relative(bytes - n);
480   return 0;
481 }
482
483 int zdemuxer_t::
484 handle_scrambling(int decryption_offset)
485 {
486   title_t *title = titles[current_title];
487   /* Advance 2048 bytes if scrambled.  We might pick up a spurrius */
488   /* packet start code in the scrambled data otherwise. */
489   int64_t next_packet_position = last_packet_start + DVD_PACKET_SIZE;
490   if( next_packet_position > absolute_position() ) {
491     title->fs->seek_relative(next_packet_position-absolute_position());
492   }
493   /* Descramble if desired. */
494   if( zdata.size || zaudio.size || zvideo.size ) {
495     uint8_t *buffer_ptr = 0;
496     if( zdata.size ) buffer_ptr = zdata.buffer;
497     else if( zaudio.size ) buffer_ptr = zaudio.buffer;
498     else if( zvideo.size ) buffer_ptr = zvideo.buffer;
499 //zmsgs(" zdata.size=%x decryption_offset=%x\n",
500 //  zdata.size, decryption_offset);
501     if( title->fs->css.decrypt_packet(buffer_ptr, decryption_offset)) {
502       zerr("handle_scrambling: Decryption not available\n");
503       return 1;
504     }
505   }
506   return 0;
507 }
508
509 void zdemuxer_t::
510 del_subtitle(int idx)
511 {
512   delete subtitles[idx];
513   for( int i=idx; ++i<total_subtitles; )
514     subtitles[i-1] = subtitles[i];
515   --total_subtitles;
516 }
517
518 /* Create new subtitle object if none with the same id is in the table */
519 zsubtitle_t* zdemuxer_t::
520 get_subtitle(int id, int64_t offset)
521 {
522 //zmsgs(" id=0x%04x ofs=%012lx\n", id, offset);
523   subtitle_t *subtitle = 0, *reuse = 0;
524   /* Get current/reuse subtitle object for the stream */
525   /* delete extra expired subtitles */
526   int i = 0;
527   while( i < total_subtitles ) {
528     subtitle_t *sp = subtitles[i];
529     if( sp->done < 0 ) {
530       if( reuse ) { del_subtitle(i);  continue; }
531       reuse = sp;
532     }
533     else if( !subtitle && !sp->done && sp->id == id )
534       subtitle = sp;
535     ++i;
536   }
537   /* found current unfinished subtitle */
538   if( subtitle ) return subtitle;
539   /* Make new/reused subtitle object */
540   if( reuse ) {
541     subtitle = reuse;
542     subtitle->data_used = 0;
543     subtitle->done = 0;
544     subtitle->draw = 0;
545     subtitle->active = 0;
546     subtitle->force = 0;
547     subtitle->frame_time = 0;
548   }
549   else if( total_subtitles < MAX_SUBTITLES ) {
550     subtitle = new subtitle_t();
551     subtitles[total_subtitles++] = subtitle;
552   }
553   else
554     return 0;
555   subtitle->id = id;
556   subtitle->offset = offset;
557   return subtitle;
558 }
559
560 void zsubtitle_t::
561 realloc_data(int n)
562 {
563   uint8_t *new_data = new uint8_t[n];
564   memcpy(new_data,data,data_used);
565   delete [] data;  data = new_data;
566   data_allocated = n;
567 }
568
569 void zdemuxer_t::
570 handle_subtitle(zmpeg3_t *src, int stream_id, int bytes)
571 {
572   int pos = zdata.position;
573   int size = zdata.size - zdata.position;
574   zdata.size = zdata.position = 0;
575   if( size < bytes ) bytes = size;
576   subtitle_t *subtitle = get_subtitle(stream_id, program_byte);
577   if( !subtitle ) return;
578   size = subtitle->data_used + bytes;
579   if( subtitle->data_allocated < size ) subtitle->realloc_data(size);
580   memcpy(subtitle->data+subtitle->data_used,zdata.buffer+pos,bytes);
581   subtitle->data_used += bytes;
582   if( subtitle->data_used >= 2 ) {
583     uint8_t *bfr = subtitle->data;
584     size = (bfr[0]<<8) + bfr[1];
585     if( subtitle->data_used >= size ) {
586       zvideo_t *vid = do_video ? do_video->video : 0;
587       strack_t *strack = src->create_strack(subtitle->id, vid);
588       if( strack->append_subtitle(subtitle) )
589         subtitle->done = -1;
590       else
591         got_subtitle = 1;
592     }
593   }
594 }
595
596 int zdemuxer_t::
597 handle_pcm(int bytes)
598 {
599   /* Synthesize PCM header and delete MPEG header for PCM data */
600   /* Must be done after decryption */
601   uint8_t zcode;
602   int bits_code;
603   int bits;
604   int samplerate_code;
605   int samplerate;
606   uint8_t *output = 0;
607   uint8_t *data_buffer = 0;
608   int data_start = 0;
609   int *data_size = 0;
610   int i, j;
611
612   if( read_all && zaudio.size ) {
613     output = zaudio.buffer + zaudio.start;
614     data_buffer = zaudio.buffer;
615     data_start = zaudio.start;
616     data_size = &zaudio.size;
617   }
618   else {
619     output = zdata.buffer + zdata.start;
620     data_buffer = zdata.buffer;
621     data_start = zdata.start;
622     data_size = &zdata.size;
623   }
624
625   /* Shift audio back */
626   zcode = output[1];
627   j = *data_size+zaudio_t::PCM_HEADERSIZE-3-1; 
628   for( i=*data_size-1; i>=data_start; --i,--j )
629     *(data_buffer+j) = *(data_buffer+i);
630   *data_size += zaudio_t::PCM_HEADERSIZE - 3;
631
632   bits_code = (zcode >> 6) & 3;
633   samplerate_code = (zcode >>4) & 1;
634
635   output[0] = 0x7f;
636   output[1] = 0x7f;
637   output[2] = 0x80;
638   output[3] = 0x7f;
639   /* Samplerate */
640   switch( samplerate_code ) {
641   case 1:  samplerate = 96000; break;
642   default: samplerate = 48000; break;
643   }
644   *(int32_t*)(output + 4) = samplerate;
645   /* Bits */
646   switch( bits_code ) {
647     case 0:   bits = 16;  break;
648     case 1:   bits = 20;  break;
649     case 2:   bits = 24;  break;
650     default:  bits = 16;  break;            
651   }
652   *(int32_t*)(output+ 8) = bits;
653   *(int32_t*)(output+12) = (zcode & 0x7) + 1; /* Channels */
654   *(int32_t*)(output+16) = bytes - 3 +
655      zaudio_t::PCM_HEADERSIZE;               /* Framesize */
656 //zmsgs(" %d %d %d\n", *(int32_t*)(output+ 8),
657 //  *(int32_t*)(output+12), *(int32_t*)(output+16));
658   return 0;
659 }
660
661 /* Program packet reading core */
662 int zdemuxer_t::
663 get_program_pes_packet( uint32_t header)
664 {
665   uint64_t pts = 0, dts = 0;
666   int pes_packet_length;
667   int64_t pes_packet_start, pes_packet_end;
668   int decryption_offset = 0;
669   title_t *title = titles[current_title];
670   int scrambling = 0;
671   int do_pcm = 0;
672   int do_subtitle = 0;
673
674   zdata.start = zdata.size;
675   zaudio.start = zaudio.size;
676   zvideo.start = zvideo.size;
677
678   stream_id = header & 0xff;
679   pes_packet_length = title->fs->read_uint16();
680   pes_packet_start = absolute_position();
681   pes_packet_end = pes_packet_start + pes_packet_length;
682 //zmsgs(" pes_packet_start=0x%jx pes_packet_length=%x zdata.size=%x\n", 
683 //      pes_packet_start, pes_packet_length, zdata.size);
684
685   if( stream_id != PRIVATE_STREAM_2 && stream_id != PADDING_STREAM ) {
686     if( (title->fs->next_char() >> 6) == 0x02 ) {
687       /* Get MPEG-2 packet */
688       int pes_header_bytes = 0;
689       int pts_dts_flags;
690       int pes_header_data_length;
691       last_packet_decryption = absolute_position();
692       scrambling = title->fs->read_char() & 0x30;
693    /* scrambling = 1; */
694    /* Reset scrambling bit for the mpeg3cat utility */
695    /*      if( scrambling ) raw_data[raw_offset - 1] &= 0xcf; */
696    /* Force packet length if scrambling */
697       if( scrambling )
698         pes_packet_length = DVD_PACKET_SIZE - pes_packet_start + last_packet_start;
699       pts_dts_flags = (title->fs->read_char() >> 6) & 0x3;
700       pes_header_data_length = title->fs->read_char();
701
702       /* Get Presentation and Decoding Time Stamps */
703       if( pts_dts_flags == 2 ) {
704         pts = get_timestamp();
705         if( dump ) zmsgs("pts=0x%jx\n", pts);
706         pes_header_bytes += 5;
707       }
708       else if( pts_dts_flags == 3 ) {
709         pts = get_timestamp();
710         dts = get_timestamp();
711         if( dump ) zmsgs("pts=%jd dts=%jd\n", pts, dts);
712 /*      pts = (title->fs->read_char() >> 1) & 7;
713  *      pts <<= 15;
714  *      pts |= (title->fs->read_uint16() >> 1);
715  *      pts <<= 15;
716  *      pts |= (title->fs->read_uint16() >> 1);
717  *      dts = (title->fs->read_char() >> 1) & 7;
718  *      dts <<= 15;
719  *      dts |= (title->fs->read_uint16() >> 1);
720  *      dts <<= 15;
721  *      dts |= (title->fs->read_uint16() >> 1);
722  */
723         pes_header_bytes += 10;
724       }
725 //zmsgs("get_program_pes_packet do_audio=%p do_video=%p pts=%x dts=%x\n", 
726 //  do_audio, do_video, pts, dts);
727       /* Skip unknown */
728       title->fs->seek_relative(pes_header_data_length-pes_header_bytes);
729     }
730     else {
731       int pts_dts_flags;
732       /* Get MPEG-1 packet */
733       while( !title->fs->eof() && title->fs->next_char() == 0xff ) {
734         title->fs->read_char();
735       }
736       /* Skip STD buffer scale */
737       if( (title->fs->next_char() & 0x40) ) {
738         title->fs->seek_relative(2);
739       }
740       /* Decide which timestamps are available */
741       pts_dts_flags = title->fs->next_char();
742       if( pts_dts_flags >= 0x30 ) {
743         /* Get the presentation and decoding time stamp */
744         pts = get_timestamp();
745         dts = get_timestamp();
746       }
747       else if( pts_dts_flags >= 0x20 ) {
748         /* Get just the presentation time stamp */
749         pts = get_timestamp();
750       }
751       else if( pts_dts_flags == 0x0f ) {
752         /* End of timestamps */
753         title->fs->read_char();
754       }
755       else {
756         return 1;     /* Error */
757       }
758     }
759     /* Now extract the payload. */
760     if( (stream_id >> 4) == 0xc || (stream_id >> 4) == 0xd ) {
761       /* Audio data */
762       /* Take first stream ID if -1 */
763       pes_packet_length -= absolute_position() - pes_packet_start;
764       got_audio = 1;
765       custom_id = stream_id & 0x0f;
766       if( read_all )
767         astream_table[custom_id] = afmt_MPEG;
768       else if( astream == -1 )
769         astream = custom_id;
770       if( (custom_id == astream && do_audio) || read_all ) {
771         set_audio_pts(pts, 90000.); //60000
772         decryption_offset = absolute_position() - last_packet_start;
773         if( dump ) {
774           zmsgs(" MP2 audio data offset=0x%jx custom_id=%x size=%x\n", 
775             program_byte, custom_id, pes_packet_length);
776         }
777         get_program_payload(pes_packet_length, 1, 0);
778       }
779       else {
780         if( dump ) zmsgs(" skipping audio size=%x\n", pes_packet_length);
781       }
782     }
783     else if( (stream_id >> 4) == 0xe ) {
784       /* Video data */
785       /* Take first stream ID if -1 */
786       pes_packet_length -= absolute_position() - pes_packet_start;
787       got_video = 1;
788       custom_id = stream_id & 0x0f;
789       if( read_all ) {
790         vstream_table[custom_id] = 1;
791       } else if( vstream == -1 ) 
792         vstream = custom_id;
793       if( (custom_id == vstream && do_video) || read_all ) {
794         set_video_pts(pts, 90000.); //60000
795         decryption_offset = absolute_position() - last_packet_start;
796         if( dump ) {
797           zmsgs(" video offset=0x%jx custom_id=%x size=%x\n", 
798             program_byte, custom_id, pes_packet_length);
799         }
800         get_program_payload(pes_packet_length, 0, 1);
801       }
802       else {
803         if( dump ) zmsgs(" skipping video size=%x\n", pes_packet_length);
804       }
805     }
806     else if( (stream_id == 0xbd || stream_id == 0xbf) && 
807              ((title->fs->next_char() & 0xf0) == 0x20) ) {
808       /* DVD subtitle data */
809       stream_id = title->fs->read_char();
810       custom_id = stream_id & 0x0f;
811       if( read_all ) {
812         if( !sstream_table[custom_id] ) {
813           sstream_table[custom_id] = 1;
814           src->strack[src->total_stracks] = new strack_t(custom_id);
815           if( src->strack[src->total_stracks] ) ++src->total_stracks;
816         }
817       }
818       /* Get data length */
819       pes_packet_length -= absolute_position() - pes_packet_start;
820       if( do_video ) {
821         decryption_offset = absolute_position() - last_packet_start;
822         get_program_payload(pes_packet_length, 0, 0);
823         do_subtitle = 1;
824       }
825       else {
826         if( dump ) zmsgs(" skipping subtitle size=%x\n", pes_packet_length);
827       }
828 //zmsgs("id=0x%02x size=%d\n", stream_id, pes_packet_length);
829     }
830     else if( (stream_id == 0xbd || stream_id == 0xbf) && 
831              title->fs->next_char() != 0xff &&
832              ((title->fs->next_char() & 0xf0) == 0x80 ||
833              (title->fs->next_char() & 0xf0) == 0xa0) ) {
834       /* DVD audio data */
835       /* Get the audio format */
836       int format = (title->fs->next_char() & 0xf0) == 0xa0 ?
837         afmt_PCM : afmt_AC3;
838       /* Picks up bogus data if (& 0xf) or (& 0x7f) */
839       stream_id = title->fs->next_char();
840       /* only 8 streams, counting from 0x80 */
841       custom_id = stream_id & 0x87;
842       if( astream_table[custom_id] >= 0 ) {
843         got_audio = 1;
844         /* Take first stream ID if not building TOC. */
845         if( read_all )
846           astream_table[custom_id] = format;
847         else if( astream == -1 )
848           astream = custom_id;
849         if( (custom_id == astream && do_audio) || read_all ) {
850           set_audio_pts(pts, 90000.); //60000
851           aformat = format;
852           title->fs->read_uint32();
853           pes_packet_length -= absolute_position() - pes_packet_start;
854           decryption_offset = absolute_position() - last_packet_start;
855           if( format == afmt_PCM )
856             do_pcm = 1;
857 //zmsgs("get_program_pes_packet 5 %x\n", decryption_offset);
858           if( dump ) zmsgs(" AC3 audio offset=0x%jx, custom_id=%03x, size=%x\n",
859                program_byte, custom_id, pes_packet_length);
860           get_program_payload(pes_packet_length, 1, 0);
861         }
862       }
863     }
864   }
865   else if( stream_id == PRIVATE_STREAM_2 || stream_id == PADDING_STREAM ) {
866     pes_packet_length -= absolute_position() - pes_packet_start;
867     if( stream_id == NAV_PACKET_STREAM /* == PRIVATE_STREAM_2 */ ) {
868       if( !nav ) nav = new nav_t();
869       int sub_stream = title->fs->read_char();
870       --pes_packet_length;
871       switch( sub_stream ) {
872       case NAV_PCI_SSID:
873         if( pes_packet_length >= NAV_PCI_BYTES ) {
874           title->fs->read_data(&nav->pci[0],NAV_PCI_BYTES);
875 //zmsgs("nav_pci: %lu + %lu\n",absolute_position()/2048,absolute_position()%2048);
876 //dmp(&nav->pci[0],NAV_PCI_BYTES);
877           pes_packet_length -= NAV_PCI_BYTES;
878         }
879         break;
880       case NAV_DSI_SSID:
881         if( pes_packet_length >= NAV_DSI_BYTES ) {
882           title->fs->read_data(&nav->dsi[0],NAV_DSI_BYTES);
883 //zmsgs("nav_dsi: %lu + %lu\n",absolute_position()/2048,absolute_position()%2048);
884 //dmp(&nav->dsi[0],NAV_DSI_BYTES);
885           pes_packet_length -= NAV_DSI_BYTES;
886           int64_t blk_pos = ((int64_t)nav->dsi_gi_pck_lbn() & 0x7fffffffU) * DVD_PACKET_SIZE;
887           if( blk_pos != 0 && last_packet_start != blk_pos )
888             zmsgs("blk_pos 0x%jx != 0x%jx last_packet_start\n", blk_pos, last_packet_start);
889           int64_t next_pos, next_vobu, end_byte, end_pos;
890           int64_t blk_size = (int64_t)nav->dsi_gi_vobu_ea() * DVD_PACKET_SIZE;
891           nav_cell_end_byte = program_byte + blk_size + DVD_PACKET_SIZE;
892           end_pos = program_to_absolute(nav_cell_end_byte, &end_byte);
893           if( end_byte != nav_cell_end_byte ) 
894             zmsgs("end_byte 0x%jx != 0x%jx nav_cell_end_byte\n", end_byte, nav_cell_end_byte);
895           uint32_t next_vobu_offset = nav->dsi_si_next_vobu();
896           if( next_vobu_offset == NAV_SRI_END_OF_CELL ) {
897             next_vobu = playinfo_next_cell();
898             next_pos = next_vobu >= 0 ? program_to_absolute(next_vobu) : -1;
899           }
900           else {
901             next_pos = blk_pos + ((int64_t)next_vobu_offset & 0x7fffffffU) * DVD_PACKET_SIZE;
902             next_vobu = absolute_to_program(next_pos);
903           }
904           if( next_vobu > 0 && end_pos != next_pos ) {
905             nav_cell_next_vobu = next_vobu;
906             zmsgs("blk end_pos 0x%jx != 0x%jx next_pos, jump to 0x%jx\n",
907               end_pos, next_pos, nav_cell_next_vobu);
908           }
909           else
910             nav_cell_end_byte = nav_cell_next_vobu = -1;
911 if( nav_cell_end_byte >= 0 )
912   zmsgs("nav pkt at 0x%jx ends 0x%jx next_vobu 0x%jx/0x%jx\n",
913     program_byte, nav_cell_end_byte, nav_cell_next_vobu, next_pos);
914         }
915         break;
916       }
917     }
918   }
919
920   int64_t len = pes_packet_end - absolute_position();
921   if( len > 0 )
922     title->fs->seek_relative(len);
923
924   if( scrambling )
925     handle_scrambling(decryption_offset);
926   if( do_pcm )
927     handle_pcm(pes_packet_length);
928   else if( do_subtitle )
929     handle_subtitle(src, custom_id, pes_packet_length);
930   return 0;
931 }
932
933 int zdemuxer_t::
934 read_program()
935 {
936   int64_t pos;
937   int result = 0;
938   title_t *title = titles[current_title];
939   uint32_t header = 0;
940   int pack_count = 0;
941   const int debug = 0;
942
943   got_audio = 0;
944   got_video = 0;
945   stream_id = 0;
946   custom_id = -1;
947   got_subtitle = 0;
948
949   if( title->fs->eof() ) return 1;
950   last_packet_start = absolute_position();
951   program_byte = absolute_to_program(last_packet_start);
952
953 /* Search for next header */
954 /* Parse packet until the next packet start code */
955   while( !result ) {
956     title = titles[current_title];
957     if( debug )
958       zmsgs("%d %d 0x%jx 0x%jx\n", 
959         __LINE__, result, title->fs->current_byte, title->fs->total_bytes);
960     if( title->fs->eof() ) break;
961     pos = absolute_position();
962     header = title->fs->read_uint32();
963     if( header == PACK_START_CODE ) {
964       if( debug )
965         zmsgs("%d %d 0x%jx 0x%jx\n", 
966           __LINE__, result, title->fs->current_byte, title->fs->total_bytes);
967 /* Second start code in this call.  Don't read it. */
968       if( pack_count ) {
969         title->fs->seek_relative(-4);
970         break;
971       }
972       last_packet_start = pos;
973       result = get_pack_header();
974       pack_count++;
975       if( debug )
976         zmsgs("%d %d 0x%jx 0x%jx\n",
977           __LINE__, result, title->fs->current_byte, title->fs->total_bytes);
978     }
979     else if( header == SYSTEM_START_CODE && pack_count ) {
980       if( debug )
981         zmsgs("%d %d 0x%jx 0x%jx\n",
982           __LINE__, result, title->fs->current_byte, title->fs->total_bytes);
983       result = get_system_header();
984       if( debug )
985         zmsgs("%d %d 0x%jx 0x%jx\n",
986           __LINE__, result, title->fs->current_byte, title->fs->total_bytes);
987     }
988     else if( header == PROGRAM_END_CODE ) {
989       title->fs->total_bytes = title->fs->current_byte;
990       stream_end = program_byte;
991     }
992     else if( (header >> 8) == PACKET_START_CODE_PREFIX && pack_count ) {
993       if( debug )
994         zmsgs("%d %d 0x%jx 0x%jx\n",
995           __LINE__, result, title->fs->current_byte, title->fs->total_bytes);
996       result = get_program_pes_packet(header);
997       if( debug )
998         zmsgs("%d %d 0x%jx 0x%jx\n",
999           __LINE__, result, title->fs->current_byte, title->fs->total_bytes);
1000     }
1001     else {
1002 /* if whamming on bad blocks, if possible skip to the next cell and continue */
1003       int errs = title->fs->errors();
1004       if( errs ) {
1005         if( total_titles > 1 || title->cell_table_size > 1 ) {
1006           zmsgs("%d device errs, truncating cell %d\n", errs, current_cell_no());
1007           program_byte = absolute_to_program(last_packet_start);
1008           src->demuxer->titles[current_title]->cell_table[title_cell].program_end =
1009             title->cell_table[title_cell].program_end = program_byte;
1010           nav_cell_end_byte = 0;
1011         }
1012       }
1013       else
1014 /* Try again starting with next byte */
1015         program_byte = absolute_to_program(pos) + 1;
1016       result = seek_phys();
1017       last_packet_start = absolute_position();
1018     }
1019   }
1020 /* Ignore errors in the parsing.  Just quit if eof. */
1021   result = 0;
1022   if( debug )
1023     zmsgs("%d\n", __LINE__);
1024   last_packet_end = absolute_position();
1025   pos = absolute_to_program(last_packet_start);
1026   program_byte = pos + (last_packet_end - last_packet_start);
1027   if( debug )
1028     zmsgs("%d\n", __LINE__);
1029   return result;
1030 }
1031
1032 int zdemuxer_t::
1033 get_cell(int no, zcell_t *&v)
1034 {
1035   for( int i=0; i<total_titles; ++i ) {
1036     title_t *title = titles[i];
1037     int n = title->cell_table_size;
1038     for( int k=0; k<n; ++k ) {
1039       zcell_t *cell = &title->cell_table[k];
1040       if( cell->cell_no >= no ) {
1041         v = cell;
1042         return cell->cell_no == no ? 0 : 1;
1043       }
1044     }
1045   }
1046   return -1;
1047 }
1048
1049 int zdemuxer_t::
1050 seek_phys()
1051 {
1052   int last_cell_no = current_cell_no();
1053
1054   int64_t next_byte = program_byte;
1055   if( !reverse && nav_cell_end_byte >= 0 && next_byte >= nav_cell_end_byte ) {
1056     if( nav_cell_next_vobu >= 0 ) {
1057       if( next_byte != nav_cell_next_vobu ) {
1058         zmsgs("next_vobu 0x%jx!=0x%jx next_byte\n", nav_cell_next_vobu, next_byte);
1059         next_byte = nav_cell_next_vobu;
1060       }
1061       nav_cell_next_vobu = -1;
1062     }
1063     nav_cell_end_byte = -1;
1064   }
1065
1066   int next_title, next_cell;
1067   int64_t pos = program_to_absolute(next_byte, &next_byte, &next_title, &next_cell);
1068   if( next_byte < 0 ) return 1;
1069
1070
1071   int do_cell_change = 0;
1072   if( program_byte != next_byte ) {
1073     zmsgs("program_byte hopped from 0x%jx to 0x%jx\n", program_byte, next_byte);
1074     program_byte = next_byte;
1075     do_cell_change = 1;
1076   }
1077   if( next_title != current_title ) {
1078     open_title(next_title);
1079     do_cell_change = 1;
1080   }
1081   if( title_cell != next_cell ) {
1082     title_cell = next_cell;
1083     do_cell_change = 1;
1084   }
1085
1086   if( do_cell_change ) {
1087 /* Need to change cells if we get here. */
1088     int cell_no = current_cell_no();
1089     if( last_cell_no != cell_no ) {
1090       nav_cell_end_byte = -1;
1091       if( !read_all ) {
1092         zcell_t *cell = 0;
1093         if( !get_cell(cell_no, cell) && cell->discontinuity ) {
1094           if( do_audio ) {
1095             atrack_t *atrk = do_audio;
1096             atrk->reset_pts();
1097             atrk->pts_offset = atrk->audio_time = cell->cell_time;
1098             atrk->pts_position = atrk->audio_time * atrk->sample_rate;
1099           }
1100           if( do_video ) {
1101             vtrack_t *vtrk = do_video;
1102             vtrk->reset_pts();
1103             vtrk->pts_offset = vtrk->video_time = cell->cell_time;
1104             vtrk->pts_position = vtrk->video_time * vtrk->frame_rate;
1105           }
1106         }
1107       }
1108     }
1109   }
1110
1111   if( !zdata.length() ) {
1112     if( program_byte >= movie_size() ) return 1;
1113     if( stream_end >= 0 && program_byte >= stream_end ) return 1;
1114   }
1115   error_flag = 0;
1116   title_t *title = titles[current_title];
1117   title->fs->seek(pos - title->start_byte);
1118   return 0;
1119 }
1120
1121 int zdemuxer_t::
1122 next_code(uint32_t zcode)
1123 {
1124   uint32_t result = 0;
1125   int error = 0;
1126
1127   while( result!=zcode && !error ) {
1128     result <<= 8;
1129     title_t *title = titles[current_title];
1130     result |= title->fs->read_char() & 0xff;
1131     ++program_byte;
1132     error = seek_phys();
1133   }
1134
1135   return error;
1136 }
1137
1138 /* Read packet in the forward direction */
1139 int zdemuxer_t::
1140 read_next_packet()
1141 {
1142   if( current_title < 0 ) return 1;
1143   int result = 0;
1144   title_t *title = titles[current_title];
1145 /* Reset output buffer */
1146   zdata.size = 0;
1147   zdata.position = 0;
1148   zaudio.size = 0;
1149   zvideo.size = 0;
1150 //zmsgs("%d program_byte=0x%jx reverse=%d\n", 
1151 //   __LINE__, program_byte, reverse);
1152
1153 /* Switch to forward direction. */
1154   if( reverse ) {
1155 /* Don't reread anything if we're at the beginning of the file. */
1156     if( program_byte < 0 ) {
1157       program_byte = 0;
1158       result = seek_phys();
1159 /* First character was the -1 byte which brings us to 0 after this function. */
1160       result = 1;
1161     }
1162     else if( src->packet_size > 0 ) { /* Transport or elementary stream */
1163       program_byte += src->packet_size;
1164       result = seek_phys();
1165     }
1166     else {
1167 /* Packet just read */
1168       if( !result )
1169         result = next_code(PACK_START_CODE);
1170 /* Next packet */
1171       if( !result )
1172         result = next_code(PACK_START_CODE);
1173     }
1174     reverse = 0;
1175   }
1176
1177 /* Read packets until the output buffer is full. */
1178 /* Read a single packet if not fetching audio or video. */
1179   if( !result ) do {
1180     title = titles[current_title];
1181 //zmsgs("10 0x%jx\n", absolute_position());
1182     if( src->is_transport_stream() ) {
1183       result = seek_phys();
1184       if( !result )
1185         result = read_transport();
1186     }
1187     else if( src->is_program_stream() ) {
1188       result = seek_phys();
1189 //zmsgs("%d 0x%jx\n", __LINE__, tell_byte());
1190       if( !result )
1191         result = read_program();
1192 //zmsgs("%d 0x%jx\n", __LINE__, tell_byte());
1193     }
1194     else {
1195       if( read_all && src->is_audio_stream() ) {
1196 /* Read elementary stream. */
1197         result = title->fs->read_data(zaudio.buffer, src->packet_size);
1198         zaudio.size = src->packet_size;
1199       }
1200       else if( read_all && src->is_video_stream() ) {
1201 /* Read elementary stream. */
1202         result = title->fs->read_data(zvideo.buffer, src->packet_size);
1203         zvideo.size = src->packet_size;
1204       }
1205       else {
1206         result = title->fs->read_data(zdata.buffer, src->packet_size);
1207         zdata.size = src->packet_size;
1208       }
1209       program_byte += src->packet_size;
1210       result |= seek_phys();
1211     }
1212 //zmsgs("100 result=%d zdata.size=0x%x\n", result, zdata.size);
1213   } while( !result && zdata.size == 0 && (do_audio || do_video) );
1214
1215 //zmsgs("%d result=%d zdata.size=0x%x\n", __LINE__, result, zdata.size);
1216   return result;
1217 }
1218
1219 int zdemuxer_t::
1220 previous_code(uint32_t zcode)
1221 {
1222   uint32_t result = 0;
1223   int error = 0;
1224
1225   while( result!=zcode && program_byte>0 && !error ) {
1226     result >>= 8;
1227     title_t *title = titles[current_title];
1228     title->fs->seek(program_byte-title->start_byte-1);
1229     result |= (title->fs->read_char() & 0xff) << 24;
1230     --program_byte;
1231     error = seek_phys();
1232   }
1233   return error;
1234 }
1235
1236 /* Read the packet right before the packet we're currently on. */
1237 int zdemuxer_t::
1238 read_prev_packet()
1239 {
1240   int result = 0;
1241   title_t *title = titles[current_title];
1242   nav_cell_end_byte = -1;
1243   zdata.size = 0;
1244   zdata.position = 0;
1245 /* Switch to reverse direction */
1246   if( !reverse ) {
1247     reverse = 1;
1248 /* Transport stream or elementary stream case */
1249     if( src->packet_size > 0 ) {
1250       program_byte -= src->packet_size;
1251       result = seek_phys();
1252     }
1253     else { /* Program stream */
1254       result = previous_code(PACK_START_CODE);
1255     }
1256   }
1257
1258 /* Go to beginning of previous packet */
1259   do {
1260     title = titles[current_title];
1261
1262 /* Transport stream or elementary stream case */
1263     if( src->packet_size > 0 ) {
1264 //zmsgs("1 result=%d title=%d tell=0x%jx program_byte=0x%jx\n",
1265 //        result, current_title, absolute_position(), program_byte);
1266       program_byte -= src->packet_size;
1267       result = seek_phys();
1268 //zmsgs("100 result=%d title=%d tell=0x%jx program_byte=0x%jx\n",
1269 //        result, current_title, absolute_position(), program_byte);
1270     }
1271     else {
1272       if( !result )
1273         result = previous_code(PACK_START_CODE);
1274     }
1275
1276 /* Read packet and then rewind it */
1277     title = titles[current_title];
1278     if( src->is_transport_stream() && !result ) {
1279       result = read_transport();
1280
1281       if( program_byte > 0 ) {
1282         program_byte -= src->packet_size;
1283         result = seek_phys();
1284       }
1285     }
1286     else if( src->is_program_stream() && !result ) {
1287       int64_t cur_position = program_byte;
1288 /* Read packet */
1289       result = read_program();
1290 /* Rewind packet */
1291       while( program_byte > cur_position && !result ) {
1292         result = previous_code(PACK_START_CODE);
1293       }
1294     }
1295     else if( !result ) {
1296 /* Elementary stream */
1297 /* Read the packet forwards and seek back to the start */
1298       result = title->fs->read_data(zdata.buffer, src->packet_size);
1299       if( !result ) {
1300         zdata.size = src->packet_size;
1301         result = title->fs->seek(program_byte);
1302       }
1303     }
1304   } while (!result && zdata.size == 0 && (do_audio || do_video) );
1305
1306   return result;
1307 }
1308
1309 /* For audio */
1310 int zdemuxer_t::
1311 read_data(uint8_t *output, int size)
1312 {
1313   int result = 0;
1314   error_flag = 0;
1315 //zmsg("1\n");
1316
1317   if( zdata.position >= 0 ) {
1318     int count = 0;
1319 /* Read forwards */
1320     while( count<size && !result ) {
1321       int fragment_size = size - count;
1322       int len = zdata.length();
1323       if( fragment_size > len ) fragment_size = len;
1324       memcpy(output+count, zdata.buffer+zdata.position, fragment_size);
1325       zdata.position += fragment_size;
1326       count += fragment_size;
1327       if( count >= size ) break;
1328       result = read_next_packet();
1329 //zmsgs("10 offset=0x%jx pid=0x%x bytes=0x%x i=0x%x\n", 
1330 //   tell_byte(), pid, zdata.size, count);
1331     }
1332 //zmsg("10\n");
1333   }
1334   else {
1335     int cur_position = zdata.position;
1336 /* Read backwards a full packet. */
1337 /* Only good for reading less than the size of a full packet, but */
1338 /* this routine should only be used for searching for previous markers. */
1339     result = read_prev_packet();
1340     if( !result ) zdata.position = zdata.size + cur_position;
1341     memcpy(output, zdata.buffer+zdata.position, size);
1342     zdata.position += size;
1343   }
1344
1345 //zmsg("2\n");
1346   error_flag = result;
1347   return result;
1348 }
1349
1350 uint8_t zdemuxer_t::
1351 read_char_packet()
1352 {
1353   error_flag = 0;
1354   next_char = -1;
1355   if( zdata.position >= zdata.size )
1356     error_flag = read_next_packet();
1357   if( !error_flag ) 
1358     next_char = zdata.buffer[zdata.position++];
1359   return next_char;
1360 }
1361
1362 uint8_t zdemuxer_t::
1363 read_prev_char_packet()
1364 {
1365   error_flag = 0;
1366   if( --zdata.position < 0 ) {
1367     error_flag = read_prev_packet();
1368     if( !error_flag ) zdata.position = zdata.size - 1;
1369   }
1370
1371   if( zdata.position >= 0 )
1372     next_char = zdata.buffer[zdata.position];
1373   return next_char;
1374 }
1375
1376 int zdemuxer_t::
1377 open_title(int title_number)
1378 {
1379   title_t *title;
1380
1381   if( title_number<total_titles && title_number >= 0 ) {
1382     if( current_title >= 0 ) {
1383       titles[current_title]->fs->close_file();
1384       current_title = -1;
1385     }
1386     title = titles[title_number];
1387     if( title->fs->open_file() ) {
1388       error_flag = 1;
1389       perrs("%s",title->fs->path);
1390     }
1391     else
1392       current_title = title_number;
1393   }
1394   else
1395     zerrs("title_number = %d\n", title_number);
1396   return error_flag;
1397 }
1398
1399 int zdemuxer_t::
1400 copy_titles(zdemuxer_t *dst)
1401 {
1402   int i;
1403   memcpy(&dst->vstream_table[0],&vstream_table[0],sizeof(dst->vstream_table));
1404   memcpy(&dst->astream_table[0],&astream_table[0],sizeof(dst->astream_table));
1405   memcpy(&dst->sstream_table[0],&sstream_table[0],sizeof(dst->sstream_table));
1406
1407   for( i=0; i<dst->total_titles; ++i )
1408     delete dst->titles[i];
1409
1410   dst->total_titles = total_titles;
1411   for( i=0; i<total_titles; ++i ) {
1412     dst->titles[i] = new title_t(*titles[i]);
1413   }
1414
1415   if( current_title >= 0 )
1416     dst->open_title(current_title);
1417
1418   dst->title_cell = -1;
1419   return 0;
1420 }
1421
1422 void zdemuxer_t::
1423 end_title(int64_t end_byte)
1424 {
1425   if( !total_titles ) return;
1426   title_t *title = titles[total_titles-1];
1427   title->total_bytes = end_byte - title->start_byte;
1428   title->end_byte = end_byte;
1429   if( !title->cell_table_size ) return;
1430   title_t::cell_t *cell = &title->cell_table[title->cell_table_size-1];
1431   cell->title_end = title->total_bytes;
1432   cell->program_end = cell->title_end - cell->title_start + cell->program_start;
1433 }
1434
1435 /* ==================================================================== */
1436 /*                            Entry points */
1437 /* ==================================================================== */
1438
1439 zdemuxer_t::
1440 demuxer_t(zmpeg3_t *zsrc, zatrack_t *do_aud, zvtrack_t *do_vid, int cust_id)
1441 {
1442 /* The demuxer will change the default packet size for its own use. */
1443   src = zsrc;
1444   do_audio = do_aud;
1445   do_video = do_vid;
1446
1447 /* Allocate buffer + padding */
1448   raw_data = new uint8_t[RAW_SIZE];
1449   zdata.buffer = new uint8_t[zdata.allocated=RAW_SIZE];
1450   zaudio.buffer = new uint8_t[zaudio.allocated=RAW_SIZE];
1451   zvideo.buffer = new uint8_t[zvideo.allocated=RAW_SIZE];
1452
1453 /* System specific variables */
1454   audio_pid = cust_id;
1455   video_pid = cust_id;
1456   subtitle_pid = cust_id;
1457   astream = cust_id;
1458   vstream = cust_id;
1459   current_title = -1;
1460   title_cell = -1;
1461   pes_audio_time = -1.;
1462   pes_video_time = -1.;
1463 //zmsgs("%f\n", time);
1464   stream_end = -1;
1465   nav_cell_end_byte = -1;
1466 }
1467
1468 zdemuxer_t::
1469 ~demuxer_t()
1470 {
1471   int i;
1472
1473   if( current_title >= 0 )
1474     titles[current_title]->fs->close_file();
1475
1476   for( i=0; i<total_titles; ++i )
1477     delete titles[i];
1478
1479   if( zdata.buffer ) delete [] zdata.buffer;
1480   if( raw_data ) delete [] raw_data;
1481   if( zaudio.buffer ) delete [] zaudio.buffer;
1482   if( zvideo.buffer ) delete [] zvideo.buffer;
1483
1484   for( i=0; i<total_subtitles; ++i )
1485     delete subtitles[i];
1486
1487   if( nav ) delete nav;
1488 }
1489
1490 uint8_t zdemuxer_t::
1491 read_prev_char()
1492 {
1493   if( zdata.position )
1494     return zdata.buffer[--zdata.position];
1495   return read_prev_char_packet();
1496 }
1497
1498 bool zdemuxer_t::
1499 bof()
1500 {
1501   return current_title == 0 && titles[0]->fs->bof();
1502 }
1503
1504 bool zdemuxer_t::
1505 eof()
1506 {
1507   if( !src->seekable ) return zdata.eof();
1508   if( error() ) return 1;
1509   if( current_title >= total_titles ) return 1;
1510   if( current_title >= 0 && titles[current_title]->fs->eof() ) return 1;
1511   /* Same operation performed in seek_phys */
1512   return stream_end >= 0 && program_byte >= stream_end && !zdata.length();
1513 }
1514
1515 void zdemuxer_t::
1516 start_reverse()
1517 {
1518   reverse = 1;
1519 }
1520
1521 void zdemuxer_t::
1522 start_forward()
1523 {
1524   reverse = 0;
1525 }
1526
1527 /* Seek to absolute byte */
1528 int zdemuxer_t::
1529 seek_byte(int64_t byte)
1530 {
1531 /* for( int i=0; i<total_titles; ++i ) titles[i]->dump_title(); */
1532   error_flag = 0;
1533   title_cell = -1;
1534   nav_cell_end_byte = -1;
1535   program_byte = byte;
1536   zdata.position = 0;
1537   zdata.size = 0;
1538
1539   int result = seek_phys();
1540 //zmsgs("1 %p %d 0x%jx 0x%jx\n", do_video, result, byte, program_byte);
1541   return result;
1542 }
1543
1544 void zdemuxer_t::
1545 set_audio_pts(uint64_t pts, const double denom)
1546 {
1547   if( pts ) {
1548     pes_audio_pid = custom_id;
1549     pes_audio_time = pts / denom;
1550 //zmsgs("pid 0x%03x, pts %f @0x%jx\n",pes_audio_pid, pes_audio_time,
1551 //  absolute_position());
1552   }
1553 }
1554
1555 void zdemuxer_t::
1556 set_video_pts(uint64_t pts, const double denom)
1557 {
1558   if( pts ) {
1559     pes_video_pid = custom_id;
1560     pes_video_time = pts / denom;
1561 //zmsgs("pid 0x%03x, pts %f @0x%jx\n",pes_video_pid, pes_video_time,
1562 //  absolute_position());
1563   }
1564 }
1565
1566 void zdemuxer_t::
1567 reset_pts()
1568 {
1569   atrack_t *atrk = do_audio;
1570   vtrack_t *vtrk = do_video;
1571   if( !atrk && !vtrk ) {
1572     for( int i=0; !atrk && i<src->total_atracks; ++i )
1573       if( src->atrack[i]->pid == pid ) atrk = src->atrack[i];
1574     for( int i=0; !vtrk && i<src->total_vtracks; ++i )
1575       if( src->vtrack[i]->pid == pid ) vtrk = src->vtrack[i];
1576   }
1577   if( atrk ) atrk->reset_pts();
1578   if( vtrk ) vtrk->reset_pts();
1579 }
1580
1581 double zdemuxer_t::
1582 scan_pts()
1583 {
1584   int64_t start_position = tell_byte();
1585   int64_t end_position = start_position + PTS_RANGE;
1586   int64_t current_position = start_position;
1587   int result = 0;
1588
1589   reset_pts();
1590   while( !result && current_position < end_position &&
1591          ( (do_audio && pes_audio_time < 0) ||
1592            (do_video && pes_video_time < 0) ) ) {
1593     result = read_next_packet();
1594     current_position = tell_byte();
1595   }
1596
1597 /* Seek back to starting point */
1598   seek_byte(start_position);
1599
1600   if( do_audio ) return pes_audio_time;
1601   if( do_video ) return pes_video_time;
1602   zerr("no active data to scan\n");
1603   return 0;
1604 }
1605
1606 int zdemuxer_t::
1607 goto_pts(double pts)
1608 {
1609   int64_t start_position = tell_byte();
1610   int64_t end_position = start_position + PTS_RANGE;
1611   int64_t current_position = start_position;
1612   int result = 0;
1613
1614 /* Search forward for nearest pts */
1615   reset_pts();
1616   while( !result && current_position < end_position ) {
1617     result = read_next_packet();
1618     if( pes_audio_time > pts ) break;
1619     current_position = tell_byte();
1620   }
1621
1622 /* Search backward for nearest pts */
1623   end_position = current_position - PTS_RANGE;
1624   read_prev_packet();
1625   while( !result && current_position > end_position ) {
1626     result = read_prev_packet();
1627     if( pes_audio_time < pts ) break;
1628     current_position = tell_byte();
1629   }
1630   return 0;
1631 }
1632
1633 int zdemuxer_t::
1634 current_cell_no()
1635 {
1636   if( current_title < 0 || current_title >= total_titles ) return -1;
1637   title_t *title = titles[current_title];
1638   if( !title->cell_table || title_cell < 0 ) return -1;
1639   return title->cell_table[title_cell].cell_no;
1640 }
1641
1642 int64_t zdemuxer_t::
1643 absolute_to_program(int64_t byte)
1644 {
1645 //zmsgs("%d\n", zdata.size);
1646 /* Can only offset to current cell since we can't know what cell the */
1647 /* byte corresponds to. */
1648   title_t *title = titles[current_title];
1649   title_t::cell_t *cell = &title->cell_table[title_cell];
1650   return byte - cell->title_start - title->start_byte + cell->program_start;
1651 }
1652
1653 int64_t zdemuxer_t::
1654 prog2abs_fwd(int64_t byte, int64_t *nbyte, int *ntitle, int *ncell)
1655 {
1656   int ltitle = -1, lcell = -1;
1657   int64_t lbyte = -1;
1658   int ititle = current_title;
1659   int icell = title_cell;
1660   title_t *title;
1661   title_t::cell_t *cell;
1662 // check current cell first
1663   if( ititle >= 0 && ititle < total_titles ) {
1664     title = titles[ititle];
1665     if( icell >= 0 && icell < title->cell_table_size ) {
1666       cell = &title->cell_table[icell];
1667       if( byte >= cell->program_start && byte < cell->program_end ) goto xit;
1668     }
1669   }
1670
1671   for( ititle=0; ititle<total_titles; ++ititle ) {
1672 // check all title cells
1673     title = titles[ititle];
1674     int ncells = title->cell_table_size;
1675     if( ncells <= 0 ) continue;
1676     if( byte >= title->cell_table[ncells-1].program_end ) continue;
1677     for( icell=0; icell<ncells; ++icell ) {
1678       cell = &title->cell_table[icell];
1679       if( byte < cell->program_end ) goto xit;
1680       if( lbyte > cell->program_end ) continue;
1681       lbyte = cell->program_end;
1682       ltitle = ititle;  lcell = icell;
1683     }
1684   }
1685 // not found, return search region boundry
1686   if( nbyte ) *nbyte = lbyte;
1687   if( ntitle ) *ntitle = ltitle;
1688   if( ncell ) *ncell = lcell;
1689   return total_titles>0 ? titles[total_titles-1]->end_byte : -1;
1690
1691 xit:
1692   if( byte < cell->program_start ) byte = cell->program_start;
1693   if( nbyte ) *nbyte = byte;
1694   if( ntitle ) *ntitle = ititle;
1695   if( ncell ) *ncell = icell;
1696   return title->start_byte + cell->title_start + byte - cell->program_start;
1697 }
1698
1699 int64_t zdemuxer_t::
1700 prog2abs_rev(int64_t byte, int64_t *nbyte, int *ntitle, int *ncell)
1701 {
1702   int ititle = current_title;
1703   int icell = title_cell;
1704   title_t *title;
1705   title_t::cell_t *cell;
1706 // check current cell first
1707   if( ititle >= 0 && ititle < total_titles ) {
1708     title = titles[ititle];
1709     if( icell >= 0 && icell < title->cell_table_size ) {
1710       cell = &title->cell_table[icell];
1711       if( byte > cell->program_start && byte <= cell->program_end ) goto xit;
1712     }
1713   }
1714
1715   for( ititle=total_titles; --ititle>=0; ) {
1716 // check all title cells
1717     title = titles[ititle];
1718     int ncells = title->cell_table_size;
1719     if( ncells <= 0 ) continue;
1720     if( byte < title->cell_table[0].program_start ) continue;
1721     for( icell=ncells; --icell>=0; ) {
1722       cell = &title->cell_table[icell];
1723       if( byte > cell->program_start ) goto xit;
1724     }
1725   }
1726 // not found, return search region boundry
1727   if( nbyte ) *nbyte = 0;
1728   if( ntitle ) *ntitle = 0;
1729   if( ncell ) *ncell = 0;
1730   return 0;
1731
1732 xit:
1733   if( byte > cell->program_end ) byte = cell->program_end;
1734   if( nbyte ) *nbyte = byte;
1735   if( ntitle ) *ntitle = ititle;
1736   if( ncell ) *ncell = icell;
1737   return title->start_byte + cell->title_start + byte - cell->program_start;
1738 }
1739
1740 int64_t zdemuxer_t::
1741 program_to_absolute(int64_t byte, int64_t *nbyte, int *ntitle, int *ncell)
1742 {
1743   return !reverse ?
1744     prog2abs_fwd(byte, nbyte, ntitle, ncell) :
1745     prog2abs_rev(byte, nbyte, ntitle, ncell) ;
1746 }
1747
1748 int64_t zdemuxer_t::
1749 movie_size()
1750 {
1751   if( !total_bytes ) {
1752     int64_t result = 0;
1753     int i, j;
1754     for( i=0; i<total_titles; ++i ) {
1755       title_t *title = titles[i];
1756       if( title->cell_table ) {
1757         for( j=0; j<title->cell_table_size; ++j ) {
1758           title_t::cell_t *cell = &title->cell_table[j];
1759 /*        result = cell->program_end - cell->program_start; */
1760           if( result < cell->program_end ) result = cell->program_end;
1761         }
1762       }
1763 /*    result += titles[i]->total_bytes; */
1764     }
1765     total_bytes = result;
1766   }
1767   return total_bytes;
1768 }
1769
1770 int64_t zdemuxer_t::
1771 next_cell()
1772 {
1773   if( current_title < 0 || current_title >= total_titles ) return -1;
1774   int i = current_title;
1775   if( !titles[i]->cell_table || title_cell < 0 ) return -1;
1776   int k = title_cell;
1777   int n = titles[i]->cell_table[k].cell_no;
1778
1779   /* always forward search, stop when cell_no changes */
1780   while ( i < total_titles && titles[i]->cell_table[k].cell_no == n ) {
1781     ++k;
1782     /* some titles have no cells (may be another program) */
1783     while( !titles[i]->cell_table || k >= titles[i]->cell_table_size ) {
1784       if( ++i >= total_titles ) break;
1785       k = 0;
1786     }
1787   }
1788
1789   return  i < total_titles ? titles[i]->cell_table[k].program_start : movie_size();
1790 }
1791
1792 int64_t zdemuxer_t::
1793 playinfo_next_cell()
1794 {
1795   int64_t result = -1;
1796   int i = title_cell;
1797   int pcell_no = titles[current_title]->cell_table[i++].cell_no;
1798
1799   for( int n=current_title ; result<0 && n<total_titles; ++n ) {
1800     title_t *title = titles[n];
1801     for( ; result<0 && i<title->cell_table_size; ++i ) {
1802       if( title->cell_table[i].cell_no != pcell_no )
1803          result = title->cell_table[i].program_start;
1804     }
1805     i = 0;
1806   }
1807
1808   return result;
1809 }
1810
1811 int64_t zdemuxer_t::
1812 title_bytes()
1813 {
1814   title_t *title = titles[current_title];
1815   return title->total_bytes;
1816 }
1817
1818 void zdemuxer_t::
1819 append_data(uint8_t *data, int bytes)
1820 {
1821   if( bytes <= 0 ) return;
1822   int new_data_size = zdata.size + bytes;
1823   if( zdata.size + new_data_size >= zdata.allocated ) {
1824     zdata.allocated = (zdata.size + new_data_size) * 2;
1825     uint8_t *new_data_buffer = new uint8_t[zdata.allocated];
1826     memcpy(new_data_buffer,zdata.buffer,zdata.size);
1827     delete [] zdata.buffer;
1828     zdata.buffer = new_data_buffer;
1829   }
1830
1831   memcpy(zdata.buffer+zdata.size, data, bytes);
1832   zdata.size += bytes;
1833 }
1834
1835 void zdemuxer_t::
1836 shift_data()
1837 {
1838   if( zdata.position <= 0 ) return;
1839   memmove(zdata.buffer,
1840           zdata.buffer+zdata.position,
1841           zdata.size-zdata.position);
1842   zdata.size -= zdata.position;
1843   zdata.position = 0;
1844 }
1845
1846 /* Create a title and get PID's by scanning first few bytes. */
1847 int zdemuxer_t::
1848 create_title(int full_scan)
1849 {
1850   int debug = 0;
1851
1852   error_flag = 0;
1853   read_all = 1;
1854
1855 /* Create a single title */
1856   if( !total_titles ) {
1857     titles[0] = new title_t(src);
1858     total_titles = 1;
1859     open_title(0);
1860   }
1861
1862   title_t *title = titles[0];
1863   title->total_bytes = title->fs->ztotal_bytes();
1864   title->start_byte = 0;
1865   title->end_byte = title->total_bytes;
1866   if( debug )
1867     zmsgs("%d path=%s total_bytes=%jd\n",
1868       __LINE__, src->fs->path, title->total_bytes);
1869
1870 /* Create default cell */
1871   if( !title->cell_table_size )
1872           title->new_cell(title->end_byte);
1873
1874 /* Get PID's and tracks */
1875   if( src->is_transport_stream() || src->is_program_stream() ) {
1876     title->fs->seek(START_BYTE);
1877     int64_t next_byte = START_BYTE;
1878     int64_t last_time_pos = next_byte;
1879     // only spend a few seconds on this
1880     struct timeval tv;
1881     gettimeofday(&tv,NULL);
1882     double start_time = tv.tv_sec + tv.tv_usec/1000000.0;
1883     while( !title->fs->eof() ) {
1884       if( read_next_packet() ) break;
1885       next_byte = title->fs->tell();
1886 #ifdef ZDVB
1887       if( src->is_transport_stream() ) {
1888         src->dvb.atsc_tables(this, custom_id);
1889       }
1890 #endif
1891       if( full_scan ) continue;
1892       if( src->is_transport_stream() ) {
1893         if( next_byte > START_BYTE + MAX_TS_PROBE ) break;
1894 #ifdef ZDVB
1895         if( src->dvb.signal_time() > 3 ) break;
1896 #endif
1897       }
1898       else if( src->is_program_stream() )
1899         if( next_byte > START_BYTE + MAX_PGM_PROBE ) break;
1900       if( next_byte - last_time_pos > 0x40000 ) {
1901         gettimeofday(&tv,NULL);
1902         double next_time = tv.tv_sec + tv.tv_usec/1000000.0;
1903         if( next_time - start_time > 3 ) break;
1904         last_time_pos = next_byte;
1905       }
1906     }
1907   }
1908 #ifdef ZDVB
1909   if( src->is_transport_stream() )
1910     src->dvb.read_dvb(this);
1911 #endif
1912   title->fs->seek(START_BYTE);
1913   read_all = 0;
1914   return 0;
1915 }
1916
1917 void zdemuxer_t::
1918 skip_video_frame()
1919 {
1920   uint32_t header = 0;
1921   title_t *title = titles[current_title];
1922
1923   do {
1924     header <<= 8;
1925     header &= 0xffffffff;
1926     header |= title->fs->read_char();
1927   } while( header != PICTURE_START_CODE && !title->fs->eof() );
1928 /*
1929  *  if(!mpeg3io_eof(title->fs))
1930  *    mpeg3io_seek_relative(title->fs, -4);
1931  */
1932   src->last_type_read = 2;
1933 }
1934