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