rework keyframe hide popup, keyframe auto render, textbox set_selection wide text
[goodguy/history.git] / cinelerra-5.1 / libzmpeg3 / libzmpeg3.h
1 #ifndef LIBMPEG3_H
2 #define LIBMPEG3_H
3
4 /* for quicktime build */
5 #define MAXFRAMESAMPLES 65536
6 #define ZDVB
7 #define USE_FUTEX
8
9 #include <stdio.h>
10 #define __STDC_LIMIT_MACROS
11 #include <stdint.h>
12
13 typedef int (*zthumbnail_cb)(void *p, int trk);
14 typedef int (*zcc_text_cb)(int sid, int id, int sfrm, int efrm, const char *txt);
15
16 #ifdef __cplusplus
17 #include <unistd.h>
18 #include <stdlib.h>
19 #include <byteswap.h>
20 #include <dirent.h>
21 #include <fcntl.h>
22 #include <string.h>
23 #include <limits.h>
24 #include <errno.h>
25 #include <endian.h>
26 #include <signal.h>
27 #include <pthread.h>
28 #include <mntent.h>
29 #include <linux/cdrom.h>
30 #include <sys/ioctl.h>
31 #include <sys/stat.h>
32 #include <sys/types.h>
33 #include <sys/time.h>
34 #include <sys/syscall.h>
35 #ifdef USE_FUTEX
36 #include <linux/futex.h>
37 #endif
38
39 extern "C" {
40 #include "a52dec-0.7.3/include/a52.h"
41 }
42
43 #define ZMPEG3_MAJOR   2
44 #define ZMPEG3_MINOR   0
45 #define ZMPEG3_RELEASE 0
46 #define ZRENDERFARM_FS_PREFIX "vfs://"
47
48 #define ZIO_SINGLE_ACCESS zfs_t::io_SINGLE_ACCESS
49 #define ZIO_UNBUFFERED zfs_t::io_UNBUFFERED
50 #define ZIO_NONBLOCK zfs_t::io_NONBLOCK
51 #define ZIO_SEQUENTIAL zfs_t::io_SEQUENTIAL
52 #define ZIO_THREADED zfs_t::io_THREADED
53 #define ZIO_ERRFAIL zfs_t::io_ERRFAIL
54 #define ZIO_RETRIES 1
55
56 #define TOC_SAMPLE_OFFSETS zmpeg3_t::show_toc_SAMPLE_OFFSETS
57 #define TOC_AUDIO_INDEX zmpeg3_t::show_toc_AUDIO_INDEX
58 #define TOC_FRAME_OFFSETS zmpeg3_t::show_toc_FRAME_OFFSETS
59
60 #define ZMPEG3_PROC_CPUINFO "/proc/cpuinfo"
61 #if BYTE_ORDER == LITTLE_ENDIAN
62 #define ZMPEG3_LITTLE_ENDIAN 1
63 #else
64 #define ZMPEG3_LITTLE_ENDIAN 0
65 #endif
66
67 // Combine the pid and the stream id into one unit
68 #define CUSTOM_ID(pid, stream_id) (((pid << 8) | stream_id) & 0xffff)
69 #define CUSTOM_ID_PID(id) (id >> 8)
70 #define CUSTOM_ID_STREAMID(id) (id & 0xff)
71
72 #ifndef ZMAX
73 #define ZMAX(a, b) ((a) > (b) ? (a) : (b))
74 #endif
75
76 #ifndef ZMIN
77 #define ZMIN(a, b) ((a) < (b) ? (a) : (b))
78 #endif
79
80 #ifndef isizeof
81 #define isizeof(x) ((int)sizeof(x))
82 #endif
83 #ifndef lengthof
84 #define lengthof(x) ((int)(sizeof(x)/sizeof(x[0])))
85 #endif
86
87 #define zlikely(x)   __builtin_expect((x),1)
88 #define zunlikely(x) __builtin_expect((x),0)
89
90 #if defined(__x86_64__)
91 #define _LD "%ld"
92 #define _LDv(v) "%" #v "ld"
93 #define _LU "%lu"
94 #define _LUv(v) "%" #v "lu"
95 #define _LX "%lx"
96 #define _LXv(v) "%" #v "lx"
97 #else
98 #define _LD "%lld"
99 #define _LDv(v) "%" #v "lld"
100 #define _LU "%llu"
101 #define _LUv(v) "%" #v "llu"
102 #define _LX "%llx"
103 #define _LXv(v) "%" #v "llx"
104 #endif
105 #define bcd(n) ((((n)>>4)&0x0f)*10+((n)&0x0f))
106
107 #define new_memset(s) \
108   void *operator new(size_t n) { \
109     void *t = (void*) new char[n]; \
110     memset(t,s,n); \
111     return t; \
112   } \
113   void operator delete(void *t,size_t n) { \
114     delete[](char*)t; \
115   } \
116   void *operator new[](size_t n) { \
117     void *t = (void*) new char[n]; \
118     memset(t,s,n); \
119     return t; \
120   } \
121   void operator delete[](void *t,size_t n) { \
122     delete[](char*)t; \
123   }
124
125 #define znew(T,n) ((T*)memset(new T[n],0,(n)*sizeof(T)))
126 #define zmsg(fmt) printf("%s: " fmt, __func__)
127 #define zmsgs(fmt,args...) printf("%s: " fmt, __func__, args)
128 #define zerr(fmt) fprintf(stderr,"%s:err " fmt, __func__)
129 #define zerrs(fmt,args...) fprintf(stderr,"%s:err " fmt, __func__, args)
130 #define perr(fmt) do { char msg[512]; \
131  snprintf(&msg[0],sizeof(msg), "%s: " fmt,__func__); perror(&msg[0]); \
132 } while(0)
133 #define perrs(fmt,args...) do { char msg[512]; \
134  snprintf(&msg[0],sizeof(msg), "%s: " fmt,__func__,args); perror(&msg[0]); \
135 } while(0)
136
137 class zmpeg3_t;
138
139 class zmpeg3_t {
140 public:
141   new_memset(0);
142   class zlock_t;
143   class zblock_t;
144   class zrwlock_t;
145   class fs_t;
146   class bits_t;
147   class index_t;
148   class bitfont_t;
149   class timecode_t;
150   class audio_t;
151   class slice_buffer_t;
152   class video_t;
153   class slice_decoder_t;
154   class subtitle_t;
155   class demuxer_t;
156   class cacheframe_t;
157   class cache_t;
158   class atrack_t;
159   class vtrack_t;
160   class strack_t;
161 #ifdef ZDVB
162   class dvb_t;
163 #endif
164
165   enum {
166     // Error codes for the error_return variable
167     ERR_UNDEFINED_ERROR              = 1,
168     ERR_INVALID_TOC_VERSION          = 2,
169     ERR_TOC_DATE_MISMATCH            = 3,
170
171     TOC_PREFIX                       = 0x544f4320,
172     // This decreases with every new version
173     TOC_VERSION                      = 0x000000f9,
174     ID3_PREFIX                       = 0x494433,
175     IFO_PREFIX                       = 0x44564456,
176     // First byte to read when opening a file
177     START_BYTE                       = 0x0,
178     // Bytes read by mpeg3io at a time
179     MAX_IO_SIZE                      = 0x10000,
180     IO_SIZE                          = 0x80000,
181     SEQ_IO_SIZE                      = 0xc00000,
182     MAX_TS_PROBE                     = 0x800000,
183     MAX_PGM_PROBE                    = 0x800000,
184     // Largest possible packet
185     RAW_SIZE                         = 0x400000,
186     RIFF_CODE                        = 0x52494646,
187     BD_PACKET_SIZE                   = 192,
188     TS_PACKET_SIZE                   = 188,
189     DVD_PACKET_SIZE                  = 0x800,
190     ERR_PACKET_SIZE                  = 0x800,
191     IO_ERR_LIMIT                     = 2,
192     SYNC_BYTE                        = 0x47,
193     PROGRAM_END_CODE                 = 0x000001b9,
194     PACK_START_CODE                  = 0x000001ba,
195     SEQUENCE_START_CODE              = 0x000001b3,
196     SEQUENCE_END_CODE                = 0x000001b7,
197     SYSTEM_START_CODE                = 0x000001bb,
198     STRLEN                           = 1024,
199     // Maximum number of PIDs in one stream
200     PIDMAX                          = 256,
201     PROGRAM_ASSOCIATION_TABLE       = 0x00,
202     CONDITIONAL_ACCESS_TABLE        = 0x01,
203     PACKET_START_CODE_PREFIX        = 0x000001,
204     // NAV/PRIVATE_STREAM_2 are the same id
205     PRIVATE_STREAM_2                = 0xbf,
206     NAV_PACKET_STREAM               = 0xbf,
207     NAV_PCI_BYTES                   = 0x3d3,
208     NAV_DSI_BYTES                   = 0x3f9,
209     NAV_PCI_SSID                    = 0x00,
210     NAV_DSI_SSID                    = 0x01,
211     NAV_SRI_END_OF_CELL             = 0x3fffffff,
212     PADDING_STREAM                  = 0xbe,
213     GOP_START_CODE                  = 0x000001b8,
214     PICTURE_START_CODE              = 0x00000100,
215     EXT_START_CODE                  = 0x000001b5,
216     USER_START_CODE                 = 0x000001b2,
217     SLICE_MIN_START                 = 0x00000101,
218     SLICE_MAX_START                 = 0x000001af,
219     AC3_START_CODE                  = 0x0b77,
220     PCM_START_CODE                  = 0x7f7f807f,
221     MAX_CPUS                        = 256,
222     MAX_STREAMZ                     = 0x10000,
223     MAX_PACKSIZE                    = 262144,
224     MAX_CACHE_FRAMES                = 128,
225     // Maximum number of complete subtitles to buffer in a subtitle track
226     // or number of incomplete subtitles to buffer in demuxer.
227     MAX_SUBTITLES                   = 16,
228     // Positive difference before declaring timecodes discontinuous
229     CONTIGUOUS_THRESHOLD            = 10  ,
230     // Minimum number of seconds before interleaving programs
231     PROGRAM_THRESHOLD               = 5   ,
232     // Number of frames difference before absolute seeking
233     SEEK_THRESHOLD                  = 16  ,
234     // Size of chunk of audio in table of contents
235     AUDIO_CHUNKSIZE                 = 0x10000 ,
236     // Minimum amount of data required to read a video header in streaming mode.
237     VIDEO_STREAM_SIZE               = 0x100,
238     // Number of samples in audio history
239     AUDIO_HISTORY                   = 0x100000 ,
240     // max number of samples returned by decoder per input frame
241     AUDIO_MAX_DECODE                = 0x800 ,
242     // Range to scan for pts after byte seek
243     PTS_RANGE                       = 0x100000,
244     // stream type
245     FT_PROGRAM_STREAM               = 0x0001,
246     FT_TRANSPORT_STREAM             = 0x0002,
247     FT_AUDIO_STREAM                 = 0x0004,
248     FT_VIDEO_STREAM                 = 0x0008,
249     FT_IFO_FILE                     = 0x0010,
250     FT_BD_FILE                      = 0x0020,
251     SUBTITLE_HOLD_TIME              = 3,
252     CCAPTION_HOLD_TIME              = 15,
253   };
254
255   enum color_model {
256     // All color models supported for read_frame
257     cmdl_BGR888=0,
258     cmdl_BGRA8888=1,
259     cmdl_RGB565=2,
260     cmdl_RGB888=3,
261     cmdl_RGBA8888=4,
262     cmdl_RGBA16161616=5,
263     // Color models for the 601 to RGB conversion
264     // 601 not implemented for scalar code
265     cmdl_601_BGR888=7,
266     cmdl_601_BGRA8888=8,
267     cmdl_601_RGB888=9,
268     cmdl_601_RGBA8888=10,
269     cmdl_601_RGB565=11,
270     // next 2 are supported color models for read_yuvframe
271     //  also YVU420P/YVU422P with uv output_row ptrs reversed for read_frame
272     cmdl_YUV420P=12,
273     cmdl_YUV422P=13,
274     // the rest are supported color models for read_frame
275     cmdl_601_YUV420P=14,
276     cmdl_601_YUV422P=15,
277     cmdl_UYVY=16,
278     cmdl_YUYV=17,
279     cmdl_601_UYVY=18,
280     cmdl_601_YUYV=19,
281     cmdl_YUV888=20,
282     cmdl_YUVA8888=21,
283     cmdl_601_YUV888=22,
284     cmdl_601_YUVA8888=23,
285   };
286
287   // Values for audio input/output formats
288   enum audio_format {
289     afmt_IGNORE=-1,
290     afmt_UNKNOWN=0,
291     afmt_MPEG=1,
292     afmt_AC3=2,
293     afmt_PCM=3,
294     afmt_AAC=4,
295     afmt_JESUS=5,
296
297     atyp_NONE=0,
298     atyp_DOUBLE=1,
299     atyp_FLOAT=2,
300     atyp_INT=3,
301     atyp_SHORT=4,
302   };
303
304   // Table of contents sections
305   enum toc_section_type {
306     toc_FILE_TYPE_PROGRAM=0,
307     toc_FILE_TYPE_TRANSPORT=1,
308     toc_FILE_TYPE_AUDIO=2,
309     toc_FILE_TYPE_VIDEO=3,
310     toc_STREAM_AUDIO=4,
311     toc_STREAM_VIDEO=5,
312     toc_STREAM_SUBTITLE=6,
313     toc_OFFSETS_AUDIO=7,
314     toc_OFFSETS_VIDEO=8,
315     toc_ATRACK_COUNT=9,
316     toc_VTRACK_COUNT=10,
317     toc_STRACK_COUNT=11,
318     toc_TITLE_PATH=12,
319     toc_IFO_PALETTE=13,
320     toc_FILE_INFO=14,
321     toc_IFO_PLAYINFO=15,
322     toc_SRC_PROGRAM=16,
323   };
324
325
326 #ifdef USE_FUTEX
327 #define ZMPEG3_ZLOCK_INIT zzlock_t()
328   class zloc_t {
329   protected:
330     volatile int loc;
331     int zfutex(int op, int val, timespec *time=0) {
332       return syscall(SYS_futex,&loc,op,val,time,0,0);
333     }
334     int zyield();
335     int zgettid();
336   public:
337     int zwake(int nwakeups);
338     int zwait(int val);
339     int zwait() { return zwait(loc); }
340     static void zincr(volatile int &v) { /* atomic(++v) */
341       asm ( " lock incl %1\n" : "+m" (v) :: );
342     }
343     static void zdecr(volatile int &v) { /* atomic(--v) */
344       asm ( " lock decl %1\n" : "+m" (v) :: );
345     }
346     static char tdecr(volatile int &v) {
347       char ret; /* ret = atomic(--loc >= 0 ? 1 : 0) */
348       asm ( " lock decl %1\n setge %0\n" : "=r" (ret), "+m" (v) :: );
349       return ret;
350     }
351     static char tincr(volatile int &v) {
352       char ret; /* ret = atomic(++loc > 0 ? 1 : 0) */
353       asm ( " lock incl %1\n setg %0\n" : "=r" (ret), "+m" (v) :: );
354       return ret;
355     }
356     static int zcmpxchg(int old, int val, volatile int &v) {
357       int ret = old;
358       asm volatile( " lock\n cmpxchgl %2,%1\n"
359         : "+a" (ret), "+m" (v) :  "r" (val) : "memory" );
360       return ret;
361     }
362     static int zxchg(int val, volatile int &v) {
363       asm volatile( " xchgl %0,%1\n"
364         : "+r" (val), "+m" (v) :: "memory" );
365       return val;
366     }
367     static int zadd(int n, volatile int &v) {
368       int old, mod, val;
369       do { val = (old=v)+n; mod = zcmpxchg(old,val,v);
370       } while( mod != old );
371       return val;
372     }
373     static void zmfence() {
374       asm volatile ( " mfence\n" ::: "memory" );
375     }
376
377     zloc_t() : loc(-1) {}
378     ~zloc_t() {}
379   };
380
381   class zlock_t : zloc_t {
382   protected:
383     friend class zblock_t;
384     friend class zrwlock_t;
385     int zlock(int v);
386     int zunlock(int nwakeups=1);
387     static int zemsg1();
388   public:
389     int lock() {
390       int v, ret = zunlikely( (v=zcmpxchg(-1,0,loc)) >= 0 ) ? zlock(v) : 0;
391       return ret;
392     }
393     int unlock() {
394       if( zunlikely(loc < 0) ) { return zemsg1(); }
395       int v, ret = zunlikely( (v=zcmpxchg(0,-1,loc)) != 0 ) ? zunlock() : 0;
396       return ret;
397     }
398     zlock_t() {}
399     ~zlock_t() {}
400   };
401
402   class zblock_t : zlock_t {
403   public:
404     void block() { loc = 0; zwait(0); }
405     void unblock() { if( !loc ) { loc = -1; zwake(INT_MAX); } }
406     zblock_t() {}
407     ~zblock_t() {}
408   };
409
410   class zrwlock_t : zloc_t {
411     zlock_t lk;
412     void zenter();
413     void zleave();
414     void zwrite_enter(int r); // r==0: do nothing, r>0: write_lock
415     void zwrite_leave(int r); // r<0: write_lock while read_lock
416   public:
417     void enter() { zincr(loc); if( zunlikely( lk.loc >= 0 ) ) zenter(); }
418     void leave() { if( zunlikely( !tdecr(loc) ) ) zleave(); }
419     void write_enter(int r=1) { if( r ) zwrite_enter(r); }
420     void write_leave(int r=1) { if( r ) zwrite_leave(r); }
421     zrwlock_t() {}
422     ~zrwlock_t() {}
423   };
424
425 #else
426 #define ZMPEG3_ZLOCK_INIT { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER }
427
428   class zlock_t {
429   protected:
430     pthread_mutex_t zlock;
431   public:
432     void lock() { pthread_mutex_lock(&zlock); }
433     void unlock() { pthread_mutex_unlock(&zlock); }
434     zlock_t() { pthread_mutex_init(&zlock, 0); }
435     ~zlock_t() { pthread_mutex_destroy(&zlock); }
436   };
437
438   class zblock_t {
439     pthread_mutex_t zblock;
440     pthread_cond_t cond;
441   public:
442     zblock_t() {
443       pthread_mutex_init(&zblock, 0);
444       pthread_cond_init(&cond, 0);
445     }
446     ~zblock_t() {
447       pthread_mutex_destroy(&zblock);
448       pthread_cond_destroy(&cond);
449     }
450     void block() {
451       pthread_mutex_lock(&zblock);
452       pthread_cond_wait(&cond, &zblock);
453       pthread_mutex_unlock(&zblock);
454     }
455     void unblock() { pthread_cond_broadcast(&cond); }
456   };
457
458   class zrwlock_t : zlock_t {
459     volatile pthread_t blocking;
460     volatile int users;
461     zlock_t lk;
462     pthread_cond_t cond;
463     void wait() { pthread_cond_wait(&cond, &zlock); }
464     void wake() { pthread_cond_signal(&cond); }
465     void zwrite_enter(int r);
466     void zwrite_leave(int r);
467   public:
468     void enter();
469     void leave();
470     void write_enter(int r=1) { if( r ) zwrite_enter(r); }
471     void write_leave(int r=1) { if( r ) zwrite_leave(r); }
472     int count() { return users; }
473
474     zrwlock_t() { pthread_cond_init(&cond, 0); }
475     ~zrwlock_t() { pthread_cond_destroy(&cond); }
476   };
477
478 #endif
479
480   // I/O
481
482   // Filesystem structure
483   // We buffer in IO_SIZE buffers.  Stream IO would require back
484   // buffering a buffer since the stream must be rewound for packet headers,
485   // sequence start codes, format parsing, decryption, and mpeg3cat.
486
487   class fs_t {
488     int sync() {
489       return buffer->sync(current_byte);
490     }
491     int enter() {
492       buffer->lock();
493       return sync();
494     }
495     void leave() {
496       buffer->unlock();
497     }
498   public:
499     new_memset(0);
500     class css_t;
501
502     class css_t { // Encryption object
503     public:
504       class playkey_t;
505       class keytext_t;
506
507       typedef uint8_t key_t[5];
508       typedef uint8_t blk_t[5];
509       class playkey_t {
510       public:
511         int offset;
512         key_t key;
513       };
514       class keytext_t {
515       public:
516         keytext_t *lt, *rt;
517         uint8_t ktxt[4], ctxt[10];
518         keytext_t(const uint8_t *kp, const uint8_t *cp) {
519           lt = rt = 0;
520           memcpy(&ktxt[0],kp,sizeof(ktxt));
521           memcpy(&ctxt[0],cp,sizeof(ctxt));
522         }
523         ~keytext_t() {}
524       } *key_root;
525       void add_key_text(const uint8_t *kp, const uint8_t *cp);
526       uint8_t *find_key_text(const uint8_t *kp);
527       int attack_pattern(uint8_t const *sec, uint8_t *key);
528       void del_keytexts(keytext_t *p);
529     private:
530       void css_engine(int v,uint8_t const *input, blk_t &output);
531       void crypt_key1(int v, blk_t &key);
532       void crypt_key2(blk_t &key);
533       void crypt_bus_key(blk_t &key);
534       int get_asf();
535       int authenticate_drive(key_t &key);
536       int hostauth(dvd_authinfo *ai);
537       int get_title_key(key_t &key);
538       int get_disk_key(key_t &key);
539       int validate(int do_title);
540       int validate_path(int do_title);
541       int decrypt_title_key(uint8_t *dkey, uint8_t *tkey);
542     public:
543       key_t key1;
544       key_t key2;
545       key_t keycheck;
546       key_t title_key;
547       int lba, fsz, agid, encrypted;
548       char device_path[STRLEN];    // Device where the file is located
549       uint8_t disk_key[DVD_PACKET_SIZE];
550       char challenge[10];
551       int varient;
552       int fd;
553       char path[STRLEN];
554
555       css_t();
556       ~css_t();
557
558       int get_keys(char *fpath);
559       int decrypt_packet(uint8_t *sector, int offset);
560       int crack_title_key(key_t &ckey, key_t &tkey);
561     } css;
562
563     enum access_strategy {
564       io_SINGLE_ACCESS=1,
565       io_UNBUFFERED=2,
566       io_NONBLOCK=4,
567       io_SEQUENTIAL=8,
568       io_THREADED=16,
569       io_ERRFAIL=32,
570     };
571
572     class buffer_t {
573       void unblock();
574       void block();
575       void reader();
576       static void *reader(void *the_buffer);
577       void writer();
578       static void *writer(void *the_buffer);
579       int64_t read_in(int64_t len);
580       int read_fin(int64_t len);
581       int wait_in(int64_t pos);
582       int seek_in(int64_t pos);
583       int seek_to(int64_t pos, int64_t len);
584       int read_to(int64_t pos);
585       zmpeg3_t *src;
586       zlock_t io_lock;          // buffer_t access lock
587       zblock_t io_block;        // buffer_t access block
588       int errs;                 // number of consecutive errors
589       uint8_t *data;            // Readahead buffer
590       int alloc;                // buffer byte allocate
591       int size;                 // defined bytes in buffer
592       int in;                   // buffer byte in, owned by read_in
593       int out;                  // buffer byte out
594       int64_t out_pos;          // file offset next byte from last read
595       int64_t file_pos;         // file position of next readable byte
596       int64_t file_nudge;       // sync position offset
597       int fin;                  // locked version of in, synced with file_pos
598       pthread_t the_reader;     // reader thread if io_THREADED
599       pthread_t the_writer;     // writer thread if io_THREADED and recording
600       pthread_t owner;          // for debugging
601       int restarted;            // reader restarted
602       int reader_done;          // reader thread termination flag
603       int writer_done;          // writer thread termination flag
604       int wout;                 // write record file buffer byte out
605       int64_t write_pos;        // file_pos written to recd_fd
606       zblock_t write_lock;      // write record block
607     public:
608       new_memset(0);
609       buffer_t(zmpeg3_t *zsrc, int access);
610       ~buffer_t();
611       int access_type;          // io_ flags
612       int paused;               // reader discard data
613       int do_restart;           // reader restart buffer
614       int ref_count;            // number of fs_t referencing this
615       int open_count;           // number of is_open fs_t
616       int fd;                   // unbuffered file descriptor
617       FILE *fp;                 // buffered file handle
618       int open_file(char *path);
619       void close_file();
620       void reset();
621       void restart(int lk=1);
622       int64_t tell() { return out_pos; }
623       int64_t file_tell() { return file_pos; }
624       int sync(int64_t pos);
625       int errors() { return errs; }
626       uint32_t next_byte() {
627         return data[out];
628       }
629       uint32_t get_byte() {
630         uint32_t result = next_byte();
631         if( ++out >= alloc ) out = 0;
632         ++out_pos;
633         return result;
634       }
635       int read_out(uint8_t *bfr,int len);
636       int get_fd() {
637         return (access_type & io_UNBUFFERED) ? fd : fileno(fp);
638       }
639       void lock() {
640         if( (access_type & io_SINGLE_ACCESS) )
641           io_lock.lock();
642         if( !data ) data = new uint8_t[alloc];
643       }
644       void unlock() {
645         if( (access_type & io_SINGLE_ACCESS) )
646           io_lock.unlock();
647       }
648       void start_reader();
649       void stop_reader();
650       int start_record();
651       int stop_record();
652       int write_align(int sz);
653       void write_record(int sz, int mask);
654     } *buffer;
655
656     zmpeg3_t *src;
657     char path[STRLEN];
658     int64_t current_byte;       // Hypothetical position of file pointer
659     int64_t total_bytes;
660     int is_open;
661
662     fs_t(zmpeg3_t *zsrc, const char *fpath, int access=io_UNBUFFERED+io_SINGLE_ACCESS);
663     fs_t(zmpeg3_t *zsrc, int fd, int access=io_UNBUFFERED+io_SINGLE_ACCESS);
664     fs_t(zmpeg3_t *zsrc, FILE *fp, int access=io_SINGLE_ACCESS);
665     fs_t(fs_t &fs);
666     ~fs_t();
667     int open_file();
668     void close_file();
669     int errors() { return buffer ? buffer->errors() : 0; }
670     int get_fd() { return buffer ? buffer->get_fd() : -1; }
671     int read_data(uint8_t *bfr, int64_t len);
672     uint8_t next_char();
673     uint8_t read_char();
674     uint32_t read_uint16();
675     uint32_t read_uint24();
676     uint32_t read_uint32();
677     uint64_t read_uint64();
678     int seek(int64_t byte);
679     int seek_relative(int64_t bytes);
680     int64_t tell() { return current_byte; }
681     int64_t eof() { return current_byte >= total_bytes; }
682     int64_t bof() { return current_byte < 0; }
683     int64_t get_total_bytes();
684     int64_t ztotal_bytes() { return total_bytes; }
685     void chk_next() {
686       if( ++current_byte >= buffer->file_tell() ) sync();
687     }
688     void restart();
689     int pause_reader(int v);
690     int access() { return !buffer ? 0 : buffer->access_type; }
691     void sequential() { buffer->access_type |= io_SEQUENTIAL; }
692     int start_record(int bsz);
693     int stop_record();
694     void attach(fs_t *zfs);
695     void detach();
696     void close_buffer();
697   };
698
699
700   // Bitstream                                      
701   //    next bit in forward direction               
702   //  next bit in reverse direction |               
703   //                              v v               
704   // ... | | | | | | | | |1|1|1|1|1|1|              
705   //                     ^         ^                
706   //                     |         bit_number = 1   
707   //                     bfr_size = 6               
708
709   class bits_t {
710   public:
711     new_memset(0);
712     zmpeg3_t *src;
713     uint32_t bfr;   // bfr = buffer for bits
714     int bit_number; // position of pointer in bfr
715     int bfr_size;   // number of bits in bfr.  Should always be a multiple of 8
716     demuxer_t *demuxer; // Mpeg2 demuxer
717     uint8_t *input_ptr; // when input_ptr!=0, data is read from it instead of the demuxer.
718
719     bits_t(zmpeg3_t *zsrc, demuxer_t *demux);
720     ~bits_t();
721     int read_buffer(uint8_t *buffer, int byte);
722     void use_ptr(uint8_t *buffer);
723     int eos(uint8_t *ptr) {
724       return input_ptr - (bit_number+7)/8 >= ptr;
725     }
726     int eos(uint8_t *ptr,int bits) {
727       int n = bits - bit_number;
728       if( n <= 0 ) return 0;
729       return input_ptr + (n+7)/8 > ptr;
730     }
731     void use_demuxer();
732     void start_reverse();
733     void start_forward();
734     int refill_ptr();
735     int refill_noptr();
736     int refill() { return input_ptr ? refill_ptr() : refill_noptr(); }
737     int refill_reverse();
738     int open_title(int title);
739     int seek_byte(int64_t position);
740     void reset() { bfr_size = bit_number = 0; }
741     void reset(uint32_t v) { bfr = v; bfr_size = bit_number = 32; }
742     int get_bit_offset() { return bit_number & 7; }
743     void prev_byte_align() { bit_number = (bit_number+7) & ~7; }
744     void next_byte_align() { bit_number &= ~7; }
745     int bof() { return demuxer->zdata.bof() && demuxer->bof(); }
746     int eof() { return demuxer->zdata.eof() && demuxer->eof(); }
747     int error() { return demuxer->error(); }
748     int64_t tell();
749     int next_code(uint32_t zcode);
750     int prev_code(uint32_t zcode);
751     int next_start_code();
752     void pack_bits(uint32_t v, int n) {
753       bfr = (bfr << n) | v;
754       if( (bfr_size+=n) > (int)(8*sizeof(bfr)) )
755          bfr_size = 8*sizeof(bfr);
756       bit_number += n;
757     }
758     void pack_8bits(uint32_t v) { pack_bits(v, 8); }
759     void fill_bits_ptr(int bits) {
760       while( bit_number < bits ) { pack_8bits(*input_ptr++); }
761     }
762     void fill_bits_noptr(int bits) {
763       while( bit_number < bits ) { pack_8bits(demuxer->read_char()); }
764     }
765     void fill_bits(int bits) {
766       return input_ptr ? fill_bits_ptr(bits) : fill_bits_noptr(bits);
767     }
768     uint32_t show_bits_noptr(int bits) {
769       if( bits <= 0 ) return 0;
770       fill_bits_noptr(bits);
771       return (bfr >> (bit_number-bits)) & (0xffffffff >> (32-bits));
772     }
773     uint32_t show_bit_noptr(int bits) { return show_bits_noptr(1); }
774     uint32_t show_byte_noptr() { return show_bits_noptr(8); }
775     uint32_t show_bits24_noptr() { return show_bits_noptr(24); }
776     uint32_t show_bits32_noptr() { fill_bits_noptr(32); return bfr; }
777     int show_bits(int bits) {
778       if( bits <= 0 ) return 0;
779       fill_bits(bits);
780       return (bfr >> (bit_number-bits)) & (0xffffffff >> (32-bits));
781     }
782     uint32_t get_bits_noptr(int bits) {
783       uint32_t result = show_bits_noptr(bits);
784       bit_number -= bits;
785       return result;
786     }
787     uint32_t get_bit_noptr() { return get_bits_noptr(1); }
788     int get_bits(int bits) {
789       uint32_t result = show_bits(bits);
790       bit_number -= bits;
791       return result;
792     }
793     uint32_t get_byte_noptr() { return get_bits_noptr(8); }
794     uint32_t get_bits24_noptr() { return get_bits_noptr(24); }
795     void fill_bits_reverse(int bits) {
796       int n = (bit_number & ~7);
797       if( n ) { bfr >>= n;  bfr_size -= n;  bit_number -= n; }
798       n = bit_number + bits;
799       while( bfr_size < n ) {
800         uint32_t prev_byte = input_ptr ?
801           *--input_ptr : demuxer->read_prev_char();
802         bfr |= prev_byte << bfr_size;
803         bfr_size += 8;
804       }
805     }
806     int show_bits_reverse(int bits) {
807       fill_bits_reverse(bits);
808       return (bfr >> bit_number) & (0xffffffff >> (32 - bits));
809     }
810     int get_bits_reverse(int bits) {
811       uint32_t result = show_bits_reverse(bits);
812       bit_number += bits;
813       return result;
814     }
815   };
816
817
818   class index_t {
819   public:
820     new_memset(0);
821     float **index_data; // Buffer of frames for index.  A frame is a high/low pair.
822     int index_allocated; // Number of frames allocated in each index channel.
823     int index_channels; // Number of index channels allocated
824     int index_size; // Number of high/low pairs in index channel
825     int index_zoom; // Downsampling of index buffers when constructing index
826
827     index_t();
828     ~index_t();
829   };
830
831
832   class bitfont_t {
833   public:
834     class bitchar_t;
835     static bitfont_t *fonts[];
836     static int total_fonts;
837     static int font_refs;
838     static void init_fonts();
839     static void destroy_fonts();
840     class static_init_t {
841     public:
842       static_init_t();
843       ~static_init_t();
844     };
845     class bitchar_t {
846     public:
847       uint16_t ch;
848       int16_t left, right;
849       int16_t ascent, decent;
850       uint8_t *bitmap;
851     } *chrs;
852     int16_t nch, idx, idy, imy;
853   };
854   static bitfont_t *bitfont(int style,int pen_size,int italics,int size);
855
856   class timecode_t {
857   public:
858     new_memset(0);
859     int hour;
860     int minute;
861     int second;
862     int frame;
863
864     timecode_t() {}
865     ~timecode_t() {}
866   };
867
868
869   class audio_t {
870   public:
871     new_memset(0);
872     class imdct_complex_t;
873     class imdct_al_table_t;
874     class audio_decoder_layer_t;
875     class audio_decoder_ac3_t;
876     class audio_decoder_pcm_t;
877     class ac3audblk_t; /*???*/
878
879     enum {
880       AC3_N                          = 512,
881       MAXFRAMESIZE                   = 4096,
882       MAXFRAMESAMPLEZ                = MAXFRAMESAMPLES,
883       HDRCMPMASK                     = 0xfffffd00,
884       SBLIMIT                        = 32,
885       SSLIMIT                        = 18,
886       SCALE_BLOCK                    = 12,
887       MPEG3AUDIO_PADDING             = 1024,
888       MAX_AC3_FRAMESIZE              = 1920 * 2 + 512,
889     };
890
891     enum exponent_type { // Exponent strategy constants
892       exp_REUSE=0,
893       exp_D15=1,
894       exp_D25=2,
895       exp_D45=3,
896     };
897
898     enum delta_type { // Delta bit allocation constants
899       bit_REUSE=0,
900       bit_NEW=1,
901       bit_NONE=2,
902       bit_RESERVED=3,
903     };
904
905     enum mpg_md { // Values for mode
906       md_STEREO=0,
907       md_JOINT_STEREO=1,
908       md_DUAL_CHANNEL=2,
909       md_MONO=3,
910     };
911
912     enum { PCM_HEADERSIZE = 20, };
913
914     enum id3_state {
915       id3_IDLE=0, // No ID3 tag found
916       id3_HEADER=1, // Reading header
917       id3_SKIP=2, // Skipping ID3 tag
918     };
919
920     // IMDCT variables
921     class imdct_complex_t {
922     public:
923       float real;
924       float imag;
925     };
926
927     class imdct_al_table_t {
928     public:
929       short bits;
930       short d;
931     };
932
933     zmpeg3_t *src;
934     atrack_t *track;
935
936     class l3_info_t {
937     public:
938       int scfsi;
939       uint32_t part2_3_length;
940       uint32_t big_values;
941       uint32_t scalefac_compress;
942       uint32_t block_type;
943       uint32_t mixed_block_flag;
944       uint32_t table_select[3];
945       uint32_t subblock_gain[3];
946       uint32_t maxband[3];
947       uint32_t maxbandl;
948       uint32_t maxb;
949       uint32_t region1start;
950       uint32_t region2start;
951       uint32_t preflag;
952       uint32_t scalefac_scale;
953       uint32_t count1table_select;
954       float *full_gain[3];
955       float *pow2gain;
956     };
957
958     class l3_sideinfo_t {
959     public:
960       uint32_t main_data_begin;
961       uint32_t private_bits;
962       class { public: l3_info_t gr[2]; } ch[2];
963     };
964
965     class audio_decoder_layer_t {
966       static int tabsel_123[2][3][16];
967       static long freqs[9];
968       static float decwin[512 + 32];
969       static float cos64[16], cos32[8], cos16[4], cos8[2], cos4[1];
970       static float *pnts[5];
971       static int grp_3tab[32 * 3];   /* used: 27 */
972       static int grp_5tab[128 * 3];  /* used: 125 */
973       static int grp_9tab[1024 * 3]; /* used: 729 */
974       static float muls[27][64];     /* also used by layer 1 */
975       static float gainpow2[256 + 118 + 4];
976       static long intwinbase[257];
977       static float ispow[8207];
978       static float aa_ca[8], aa_cs[8];
979       static float win[4][36];
980       static float win1[4][36];
981       static float COS1[12][6];
982       static float COS9[9];
983       static float COS6_1, COS6_2;
984       static float tfcos36[9];
985       static float tfcos12[3];
986       static float cos9[3], cos18[3];
987       static float tan1_1[16], tan2_1[16], tan1_2[16], tan2_2[16];
988       static float pow1_1[2][16], pow2_1[2][16];
989       static float pow1_2[2][16], pow2_2[2][16];
990       static int longLimit[9][23];
991       static int shortLimit[9][14];
992       static class bandInfoStruct {
993       public:
994         int longIdx[23], longDiff[22];
995         int shortIdx[14], shortDiff[13];
996       } bandInfo[9];
997       static int mapbuf0[9][152];
998       static int mapbuf1[9][156];
999       static int mapbuf2[9][44];
1000       static int *map[9][3];
1001       static int *mapend[9][3];
1002       static uint32_t n_slen2[512]; /* MPEG 2.0 slen for 'normal' mode */
1003       static uint32_t i_slen2[256]; /* MPEG 2.0 slen for intensity stereo */
1004
1005       static short tab0 [  1], tab1 [  7], tab2  [17],  tab3[ 17];
1006       static short tab5 [ 31], tab6 [ 31], tab7  [71],  tab8[ 71];
1007       static short tab9 [ 71], tab10[127], tab11[127], tab12[127];
1008       static short tab13[511], tab15[511], tab16[511], tab24[511];
1009       static short tab_c0[31], tab_c1[31];
1010       static class huffman_t {
1011       public:
1012         unsigned int linbits;
1013         short *table;
1014       } ht[32], htc[2];
1015
1016       static int dct64_1(float *out0,float *out1,float *b1,float *b2,
1017         float *samples);
1018       static int dct64(float *a,float *b,float *c);
1019       static int dct36(float *inbuf,float *o1,float *o2,float *wintab,
1020         float *tsbuf);
1021       static int dct12(float *in,float *rawout1,float *rawout2,float *wi,
1022         float *ts);
1023
1024       int get_scale_factors_1(int *scf,l3_info_t *l3_info,int ch,int gr);
1025       int get_scale_factors_2(int *scf,l3_info_t *l3_info,int i_stereo);
1026       int dequantize_sample(float xr[SBLIMIT][SSLIMIT],int *scf,
1027          l3_info_t *l3_info,int sfreq,int part2bits);
1028       int get_side_info(l3_sideinfo_t *si,int channels,int ms_stereo,
1029          long sfreq,int single,int lsf);
1030       int hybrid(float fsIn[SBLIMIT][SSLIMIT],
1031          float tsOut[SSLIMIT][SBLIMIT],int ch,l3_info_t *l3_info);
1032       int antialias(float xr[SBLIMIT][SSLIMIT],l3_info_t *l3_info);
1033       int calc_i_stereo(float xr_buf[2][SBLIMIT][SSLIMIT],int *scalefac,
1034          l3_info_t *l3_info,int sfreq,int ms_stereo,int lsf);
1035       int synth_stereo(float *bandPtr,int channel,float *out, int *pnt);
1036       int init_audio(zmpeg3_t *zsrc, atrack_t *ztrack, int zformat);
1037       int synths_reset();
1038       int select_table();
1039       int step_one(uint8_t *bit_alloc, int *scale);
1040       int step_two(uint8_t *bit_alloc, float fraction[2][4][SBLIMIT],
1041          int *scale, int x1);
1042     public:
1043       new_memset(0);
1044       bits_t *stream;
1045       // Layer 3
1046       uint8_t *bsbuf, *prev_bsbuf;
1047       uint8_t bsspace[2][MAXFRAMESIZE + 512]; // MAXFRAMESIZE
1048       int bsnum;
1049       // For mp3 current framesize without header.  For AC3 current framesize with header.
1050       long framesize;
1051       long prev_framesize, past_framesize;
1052       int channels;
1053       int samplerate;
1054       int single;
1055       int sampling_frequency_code;
1056       int error_protection;
1057       int mode;
1058       int mode_ext;
1059       int lsf;
1060       long ssize;
1061       int mpeg35;
1062       int padding;
1063       int layer;
1064       int extension;
1065       int copyright;
1066       int original;
1067       int emphasis;
1068       int bitrate;
1069       // Static variable in synthesizer
1070       int bo;                      
1071       // Ignore first frame after a seek
1072       int first_frame;
1073       float synth_stereo_buffs[2][2][0x110];
1074       float synth_mono_buff[64];
1075       float mp3_block[2][2][SBLIMIT * SSLIMIT];
1076       int mp3_blc[2];
1077
1078       // State of ID3 parsing
1079       int id3_state;
1080       int id3_current_byte;
1081       int id3_size;
1082       // Layer 2
1083       int bitrate_index;
1084       imdct_al_table_t *alloc;
1085       int jsbound;
1086       int II_sblimit;
1087       uint8_t layer2_scfsi_buf[64];
1088
1089       void layer_reset();
1090       static int layer_check(uint8_t *data);
1091       static int id3_check(uint8_t *data);
1092       int layer3_header(uint8_t *data);
1093       audio_decoder_layer_t();
1094       ~audio_decoder_layer_t();
1095       int do_layer2(uint8_t *zframe,int zframe_size,float **zoutput,int render);
1096       int do_layer3(uint8_t *zframe,int zframe_size,float **zoutput,int render);
1097       int init_layer2();
1098       int init_layer3();
1099       int init_decode_tables();
1100     } *layer_decoder;
1101
1102     class audio_decoder_ac3_t {
1103     public:
1104       new_memset(0);
1105       static int ac3_samplerates[3];
1106
1107       bits_t *stream;
1108       int samplerate;
1109       int bitrate;
1110       int flags;
1111       int channels;
1112       a52_state_t *state;
1113       sample_t *output;
1114       int framesize;
1115       static int ac3_check(uint8_t *data);
1116       int ac3_header(uint8_t *data);
1117       int do_ac3(uint8_t *zframe, int zframe_size, float **zoutput, int render);
1118       audio_decoder_ac3_t();
1119       ~audio_decoder_ac3_t();
1120     } *ac3_decoder;
1121
1122     class audio_decoder_pcm_t {
1123     public:
1124       new_memset(0);
1125       int samplerate;
1126       int bits;
1127       int channels;
1128       int framesize;
1129       int pcm_header(uint8_t *data);
1130       int do_pcm(uint8_t *zframe, int zframe_size, float **zoutput, int render);
1131       audio_decoder_pcm_t() {}
1132       ~audio_decoder_pcm_t() {}
1133     } *pcm_decoder;
1134
1135     int channels;            // channels from read_header
1136     int samplerate;          // samplerate from read_header
1137     int framenum;            // Number of current frame being decoded
1138     int framesize;           // Size of frame including header
1139     int64_t start_byte;      // First byte of audio data in the file
1140     int output_channels;     // number of defined output buffers
1141     float **output;          // Output from synthesizer in linear floats
1142     int output_size;         // Number of pcm samples in the buffer
1143     int output_allocated;    // Allocated number of samples in output
1144     int64_t output_position; // Sample position in file of start of output buffer
1145     int64_t sample_seek;     // Perform a seek to the sample
1146     int64_t byte_seek;       // Perform a seek to the absolute byte
1147     // +/- number of samples of difference between audio and video
1148     int seek_correction;
1149     // Buffer containing current packet
1150     uint8_t packet_buffer[MAXFRAMESIZE];
1151     // Position in packet buffer of next byte to read
1152     int packet_position;
1153
1154     audio_t() {}
1155     int init_audio(zmpeg3_t *zsrc, atrack_t *ztrack, int zformat);
1156     ~audio_t();
1157
1158     int rewind_audio();
1159     int read_header();
1160     void update_channels();
1161     int audio_pts_padding();
1162     int audio_pts_skipping(int samples);
1163     void update_audio_history();
1164     int read_frame(int render);
1165     int get_length();
1166     int seek();
1167     int seek_byte(int64_t byte);
1168     int seek_sample(long sample);
1169     int read_raw(uint8_t *output,long *size,long max_size);
1170     void shift_audio(int64_t diff);
1171     int decode_audio(void *output_v,int atyp,int channel,int len);
1172     int64_t audio_position() { return output_position + output_size; }
1173   };
1174
1175   class VLCtab_t {
1176   public:
1177     int8_t val, len;
1178   };
1179
1180   class DCTtab_t {
1181   public:
1182     int8_t run, level;
1183     int16_t len;
1184   };
1185
1186   class slice_buffer_t {
1187     static VLCtab_t DClumtab0[32];
1188     static VLCtab_t DClumtab1[16];
1189     static VLCtab_t DCchromtab0[32];
1190     static VLCtab_t DCchromtab1[32];
1191   
1192   public:
1193     slice_buffer_t *next;    // avail list link
1194     uint8_t *data;           // Buffer for holding the slice data
1195     video_t *video;          // decoder
1196     int buffer_size;         // Size of buffer
1197     int buffer_allocation;   // Space allocated for buffer 
1198     int buffer_position;     // Position in buffer
1199     uint32_t bits;
1200     int bits_size;
1201
1202     int eob() { return buffer_position >= buffer_size; }
1203     uint32_t get_data_byte() { return data[buffer_position++]; }
1204     void fill_bits(int nbits) {
1205       while( bits_size < nbits ) {
1206         bits <<= 8;
1207         if( !eob() ) bits |= get_data_byte();
1208         bits_size += 8;
1209       }
1210     }
1211     void flush_bits(int nbits) { fill_bits(nbits); bits_size -= nbits; }
1212     void flush_bit() { flush_bits(1); }
1213     uint32_t show_bits(int nbits) {
1214       fill_bits(nbits);
1215       return (bits >> (bits_size-nbits)) & (0xffffffff >> (32-nbits));
1216     }
1217     uint32_t get_bits(int nbits) {
1218       uint32_t result = show_bits(nbits);
1219       bits_size -= nbits;
1220       return result;
1221     }
1222     uint32_t get_bit() { return get_bits(1); }
1223     int get_dc_lum();
1224     int get_dc_chrom();
1225     uint8_t *expand_buffer(int bfrsz);
1226     void fill_buffer(bits_t *vstream);
1227     int ext_bit_info();
1228
1229     slice_buffer_t();
1230     ~slice_buffer_t();
1231   };
1232
1233
1234   class video_t {
1235     static uint8_t zig_zag_scan_nommx[64]; // zig-zag scan
1236     static uint8_t alternate_scan_nommx[64]; // alternate scan
1237     // default intra quantization matrix
1238     static uint8_t default_intra_quantizer_matrix[64];
1239     // Frame rate table must agree with the one in the encoder
1240     static double frame_rate_table[16];
1241
1242     inline void recon_comp(uint8_t *s, uint8_t *d,
1243            int lx, int lx2, int h, int type);
1244     void recon(uint8_t *src[], int sfield,
1245            uint8_t *dst[], int dfield, int lx, int lx2,
1246            int w, int h, int x, int y, int dx, int dy, int addflag);
1247     int delete_decoder();
1248     void init_scantables();
1249     int read_frame_backend(int skip_bframes);
1250     int *get_scaletable(int input_w, int output_w);
1251     int get_gop_header();
1252     long gop_to_frame(timecode_t *gop_timecode);
1253     int seek();
1254
1255   public:
1256     new_memset(0);
1257     class cc_t;
1258
1259     enum chroma_format {
1260       cfmt_420=1,
1261       cfmt_422=2,
1262       cfmt_444=3,
1263     };
1264
1265     enum ext_start_code {
1266       ext_id_SEQ=1,
1267       ext_id_DISP=2,
1268       ext_id_QUANT=3,
1269       ext_id_SEQSCAL=5,
1270       ext_id_PANSCAN=7,
1271       ext_id_CODING=8,
1272       ext_id_SPATSCAL=9,
1273       ext_id_TEMPSCAL=10,
1274     };
1275
1276     enum picture_type {
1277       pic_type_I=1,
1278       pic_type_P=2,
1279       pic_type_B=3,
1280       pic_type_D=4,
1281     };
1282
1283     enum picture_structure {
1284       pics_TOP_FIELD=1,
1285       pics_BOTTOM_FIELD=2,
1286       pics_FRAME_PICTURE=3,
1287     };
1288
1289     slice_buffer_t *slice_buffers, *avail_slice_buffers;
1290     int total_slice_buffers;
1291     void allocate_slice_buffers();
1292     void delete_slice_buffers();
1293     void reallocate_slice_buffers();
1294     zlock_t slice_lock, slice_wait, slice_active;
1295     int slice_wait_locked, slice_active_locked;
1296
1297     zmpeg3_t *src;
1298     vtrack_t *track;
1299
1300     // ================================= Seeking variables =========================
1301     bits_t *vstream;
1302     int decoder_initted;
1303     uint8_t **output_rows;     // Output frame buffer supplied by user
1304     int in_x, in_y, in_w, in_h, out_w, out_h; // Output dimensions
1305     int row_span;
1306     int *x_table, *y_table;          // Location of every output pixel in the input
1307     int color_model;
1308     int want_yvu;                    // Want to return a YUV frame
1309     char *y_output, *u_output, *v_output; // Output pointers for a YUV frame
1310
1311     int blockreadsize;
1312     int maxframe;          // Max value of frame num to read
1313     int64_t byte_seek;     // Perform absolute byte seek before the next frame is read
1314     int frame_seek;        // Perform a frame seek before the next frame is read
1315     int framenum;          // Number of the next frame to be decoded
1316     int last_number;       // Last framenum rendered
1317     int ref_frames;        // ref_frames since last seek
1318     int found_seqhdr;
1319     int bitrate;
1320     timecode_t gop_timecode;     // Timecode for the last GOP header read.
1321     int has_gops; // Some streams have no GOPs so try sequence start codes instead
1322
1323     class cc_t {        // close captioning (atsc only)
1324       video_t *video;
1325       uint8_t data[3][128];   // reorder buffers
1326       int frs_history, font_size;
1327       void decode(int idx);
1328     public:
1329       class svc_t;
1330   
1331       enum {
1332         MX_SVC = 64, MX_WIN=8,MX_CX=48,MX_CY=16,
1333         /* frame struct history */
1334         frs_tf1 = 0x01, /* top field in data[1] */
1335         frs_bf2 = 0x02, /* bottom field in data[2] */
1336         frs_frm = 0x04, /* frame in data[1] */
1337         frs_prc = 0x08, /* frame processed */
1338         st_unmap=-1, st_hidden=0, st_visible=1, /* state */
1339         dir_rt=0, dir_lt=1, dir_up=2, dir_dn=3, /* print/scroll/effect dir */
1340         jfy_left=0, jfy_right=1, jfy_center=2, jfy_full=3, /* justify */
1341         eft_snap = 0, eft_fade = 1, eft_wipe = 2, /* effect */
1342         oty_solid=0, oty_flash=1, oty_translucent=2,
1343         oty_transparent=3, bdr_width=5, /* opacity/border width */
1344         edg_none=0, edg_raised=1, edg_depressed=2, edg_uniform=3,
1345         edg_shadow_left=4, edg_shadow_right=5, /* edge type */
1346         psz_small=0, psz_standard=1, psz_large=2, /* pen size */
1347         fst_default=0, fst_mono_serif=1, fst_prop_serif=2,
1348         fst_mono_sans=3, fst_prop_sans=4, fst_casual=5,
1349         fst_cursive=6, fst_small_caps=7, /* font style */
1350         fsz_small=0, fsz_normal=1, fsz_large=2, /* font size */
1351         tag_dialog=0, tag_source_id=1, tag_device=2,
1352         tag_dialog_2=3, tag_voiceover=4, tag_audible_transl=5,
1353         tag_subtitle_transl=6, tag_voice_descr=7, tag_lyrics=8,
1354         tag_effect_descr=9, tag_score_descr=10, tag_expletive=11,
1355         tag_not_displayable=15, /* text tag */
1356         ofs_subscript=0, ofs_normal=1, ofs_superscript=2, /* offset */
1357       };
1358       /* color RGB 2:2:2 (lsb = B). */
1359       class svc_t {
1360         cc_t *cc;
1361         int sid, ctrk, size;
1362         uint8_t *bp, *ep;
1363         uint8_t data[128];
1364       public:
1365         class chr_t {
1366         public:
1367           uint16_t glyph;
1368           uint8_t fg_opacity : 2;
1369           uint8_t fg_color : 6;
1370           uint8_t bg_opacity : 2;
1371           uint8_t bg_color : 6;
1372           uint8_t pen_size : 2;
1373           uint8_t edge_color : 6;
1374           uint8_t italics : 1;
1375           uint8_t edge_type : 3;
1376           uint8_t underline : 1;
1377           uint8_t font_style : 3; 
1378           uint8_t font_size : 2; 
1379           uint8_t offset : 2; 
1380           uint8_t text_tag : 4;
1381           uint8_t rsvd2;
1382         } *bfrs;
1383         chr_t *get_bfr();
1384         void bfr_put(chr_t *&bfr);
1385
1386         class win_t;
1387         class win_t {
1388         public:
1389           class chr_attr_t;
1390           int8_t id, st, pdir, sdir;
1391           uint8_t cx, cy, cw, ch; /* pen/dim in bytes */
1392           int ax, ay, x, y, bw; /* anchor/pen/border in pixels */
1393           uint32_t fg_yuva, bg_yuva, edge_yuva; /* pen color */
1394           uint32_t fill_yuva, border_yuva; /* window color */
1395           int start_frame, end_frame;
1396           svc_t *svc;
1397           subtitle_t *subtitle;
1398           uint8_t anchor_point, anchor_horizontal, anchor_vertical;
1399           uint8_t anchor_relative, row_lock, col_lock, dirty;
1400           uint8_t priority, window_style, pen_style;
1401           /* pen style properties */
1402           uint8_t pen_size, font_style, offset, italics, underline;
1403           uint8_t fg_color, fg_opacity, bg_color, bg_opacity;
1404           uint8_t text_tag, edge_color, edge_type, scale;
1405           /* window style properties */
1406           uint8_t justify, wordwrap, fill_opacity, fill_color;
1407           uint8_t display_effect, effect_speed, effect_direction;
1408           uint8_t border_type, border_color, border_width;
1409           chr_t *bfr;
1410
1411           win_t();
1412           ~win_t();
1413           void reset(int i,svc_t *svc);
1414           int BS();   int FF();   int CR();   int HCR();
1415           int init(int ncw, int nch);
1416           int resize(int ncw, int nch);
1417           static int is_breakable(int b);
1418           int wrap();
1419           int ovfl();
1420           int store(int ch);
1421           void set_window_style(int i);
1422           void set_pen_style(int i);
1423           void default_window();
1424           void print_buffer();
1425           void hbar(int x, int y, int ww, int hh, int lm, int rm, int clr);
1426           void vbar(int x, int y, int ww, int hh, int tm, int bm, int clr);
1427           void border(int ilt, int olt, int irt, int ort,
1428                       int iup, int oup, int idn, int odn);
1429           void put_chr(chr_t *chr);
1430           static bitfont_t *chr_font(chr_t *bp, int scale);
1431           void render();
1432           void output_text();
1433           void set_state(int8_t st);
1434         } win[MX_WIN], *curw;    
1435         svc_t(cc_t *cc);
1436         ~svc_t();
1437         int id() { return sid; }
1438         int trk() { return ctrk; }
1439         void append(uint8_t *bp, int len);
1440         void decode();
1441         int render();
1442         void reset(int sid,cc_t *cc);
1443         int CWx(int id);  int DFz(int id);
1444         int DFx(int id);  int RSVD();   int ETX();
1445         int BS();   int FF();   int CR();   int HCR();
1446         int RST();  int DLC();  int DLW();  int DLY();
1447         int CLW();  int DSW();  int HDW();  int TGW();
1448         int SPA();  int SPC();  int SPL();  int SWA();
1449         int command(int cmd);
1450         static uint32_t pen_yuva(int color, int opacity);
1451       } svc;
1452   
1453       cc_t(video_t *video);
1454       ~cc_t();
1455       void reset();
1456       void get_atsc_data(bits_t *v);
1457       void decode();
1458       void reorder();
1459       zcc_text_cb text_cb;
1460     } *cc;
1461     cc_t *get_cc();
1462     int subtitle_track; // Subtitle track to composite if >= 0
1463     int show_subtitle(int strk);
1464
1465     // These are only available from elementary streams.
1466     int frames_per_gop;       // Frames per GOP after the first GOP.
1467     int first_gop_frames;     // Frames in the first GOP.
1468     int first_frame;     // Number of first frame stored in timecode
1469     int last_frame;      // Last frame in file
1470
1471     // ================================= Compression variables =====================
1472     // Malloced frame buffers.  2 refframes are swapped in and out.
1473     // while only 1 auxframe is used.
1474     uint8_t *yuv_buffer[5];  // Make YVU buffers contiguous for all frames
1475     uint8_t *oldrefframe[3], *refframe[3], *auxframe[3];
1476     uint8_t *llframe0[3], *llframe1[3];
1477     uint8_t *zigzag_scan_table;
1478     uint8_t *alternate_scan_table;
1479     // Source for the next frame presentation
1480     uint8_t *output_src[3];
1481     // Pointers to frame buffers.
1482     uint8_t *newframe[3];
1483     uint8_t *tdat;
1484     int horizontal_size, vertical_size, mb_width, mb_height;
1485     int coded_picture_width,  coded_picture_height;
1486     int chroma_format, chrom_width, chrom_height, blk_cnt;
1487     int8_t pict_type, pict_struct, field_sequence, intravlc;
1488     int8_t forw_r_size, back_r_size, full_forw, full_back;
1489     int8_t prog_seq, prog_frame, repeatfirst, secondfield;
1490     int8_t h_forw_r_size, v_forw_r_size, h_back_r_size, v_back_r_size;
1491     int8_t dc_prec, topfirst, frame_pred_dct, conceal_mv;
1492     union {
1493       struct { int8_t got_top, got_bottom, repeat_fields, current_field; };
1494       int32_t repeat_data;
1495     };
1496     int skip_bframes;
1497     int frame_time, seek_time;
1498     int stwc_table_index, llw, llh, hm, hn, vm, vn;
1499     int lltempref, llx0, lly0, llprog_frame, llfieldsel;
1500     int matrix_coefficients;
1501     int framerate_code;
1502     double frame_rate;
1503     int *cr_to_r, *crb_to_g, *cb_to_b;
1504     int intra_quantizer_matrix[64], non_intra_quantizer_matrix[64];
1505     int chroma_intra_quantizer_matrix[64], chroma_non_intra_quantizer_matrix[64];
1506     int mpeg2;
1507     int skim;                     // skip reconstruction/motion
1508     int thumb, ithumb;            // thumbnail scan/ thumbnail frame ready 
1509     int qscale_type, altscan;     // picture coding extension
1510     int pict_scal;                // picture spatial scalable extension
1511     int scalable_mode;            // sequence scalable extension
1512
1513     // Subtitling frame
1514     uint8_t *subtitle_frame[3];
1515
1516     video_t(zmpeg3_t *zsrc, vtrack_t *ztrack);
1517     ~video_t();
1518     void init_video();
1519     int seek_video() { return seek(); }
1520     void reset_subtitles();
1521     int eof();
1522
1523     int set_cpus(int cpus);
1524     int set_mmx(int use_mmx);
1525     void cache_frame();
1526     int drop_frames(long frames, int cache_it);
1527     int colormodel();
1528     int read_frame(uint8_t **output_rows,
1529       int in_x, int in_y, int in_w, int in_h,
1530       int out_w, int out_h, int color_model);
1531     int read_yuvframe(char *y_output, char *u_output, char *v_output,
1532       int in_x, int in_y, int in_w, int in_h);
1533     int read_yuvframe_ptr(char **y_output, char **u_output, char **v_output);
1534     int read_raw(uint8_t *output, long *size, long max_size);
1535     int seek_frame(long frame);
1536     int seek_byte(int64_t byte);
1537     int rewind_video(int preload=1);
1538     int previous_frame();
1539     int init_decoder();
1540     void new_output();
1541     int reconstruct( int bx, int by, int mb_type, int motion_type,
1542            int PMV[2][2][2], int mv_field_sel[2][2],
1543            int dmvector[2], int stwtype);
1544     void dump();
1545     slice_buffer_t *get_slice_buffer();
1546     void put_slice_buffer(slice_buffer_t* buffer);
1547     int get_macroblocks();
1548     int display_second_field();
1549     int video_pts_padding();
1550     int video_pts_skipping();
1551     int read_picture();
1552     int get_picture();
1553     int get_seq_hdr();
1554     int sequence_extension();
1555     int sequence_display_extension();
1556     int quant_matrix_extension();
1557     int sequence_scalable_extension();
1558     int picture_display_extension();
1559     int picture_coding_extension();
1560     int picture_spatial_scalable_extension();
1561     int picture_temporal_scalable_extension();
1562     int ext_user_data();
1563     int get_picture_hdr();
1564     int find_header();
1565     int get_header();
1566     void overlay_subtitle(subtitle_t *subtitle);
1567     void decode_subtitle();
1568     int init_output();
1569     int dither_frame(uint8_t *yy, uint8_t *uu, uint8_t *vv,uint8_t **output_rows);
1570     int dither_frame444(uint8_t *yy, uint8_t *uu, uint8_t *vv);
1571     int dithertop(uint8_t *yy, uint8_t *uu, uint8_t *vv);
1572     int dithertop444(uint8_t *yy, uint8_t *uu, uint8_t *vv);
1573     int ditherbot(uint8_t *yy, uint8_t *uu, uint8_t *vv);
1574     int ditherbot444(uint8_t *yy, uint8_t *uu, uint8_t *vv);
1575     int present_frame(uint8_t *yy, uint8_t *uu, uint8_t *vv);
1576     void calc_dmv(int DMV[][2],int *dmvector,int mvx,int mvy);
1577     int is_refframe() { return pict_type == pic_type_B ? 0 :
1578       pict_struct == pics_FRAME_PICTURE ? 1 : secondfield;
1579     }
1580   };
1581
1582
1583   class slice_decoder_t {
1584   public:
1585     static VLCtab_t PMBtab0[8];
1586     static VLCtab_t PMBtab1[8];
1587     static VLCtab_t BMBtab0[16];
1588     static VLCtab_t BMBtab1[8];
1589     static VLCtab_t spIMBtab[16];
1590     static VLCtab_t spPMBtab0[16];
1591     static VLCtab_t spPMBtab1[16];
1592     static VLCtab_t spBMBtab0[14];
1593     static VLCtab_t spBMBtab1[12];
1594     static VLCtab_t spBMBtab2[8];
1595     static VLCtab_t SNRMBtab[8];
1596     static VLCtab_t MVtab0[8];
1597     static VLCtab_t MVtab1[8];
1598     static VLCtab_t MVtab2[12];
1599     static VLCtab_t CBPtab0[32];
1600     static VLCtab_t CBPtab1[64];
1601     static VLCtab_t CBPtab2[8];
1602     static VLCtab_t MBAtab1[16];
1603     static VLCtab_t MBAtab2[104];
1604
1605     static DCTtab_t DCTtabfirst[12];
1606     static DCTtab_t DCTtabnext[12];
1607     static DCTtab_t DCTtab0[60];
1608     static DCTtab_t DCTtab0a[252];
1609     static DCTtab_t DCTtab1[8];
1610     static DCTtab_t DCTtab1a[8];
1611     static DCTtab_t DCTtab2[16];
1612     static DCTtab_t DCTtab3[16];
1613     static DCTtab_t DCTtab4[16];
1614     static DCTtab_t DCTtab5[16];
1615     static DCTtab_t DCTtab6[16];
1616
1617     // non-linear quantization coefficient table
1618     static uint8_t non_linear_mquant_table[32];
1619
1620     enum macroblock_type {
1621       mb_INTRA=1,
1622       mb_PATTERN=2,
1623       mb_BACKWARD=4,
1624       mb_FORWARD=8,
1625       mb_QUANT=16,
1626       mb_WEIGHT=32,
1627       mb_CLASS4=64,
1628     };
1629
1630     enum motion_type {
1631       mc_FIELD=1,
1632       mc_FRAME=2,
1633       mc_16X8=2,
1634       mc_DMV=3,
1635     };
1636
1637     enum mv_format {
1638       mv_FIELD=0,
1639       mv_FRAME=1,
1640     };
1641
1642     enum scalable_mode {
1643       sc_NONE=0,
1644       sc_DP=1,
1645       sc_SPAT=2,
1646       sc_SNR=3,
1647       sc_TEMP=4,
1648     };
1649
1650     slice_decoder_t *next;
1651     zmpeg3_t *src;
1652     video_t *video;
1653     pthread_t owner;        // for debugging
1654     slice_buffer_t *slice_buffer;
1655     int fault;
1656     int done;
1657     int quant_scale;
1658     int pri_brk;            // slice/macroblock
1659     short block[12][64];
1660     int sparse[12];
1661     pthread_t tid;          // ID of thread
1662     zlock_t input_lock;
1663
1664     int val, sign, idx;
1665     int get_cbp();
1666     int clear_block(int comp, int size);
1667     static uint16_t *DCTlutab[3];
1668     static uint16_t lu_pack(DCTtab_t *lp) {
1669       int run = lp->run>=64 ? lp->run-32 : lp->run;
1670       return run | ((lp->len-1)<<6) | (lp->level<<10);
1671     }
1672     static int lu_run(uint16_t lu) { return lu & 0x3f; }
1673     static int lu_level(uint16_t lu) { return lu >> 10; }
1674     static int lu_len(uint16_t lu) { return ((lu>>6) & 0x0f) + 1; }
1675     static void init_lut(uint16_t *&lutbl, DCTtab_t *tabn, DCTtab_t *tab0, DCTtab_t *tab1);
1676     static void init_tables();
1677     int get_coef(uint16_t *lut);
1678     int get_mpg2_coef(uint16_t *lut);
1679     void get_intra_block(int comp, int dc_dct_pred[]);
1680     void get_mpg2_intra_block(int comp, int dc_dct_pred[]);
1681     void get_inter_block(int comp);
1682     void get_mpg2_inter_block(int comp);
1683     int get_slice_hdr();
1684     int decode_slice();
1685     void slice_loop();
1686     static void *the_slice_loop(void *the_slice_decoder);
1687     int get_mv();
1688     int get_dmv();
1689     void motion_vector(int *PMV, int *dmvector, int h_r_size, int v_r_size,
1690       int dmv, int mvscale, int full_pel_vector);
1691     int motion_vectors(int PMV[2][2][2], int dmvector[2], int mv_field_sel[2][2],
1692       int s, int mv_count, int mv_format, int h_r_size, int v_r_size,
1693       int dmv, int mvscale);
1694     int get_macroblock_address();
1695     inline int getsp_imb_type();
1696     inline int getsp_pmb_type();
1697     inline int getsp_bmb_type();
1698     inline int get_imb_type();
1699     inline int get_pmb_type();
1700     inline int get_bmb_type();
1701     inline int get_dmb_type();
1702     inline int get_snrmb_type();
1703     int get_mb_type();
1704     int macroblock_modes(int *pmb_type,int *pstwtype, int *pstwclass,
1705        int *pmotion_type,int *pmv_count,int *pmv_format,int *pdmv,
1706        int *pmvscale,int *pdct_type);
1707     int add_block(int comp,int bx,int by,int dct_type,int addflag);
1708     static void idct_conversion(short* block);
1709     int get_active_slice_buffer();
1710
1711     slice_decoder_t();
1712     ~slice_decoder_t();
1713   } *slice_decoders, *avail_slice_decoders;
1714
1715   int total_slice_decoders;
1716   slice_buffer_t *active_slice_buffers;
1717   zlock_t decoder_lock, decoder_active;
1718   int decoder_active_locked;
1719   void allocate_slice_decoders();
1720   void delete_slice_decoders();
1721   void reallocate_slice_decoders();
1722   void decode_slice(slice_buffer_t* buffer);
1723   
1724
1725   class subtitle_t {
1726   public:
1727     new_memset(0);
1728     uint8_t *data;   // Raw data of subtitle
1729     int data_allocated, data_used;
1730     int id;         // Number of stream starting at 0x20
1731     int done;       // -1 avail, 0 read in, 1 decode
1732     int active;     // 1 subtitle is contructed, -1 subtitle is close caption
1733     int draw;       // -1 never draw, 0 draw based on frame time, 1 always draw
1734     int64_t offset; // Program offset of start of subtitle
1735     int force;      // 1 Force display, -1 force delete
1736     // image in YUV444
1737     int w, h, sz;
1738     uint8_t *image_y, *image_u, *image_v, *image_a;
1739     int x1, x2, y1, y2;
1740     int start_time; // Time after detection of subtitle to display it in msec
1741     int stop_time;  // Time after detection of subtitle to hide it in msec
1742     int palette[4]; // Indexes in the main palette
1743     int alpha[4];
1744     int start_frame, stop_frame; // framenum start/stop drawing
1745     int frame_time; // presentation frame_time at creation
1746
1747     subtitle_t();
1748     subtitle_t(int nid, int ww, int hh);
1749     ~subtitle_t();
1750
1751     void realloc_data(int count);
1752     int decompress_subtitle(zmpeg3_t *zsrc);
1753     void set_image_size(int isz);
1754     void set_image_size(int ww, int hh);
1755     int decode(video_t *video);
1756   };
1757
1758   class demuxer_t {
1759     friend class bits_t;
1760
1761     uint8_t packet_next_char() { return raw_data[raw_offset]; }
1762     uint8_t packet_read_char() { return raw_data[raw_offset++]; }
1763     uint32_t packet_read_int16() {
1764       uint32_t a = raw_data[raw_offset++];
1765       uint32_t b = raw_data[raw_offset++];
1766       return (a << 8) | b;
1767     }
1768     uint32_t packet_next_int24() {
1769       uint32_t a = raw_data[raw_offset+0];
1770       uint32_t b = raw_data[raw_offset+1];
1771       uint32_t c = raw_data[raw_offset+2];
1772       return (a << 16) | (b << 8) | c;
1773     }
1774     uint32_t packet_read_int24() {
1775       uint32_t a = raw_data[raw_offset++];
1776       uint32_t b = raw_data[raw_offset++];
1777       uint32_t c = raw_data[raw_offset++];
1778       return (a << 16) | (b << 8) | c;
1779     }
1780     uint32_t packet_read_int32() {
1781       uint32_t a = raw_data[raw_offset++];
1782       uint32_t b = raw_data[raw_offset++];
1783       uint32_t c = raw_data[raw_offset++];
1784       uint32_t d = raw_data[raw_offset++];
1785       return (a << 24) | (b << 16) | (c << 8) | d;
1786     }
1787     void packet_skip(int length) { raw_offset += length; }
1788     int get_adaptation_field();
1789     int get_program_association_table();
1790     int get_transport_payload(int is_audio, int is_video);
1791     int get_pes_packet_header(uint64_t *pts, uint64_t *dts);
1792     int get_unknown_data();
1793     int get_transport_pes_packet();
1794     int get_pes_packet();
1795     int get_payload();
1796     int read_transport();
1797     int get_system_header();
1798     uint64_t get_timestamp();
1799     int get_pack_header();
1800     int get_program_payload(int bytes, int is_audio, int is_video);
1801     int handle_scrambling(int decryption_offset);
1802     void del_subtitle(int idx);
1803     subtitle_t* get_subtitle(int id,int64_t offset);
1804     void handle_subtitle(zmpeg3_t *src, int stream_id, int bytes);
1805     int handle_pcm(int bytes);
1806     int get_program_pes_packet(uint32_t header);
1807     int previous_code(uint32_t zcode);
1808
1809   public:
1810     new_memset(0);
1811     class zstream_t;
1812     class title_t;
1813     class nav_t {
1814     public:
1815 #include "nav.h"
1816       new_memset(0);
1817     } *nav;
1818
1819     zmpeg3_t* src;
1820     uint8_t *raw_data; // One unparsed packet.
1821     int raw_offset; // Offset in raw_data of read pointer
1822     int raw_size; // Amount loaded in last raw_data
1823
1824     // Elementary stream data when only one stream is to be read.
1825     // Erased in every call to read a packet.
1826     class zstream_t {
1827     public:
1828       new_memset(0);
1829       uint8_t *buffer;
1830       int allocated; // Allocation of data_buffer
1831       int size; // Position in data_buffer of write pointer
1832       int position; // Position in data_buffer of read pointer
1833       int start; // Start of the next pes packet
1834       int length() { return size - position; }
1835       bool eof() { return position >= size; }
1836       bool bof() { return position == 0; }
1837     } zdata;
1838     // Elementary stream data when all streams are to be read.  There is no
1839     // read pointer since data is expected to be copied directly to a track.
1840     // Some packets contain audio and video.  Further division into
1841     // stream ID may be needed.
1842     zstream_t zaudio;
1843     zstream_t zvideo;
1844
1845     subtitle_t *subtitles[MAX_SUBTITLES];
1846     int total_subtitles;
1847
1848     // What type of data to read, which track is accessing
1849     atrack_t *do_audio;
1850     vtrack_t *do_video;
1851     int read_all;
1852     // Direction of reads
1853     int reverse;
1854     // Set to 1 when eof or attempt to read before beginning
1855     int error_flag;
1856     int discontinuity;
1857     // Temp variables for returning
1858     uint8_t next_char;
1859     // Info for mpeg3cat
1860     int64_t last_packet_start;
1861     int64_t last_packet_end;
1862     int64_t last_packet_decryption;
1863
1864   // Table of contents
1865     class title_t { // Titles
1866       void extend_cell_table();
1867     public:
1868       new_memset(0);
1869       class cell_t;
1870
1871       zmpeg3_t *src;
1872       fs_t *fs;
1873       int64_t total_bytes; // Total bytes in title file.
1874       int64_t start_byte; // Absolute starting byte of the title in the stream
1875       int64_t end_byte; // Absolute ending byte of the title in the stream + 1
1876       // May get rid of time values and rename to a cell offset table.
1877       // May also get rid of end byte.
1878
1879       class cell_t {
1880       public:
1881         new_memset(0);
1882         int64_t title_start; // Starting byte of cell in the title (start_byte)
1883         int64_t title_end;  // Ending byte of cell in the title (end_byte)
1884         int64_t program_start; // Starting byte of the cell in the program
1885         int64_t program_end; // Ending byte of the cell in the program
1886         double cell_time; // play time at end of cell, -1 if unknown
1887         int cell_no; // cell in original cell table
1888         int discontinuity;
1889
1890         cell_t() {}
1891         ~cell_t() {}
1892       } *cell_table; // Timecode table
1893       int cell_table_size; // Number of entries
1894       int cell_table_allocation; // Number of available slots
1895
1896       title_t(zmpeg3_t *zsrc, char *fpath);
1897       title_t(zmpeg3_t *zsrc);
1898       ~title_t();
1899       title_t(title_t &title);
1900       void new_cell(int cell_no,
1901         int64_t title_start, int64_t title_end,
1902         int64_t program_start, int64_t program_end,
1903         int discontinuity);
1904       void new_cell(int64_t byte_end) { // default cell
1905         new_cell(0, 0, byte_end, 0, byte_end, 0);
1906       }
1907       int dump_title();
1908       int print_cells(FILE *output);
1909     } *titles[MAX_STREAMZ];
1910     int total_titles;
1911     int current_title; // Title currently being used
1912
1913     // Tables of every stream ID encountered
1914     int8_t astream_table[MAX_STREAMZ];  // afmt index
1915     int8_t vstream_table[MAX_STREAMZ];  // 1 if video
1916     int8_t sstream_table[MAX_STREAMZ];  // 1 if subtitle
1917
1918     // Cell in the current title currently used
1919     int title_cell;
1920     int64_t nav_cell_next_vobu;
1921     int64_t nav_cell_end_byte;
1922
1923     // Byte position in current program.
1924     int64_t program_byte;
1925     // Total bytes in all titles
1926     int64_t total_bytes;
1927     // The end of the current stream in the current program
1928     int64_t stream_end;
1929
1930     int transport_error_indicator;
1931     int payload_unit_start_indicator;
1932     int pid; // PID of last packet
1933     int stream_id; // Stream ID of last packet
1934     int custom_id; // Custom ID of last packet
1935     int transport_scrambling_control;
1936     int adaptation_field_control;
1937     int continuity_counter;
1938     int is_padding;
1939     int pid_table[PIDMAX];
1940     int continuity_counters[PIDMAX];
1941     int total_pids;
1942     int adaptation_fields;
1943     double time;           // Time in seconds
1944     uint32_t last_code;
1945     int audio_pid;
1946     int video_pid;
1947     int subtitle_pid;
1948     int got_audio;
1949     int got_video;
1950     // if subtitle object was created in last packet
1951     int got_subtitle;
1952     // When only one stream is to be read, these store the stream IDs
1953     // Audio stream ID being decoded.  -1 = select first ID in stream
1954     int astream;     
1955     // Video stream ID being decoded.  -1 = select first ID in stream
1956     int vstream;
1957     // Multiplexed streams have the audio type
1958     // Format of the audio derived from multiplexing codes
1959     int aformat;      
1960     int program_association_tables;
1961     int table_id;
1962     int section_length;
1963     int transport_stream_id;
1964     int pes_packets;
1965     double pes_audio_time;  // Presentation Time stamps
1966     double pes_video_time;
1967     int pes_audio_pid;      // custom_id of timestamp
1968     int pes_video_pid;
1969     // Cause the stream parameters to be dumped in human readable format
1970     int dump;
1971
1972     demuxer_t(zmpeg3_t *zsrc,atrack_t *do_aud,vtrack_t *do_vid,int cust_id);
1973     ~demuxer_t();
1974
1975     int create_title(int full_scan=0);
1976     int64_t tell_byte() { return program_byte; }
1977     int64_t absolute_position() {
1978       return titles[current_title]->fs->tell() + titles[current_title]->start_byte;
1979     }
1980     bool eof();
1981     bool bof();
1982     bool error() { return error_flag; }
1983     int64_t movie_size();
1984     double get_time() { return time; }
1985     int get_cell(int no, title_t::cell_t *&v);
1986     void start_reverse();
1987     void start_forward();
1988     int seek_byte(int64_t byte);
1989     double scan_pts();
1990     int goto_pts(double pts);
1991     int seek_phys();
1992     int read_program();
1993     int64_t prog2abs_fwd(int64_t byte, int64_t *nbyte, int *ntitle, int *ncell);
1994     int64_t prog2abs_rev(int64_t byte, int64_t *nbyte, int *ntitle, int *ncell);
1995     int64_t program_to_absolute(int64_t byte, int64_t *nbyte=0, int *ntitle=0, int *ncell=0);
1996     int64_t absolute_to_program(int64_t byte);
1997     int64_t title_bytes();
1998     void append_data(uint8_t *data, int bytes);
1999     void shift_data();
2000     int open_title(int title_number);
2001     int copy_titles(demuxer_t *dst);
2002     void end_title(int64_t end_byte);
2003     int next_code(uint32_t zcode);
2004     int prev_code(uint32_t zcode);
2005     uint8_t read_char_packet();
2006     uint8_t read_prev_char_packet();
2007     uint8_t read_char() {
2008       if( zunlikely(zdata.eof()) ) return read_char_packet();
2009       return zdata.buffer[zdata.position++];
2010     }
2011     uint8_t read_prev_char();
2012     int read_data(uint8_t *output,int size);
2013     int read_next_packet();
2014     int read_prev_packet();
2015     void skip_video_frame();
2016     int64_t next_cell();
2017     int64_t playinfo_next_cell();
2018     double video_pts() { double pts = pes_video_time; pes_video_time = -1.; return pts; }
2019     double audio_pts() { double pts = pes_audio_time; pes_audio_time = -1.; return pts; }
2020     void reset_pts();
2021     void set_audio_pts(uint64_t pts, const double denom);
2022     void set_video_pts(uint64_t pts, const double denom);
2023     int current_cell_no();
2024   };
2025
2026   class cacheframe_t {
2027   public:
2028     new_memset(0);
2029     uint8_t *y, *u, *v;
2030     int y_alloc, u_alloc, v_alloc;
2031     int y_size, u_size, v_size;
2032     int64_t frame_number;
2033     uint32_t age;
2034
2035     cacheframe_t() {}
2036     ~cacheframe_t() {}
2037   };
2038
2039   class cache_t {
2040     int extend_cache();
2041   public:
2042     new_memset(0);
2043     cacheframe_t *frames;
2044     int total;
2045     int allocation;
2046     uint32_t seq;
2047
2048     cache_t() {}
2049     ~cache_t();
2050     void clear();
2051     void reset() { total = 0; }
2052     void put_frame(int64_t zframe_number,
2053       uint8_t *zy, uint8_t *zu, uint8_t *zv,
2054       int zy_size, int zu_size, int zv_size);
2055     int get_frame( int64_t frame_number,
2056         uint8_t **zy, uint8_t **zu, uint8_t **zv);
2057     int has_frame(int64_t frame_number);
2058     int64_t memory_usage();
2059   };
2060
2061   fs_t *fs; // Store entry path here
2062   demuxer_t *demuxer; // Master title tables copied to all tracks
2063   int iopened; // file opened by user (before init)
2064
2065 // Media specific
2066
2067   int total_atracks;
2068   class atrack_t {
2069     void extend_sample_offsets();
2070   public:
2071     new_memset(0);
2072     int channels;
2073     int sample_rate;
2074     demuxer_t *demuxer;
2075     audio_t *audio;
2076     int64_t current_position;
2077     int64_t total_samples;
2078     int format;               // format of audio
2079     int number, pid;
2080     long nudge;
2081     // If we got the header information yet.  Used in streaming mode.
2082     int got_header;
2083     // Pointer to master table of contents when the TOC is read.
2084     // Pointer to private table when the TOC is being created
2085     // Stores the absolute byte of each audio chunk
2086     int64_t *sample_offsets;
2087     int total_sample_offsets;
2088     int sample_offsets_allocated;
2089     // If this sample offset table must be deleted by the track
2090     int private_offsets;
2091     // End of stream in table of contents construction
2092     int64_t audio_eof;
2093     // Starting byte of previous/current packet for making TOC
2094     int64_t prev_offset, curr_offset;
2095     double audio_time;     // audio pts based time
2096     int askip;             // skipping
2097     int64_t pts_position;  // sample position at pts
2098     double pts_origin;
2099     double pts_starttime;  // demuxer first pts
2100     double pts_offset;     // pts offset due to discontinuity
2101     double frame_pts;
2102     void reset_pts();
2103     double last_pts() { return pts_starttime+audio_time-pts_offset; }
2104
2105     atrack_t(zmpeg3_t *zsrc, int custom_id, int format, demuxer_t *demux, int no);
2106     ~atrack_t();
2107
2108     int calculate_format(zmpeg3_t *src);
2109     int handle_audio_data(int track_number);
2110     int handle_audio(int track_number);
2111     int64_t track_position() { return current_position+nudge; }
2112     void append_samples(int64_t offset);
2113     void update_frame_pts() { if( frame_pts < 0 ) frame_pts = demuxer->audio_pts(); }
2114     void update_audio_time();
2115     double get_audio_time();
2116     double pts_audio_time(double pts) {
2117       return pts_starttime<0. ? pts_starttime : pts-pts_starttime+pts_offset;
2118     }
2119     int64_t apparent_position();
2120   } *atrack[MAX_STREAMZ];
2121
2122   int total_vtracks;
2123   class vtrack_t {
2124     void extend_frame_offsets();
2125     void extend_keyframe_numbers();
2126   public:
2127     new_memset(0);
2128     int width, height;
2129     uint32_t tcode;
2130     double frame_rate;
2131     float aspect_ratio;
2132     demuxer_t *demuxer;
2133     video_t *video; // Video decoding object
2134     long current_position;  // Number of next frame to be played
2135     long total_frames;      // Total frames in the file
2136     int number, pid;
2137     slice_buffer_t *slice;  // toc slice data
2138     uint8_t *sbp;
2139     int sb_size;
2140     // Pointer to master table of contents when the TOC is read.
2141     // Pointer to private table when the TOC is being created
2142     // Stores the absolute byte of each frame
2143     int64_t *frame_offsets;
2144     int total_frame_offsets;
2145     int frame_offsets_allocated;
2146     int *keyframe_numbers;
2147     int total_keyframe_numbers;
2148     int keyframe_numbers_allocated;
2149     // Starting byte of previous/current packet for making TOC
2150     int64_t prev_frame_offset;
2151     int64_t prev_offset, curr_offset;
2152     int vskip;             // skipping
2153     double video_time;     // reshuffled pts
2154     // End of stream in table of contents construction
2155     int64_t video_eof;
2156     int got_top;
2157     int got_keyframe;
2158     cache_t *frame_cache;
2159     // If these tables must be deleted by the track
2160     int private_offsets;
2161     int pts_position;      // framenum at pts
2162     double pts_origin;
2163     double pts_starttime;  // first pts
2164     double pts_offset;     // pts offset due to discontinuity
2165     double refframe_pts;   // last refframe pts
2166     double frame_pts;
2167     double pts_video_time(double pts) {
2168       return pts_starttime<0. ? pts_starttime : pts-pts_starttime+pts_offset;
2169     }
2170     void reset_pts();
2171     double last_pts() { return pts_starttime+video_time-pts_offset; }
2172
2173     vtrack_t(zmpeg3_t *zsrc, int custom_id, demuxer_t *demux, int no);
2174     ~vtrack_t();
2175
2176     int handle_video_data(int track_number, int prev_data_size);
2177     int handle_video(int track_number);
2178     int find_keyframe_index(int64_t frame);
2179     void append_frame(int64_t offset, int is_keyframe);
2180     void update_frame_pts() { if( frame_pts < 0 ) frame_pts = demuxer->video_pts(); }
2181     void update_video_time();
2182     double get_video_time();
2183     int apparent_position();
2184   } *vtrack[MAX_STREAMZ];
2185
2186   // Subtitle track
2187   // Stores the program offsets of subtitle images.
2188   // Only used for seeking off of table of contents for editing.
2189   // Doesn't have its own demuxer but hangs off the video demuxer.
2190   int total_stracks;
2191   class strack_t {
2192     void extend_offsets();
2193     void extend_subtitles();
2194   public:
2195     new_memset(0);
2196     zrwlock_t rwlock;
2197     int id; // 0x2X
2198     video_t *video;   // if non-zero, decoder owns track
2199     int64_t *offsets; // Offsets in program of subtitle packets
2200     int total_offsets;
2201     int allocated_offsets;
2202     subtitle_t *subtitles[MAX_SUBTITLES]; // Last subtitle objects found in stream.
2203     int total_subtitles;
2204
2205     strack_t(int zid, video_t *vid=0);
2206     strack_t(strack_t &strack);
2207     ~strack_t();
2208
2209     int append_subtitle(subtitle_t *subtitle, int lock=1);
2210     void append_subtitle_offset(int64_t program_offset);
2211     void del_subtitle(subtitle_t *subtitle, int lock=0);
2212     void del_subtitle(int i, int lock=0);
2213     void del_all_subtitles();
2214   } *strack[MAX_STREAMZ];
2215
2216   static uint64_t get8bytes(uint8_t *buf) {
2217     return bswap_64(*((uint64_t *)buf));
2218   }
2219   static uint32_t get4bytes(uint8_t *buf) {
2220     return bswap_32(*((uint32_t *)buf));
2221   }
2222   static uint32_t get2bytes(uint8_t *buf) {
2223     return bswap_16(*((uint16_t *)buf));
2224   }
2225
2226   class icell_t {
2227   public:
2228     new_memset(0);
2229     int64_t start_byte, end_byte;  // Bytes relative to start of stream.
2230     short vob_id, cell_id;         // cell address vob/cell id
2231     uint32_t inlv;                 // bit vector of allowed interleaves
2232     short angle, discon;           // angle interleave no, discontinuity flag
2233
2234     int has_inlv(int i) { return (inlv >> i) & 1; }
2235   };
2236
2237   class icell_table_t {
2238   public:
2239     icell_t *cells;
2240     long total_cells;
2241     long cells_allocated;
2242     icell_table_t() { cells = 0;  total_cells = cells_allocated = 0; }
2243     ~icell_table_t();
2244     icell_t *append_cell();
2245   };
2246
2247   class ifo_t {
2248   public:
2249     new_memset(0);
2250     enum ifo_id_type {
2251       id_NUM_MENU_VOBS          = 0,
2252       id_NUM_TITLE_VOBS         = 1,
2253       id_MAT                    = 0,
2254       id_PTT                    = 1,
2255       id_TSP                    = 1,
2256       id_TITLE_PGCI             = 2,
2257       id_MENU_PGCI              = 3,
2258       id_TMT                    = 4,
2259       id_MENU_CELL_ADDR         = 5,
2260       id_MENU_VOBU_ADDR_MAP     = 6,
2261       id_TITLE_CELL_ADDR        = 7,
2262       id_TITLE_VOBU_ADDR_MAP    = 8,
2263     };
2264
2265     uint32_t num_menu_vobs;
2266     uint32_t vob_start;
2267     uint32_t empirical;               // scan for audio/subtitle stream data
2268     uint8_t *data[10];
2269     int fd;                           // file descriptor
2270     int64_t pos;                      // offset of ifo file on device 
2271     int current_vob_id;
2272     int max_inlv;
2273     int64_t current_byte;
2274 #include "ifo.h"
2275
2276     int type_vts() {
2277       return !strncmp((char*)data[id_MAT], "DVDVIDEO-VTS", 12) ? 0 : -1;
2278     }
2279     int type_vmg() {
2280       return !strncmp((char*)data[id_MAT], "DVDVIDEO-VMG", 12) ? 0 : -1;
2281     }
2282
2283     void get_playlist(zmpeg3_t *zsrc);
2284     int ifo_read(long pos, long count, uint8_t *data);
2285     int read_mat();
2286
2287     ifo_t(int zfd, long zpos);
2288     ~ifo_t();
2289     int ifo_close();
2290     int init_tables();
2291     int get_table(int64_t offset,unsigned long tbl_id);
2292     void get_palette(zmpeg3_t *zsrc);
2293     void get_header(demuxer_t *demux);
2294     void get_playinfo(zmpeg3_t *zsrc, icell_table_t *icell_addrs);
2295     void icell_addresses(icell_table_t *cell_addrs);
2296     int64_t ifo_chapter_cell_time(zmpeg3_t *zsrc, int chapter);
2297     void get_ititle(zmpeg3_t *zsrc, int chapter=0);
2298     void icell_map(zmpeg3_t *zsrc, icell_table_t *icell_addrs);
2299     int chk(int vts_title, int chapter, int inlv, int angle,
2300       icell_table_t *icell_addrs, int &sectors, int &pcells, int &max_angle);
2301   };
2302
2303   // Table of contents storage
2304   int64_t **frame_offsets;
2305   int64_t **sample_offsets;
2306   int **keyframe_numbers;
2307   int64_t *video_eof;
2308   int64_t *audio_eof;
2309   int *total_frame_offsets;
2310   int *total_sample_offsets;
2311   int64_t *total_samples;
2312   int *total_keyframe_numbers;
2313   // Handles changes in channel count after the start of a stream
2314   int *channel_counts, *nudging;
2315   // Indexes for audio tracks
2316   index_t **indexes;
2317   int total_indexes;
2318   double cell_time; // time at start of last cell
2319   // toc/skim thumbnail data callback
2320   zthumbnail_cb thumbnail_fn;
2321   void *thumbnail_priv;
2322
2323   // Number of bytes to devote to the index of a single track
2324   // in the index building process.
2325   int64_t index_bytes;
2326   int file_type, log_errs;
2327   int err_logging(int v=-1) { int lv = log_errs; if( v>=0 ) log_errs=v; return lv; }
2328   // Only one of these is set to 1 to specify what kind of stream we have.
2329   int is_transport_stream() { return file_type & FT_TRANSPORT_STREAM; }
2330   int is_program_stream() { return file_type & FT_PROGRAM_STREAM; }
2331   int is_audio_stream() { return file_type & FT_AUDIO_STREAM; } // Elemental stream
2332   int is_video_stream() { return file_type & FT_VIDEO_STREAM; } // Elemental stream
2333   int is_ifo_file() { return file_type & FT_IFO_FILE; } // dvd ifo file
2334   // Special kind of transport stream for BD or AVC-HD
2335   int is_bd() { return 0; /* file_type & FT_BD_FILE; */ }
2336   int packet_size; // > 0 if known otherwise determine empirically for every packet
2337   // Type and stream for getting current absolute byte
2338   int last_type_read;  // 1 - audio   2 - video
2339   int last_stream_read;
2340   int vts_title;  // video titleset title number (counting from 0)
2341   int total_vts_titles;
2342   int interleave, angle; // active program sector interleave/angle index
2343   int total_interleaves;
2344   int cpus; // number of decode threads
2345   int seekable; // Filesystem is seekable.  Also means the file isn't a stream.
2346   int last_cell_no; // last known cell no in TOC build
2347   int pts_padding; // use pts data to add padding to sync damaged data
2348   FILE *toc_fp; // For building TOC, the output file.
2349   int recd_fd; // record file
2350   int64_t recd_pos; // record file size
2351   /* The first color palette in the IFO file.  Used for subtitles.
2352    * Byte order: YUVX * 16 */
2353   int have_palette;
2354   uint8_t palette[16 * 4];
2355   // Date of source file index was created from.
2356   // Used to compare DVD source file to table of contents source.
2357   int64_t source_date;
2358   // playback cell table
2359   icell_table_t *playinfo;
2360
2361   int calculate_packet_size();
2362   int get_file_type(int *toc_atracks, int *toc_vtracks, const char *title_path);
2363   int read_toc(int *toc_atracks, int *toc_vtracks, const char *title_path);
2364   enum { show_toc_SAMPLE_OFFSETS=1, show_toc_AUDIO_INDEX=2, show_toc_FRAME_OFFSETS=4 };
2365   int show_toc(int flags);
2366   int handle_nudging();
2367   void divide_index(int track_number);
2368   int update_index(int track_number,int flush);
2369   static ifo_t *ifo_open(int fd,long pos);
2370   int read_ifo();
2371   atrack_t *new_atrack_t(int custom_id, int format,
2372     demuxer_t *demux, int number);
2373   vtrack_t *new_vtrack_t(int custom_id, demuxer_t *demux, int number);
2374   audio_t *new_audio_t(atrack_t *ztrack, int zformat);
2375   video_t *new_video_t(vtrack_t *ztrack);
2376   strack_t* get_strack_id(int id, video_t *vid);
2377   strack_t* get_strack(int number);
2378   strack_t* create_strack(int id, video_t *vid=0);
2379   int display_subtitle(int stream, int sid, int id,
2380     uint8_t *yp, uint8_t *up, uint8_t *vp, uint8_t *ap,
2381     int x, int y, int w, int h, double start_msecs, double stop_msecs);
2382   int delete_subtitle(int stream, int sid, int id);
2383   static int clip(int v, int mn, int mx) {
2384     if( v > mx ) return mx;
2385     if( v < mn ) return mn;
2386     return v;
2387   }
2388   static uint8_t clip(int32_t v) {
2389     return ((uint8_t)v) == v ? v : clip(v,0,255);
2390   }
2391   void handle_subtitle();
2392   void handle_cell(int this_cell_no);
2393
2394 #ifdef ZDVB
2395   class dvb_t {
2396     uint8_t *xbfr, *eob;
2397     uint32_t get8bits()  { return xbfr < eob ? *xbfr++ : 0; }
2398     uint32_t get16bits() { uint32_t v = get8bits();  return (v<<8) | get8bits(); }
2399     uint32_t get24bits() { uint32_t v = get16bits(); return (v<<8) | get8bits(); }
2400     uint32_t get32bits() { uint32_t v = get24bits(); return (v<<8) | get8bits(); }
2401   public:
2402     class mgt_t;  // master guide table
2403     class vct_t;  // virtual channel table
2404     class rrt_t;  // rating region table
2405     class eit_t;  // event information table
2406     class ett_t;  // extended text table
2407     class stt_t;  // system time table
2408
2409     class mgt_t {
2410     public:
2411       new_memset(0);
2412
2413       dvb_t *dvb;
2414       uint32_t ver;
2415       int items;
2416       class mitem_t {
2417       public:
2418         new_memset(0);
2419         uint8_t *bfr;
2420         int bfr_size, bfr_alloc;
2421         int src_id, tbl_id, tbl_len;
2422         uint16_t type;
2423         uint16_t pid;
2424         uint32_t version;
2425         uint32_t size;
2426         void init(int len);
2427         void clear();
2428         void extract(uint8_t *dat, int len);
2429         int bfr_len() { return  tbl_len - bfr_size; }
2430         mitem_t() {}
2431         mitem_t(int zpid) : pid(zpid) { bfr=0; bfr_size=bfr_alloc=0; }
2432         ~mitem_t() { clear(); }
2433       } *mitems;
2434       void clear();
2435       void extract();
2436       mitem_t *search(uint16_t pid);
2437       mgt_t(dvb_t *p) : dvb(p) {}
2438       ~mgt_t() { clear(); }
2439     } *mgt;
2440
2441     class vct_t {
2442     public:
2443       new_memset(0);
2444       class vitem_t;
2445
2446       dvb_t *dvb;
2447       uint32_t version;
2448       uint32_t transport_stream_id;
2449       int items, items_allocated;
2450
2451       class vitem_t {
2452       public:
2453         new_memset(0);
2454         class ch_elts_t;
2455
2456         uint16_t short_name[7+1];
2457         uint32_t major_channel_number;
2458         uint32_t minor_channel_number;
2459         uint32_t modulation_mode;
2460         uint32_t carrier_frequency;
2461         uint32_t channel_TSID;
2462         uint32_t program_number;
2463         uint32_t etm_location;
2464         uint8_t access_controlled;
2465         uint8_t hidden;
2466         uint8_t path_select;
2467         uint8_t out_of_band;
2468         uint32_t service_type;
2469         uint32_t source_id;
2470         uint32_t pcr_pid;
2471         int num_ch_elts;
2472         class ch_elts_t {
2473         public:
2474           uint32_t stream_id;
2475           uint32_t pes_pid;
2476           uint8_t  code_639[3];
2477           void extract(dvb_t *dvb);
2478         } elts[10];
2479         void extract(dvb_t *dvb);
2480       } **vct_tbl;
2481
2482       vct_t(dvb_t *p) : dvb(p) {}
2483       ~vct_t() { clear(); }
2484       void extract();
2485       void clear();
2486       int search(vitem_t &new_item);
2487       void append(vitem_t &new_item);
2488     } *tvct, *cvct;
2489
2490     class rrt_t {
2491     public:
2492       new_memset(0);
2493       class ritem_t;
2494
2495       dvb_t *dvb;
2496       uint32_t version;
2497       uint8_t region_nlen;
2498       uint8_t region_name[2*32+1];
2499       int items;
2500
2501       class ritem_t {
2502       public:
2503         new_memset(0);
2504         class rating_vt;
2505
2506         uint8_t dim_nlen;
2507         uint8_t dim_name[2*20+1];
2508         uint8_t graduated_scale;
2509         uint8_t num_values;
2510         class rating_vt {
2511         public:
2512           uint8_t rating_nlen;
2513           uint8_t rating_name[2*8+1];
2514           uint8_t rating_tlen;
2515           uint8_t rating_text[2*150+1];
2516           void extract(dvb_t *dvb);
2517         } *abrevs;
2518         void extract(dvb_t *dvb);
2519         void clear();
2520         ritem_t() {}
2521         ~ritem_t() { clear(); }
2522       } *ratings;
2523
2524       rrt_t(dvb_t *p) : dvb(p) {}
2525       ~rrt_t() { clear(); }
2526       void extract();
2527       void clear();
2528     } *rrt;
2529
2530     class eit_t {
2531     public:
2532       new_memset(0);
2533       class einfo_t;
2534
2535       dvb_t *dvb;
2536       eit_t *next;
2537       int id;
2538       uint32_t version;
2539       uint32_t source_id;
2540       int items, nitems;
2541
2542       class einfo_t {
2543       public:
2544         new_memset(0);
2545         uint16_t event_id;
2546         uint16_t location;
2547         uint32_t start_time;
2548         uint32_t seconds;
2549         uint8_t title_tlen;
2550         uint8_t *title_text;
2551         void extract(dvb_t *dvb);
2552         void clear();
2553         einfo_t() {}
2554         ~einfo_t() { clear(); }
2555       } *infos;
2556
2557       eit_t(dvb_t *p, int id) : dvb(p), id(id) {}
2558       ~eit_t() { clear(); }
2559       void extract();
2560       int search(uint16_t evt_id);
2561       void clear();
2562     } *eit;
2563
2564     class ett_t {
2565     public:
2566       new_memset(0);
2567       class etext_t;
2568
2569       dvb_t *dvb;
2570       ett_t *next;
2571       int id;
2572
2573       class etext_t {
2574       public:
2575         new_memset(0);
2576
2577         etext_t *next;
2578         int id;
2579         uint32_t version;
2580         uint16_t table_id;
2581         uint32_t etm_id;
2582         uint16_t msg_tlen;
2583         uint8_t *msg_text;
2584         void extract(dvb_t *dvb, uint32_t eid);
2585         void clear();
2586         etext_t(int id) : id(id) {}
2587         ~etext_t() { clear(); }
2588       } *texts;
2589
2590       ett_t(dvb_t *p, int id) : dvb(p), id(id) {}
2591       ~ett_t() { clear(); }
2592       void extract();
2593       void clear();
2594     } *ett;
2595
2596     class stt_t {
2597       dvb_t *dvb;
2598     public:
2599       new_memset(0);
2600
2601       uint32_t version;
2602       uint16_t table_id;
2603       uint32_t system_time;
2604       uint8_t utc_offset;
2605       uint16_t daylight_saving;
2606
2607       stt_t(dvb_t *p) : dvb(p) {}
2608       ~stt_t() { clear(); }
2609       void extract();
2610       void clear();
2611     } *stt;
2612
2613     uint32_t stt_start_time;
2614     int64_t stt_offset() {
2615       return (365*10+7)*24*3600L - (stt ? stt->utc_offset : 0);
2616     }
2617
2618     int64_t get_system_time() {
2619       return stt && stt->system_time ? stt->system_time + stt_offset() : -1;
2620     }
2621     zmpeg3_t *src;
2622     int sect_len;
2623     int stream_id;
2624     uint32_t version;
2625     int cur_next;
2626     int sect_num;
2627     int proto_ver;
2628     int empirical;
2629
2630     int bfr_pos()  { return xbfr - active->bfr; }
2631     int bfr_len()  { return active->bfr_size - bfr_pos(); }
2632     void skip_bfr(int n);
2633     void skp_bfr(int n) { if( n > 0 ) skip_bfr(n); }
2634
2635     int text_length, text_allocated;
2636     char *text;
2637     int get_text(uint8_t *dat, int bytes);
2638     void append_text(char *dat, int bytes);
2639     char *mstring(uint8_t *bp, int len);
2640
2641     dvb_t(zmpeg3_t *zsrc);
2642     ~dvb_t();
2643     void reset();
2644     void extract();
2645
2646     mgt_t::mitem_t *active;
2647     mgt_t::mitem_t *atsc_pid(int pid);
2648     mgt_t::mitem_t base_pid;
2649
2650     int atsc_tables(demuxer_t *demux, int pid);
2651     void skip_descr(int descr_len);
2652
2653     int channel_count();
2654     int signal_time();
2655     int get_channel(int n, int &major, int &minor);
2656     int get_station_id(int n, char *name);
2657     int total_astreams(int n, int &count);
2658     int astream_number(int n, int ord, int &stream, char *enc=0);
2659     int total_vstreams(int n, int &count);
2660     int vstream_number(int n, int ord, int &stream);
2661     int read_dvb(demuxer_t *demux);
2662     int get_chan_info(int n, int ord, int i, char *txt, int len);
2663   } dvb;
2664
2665 #endif
2666
2667   // Interface
2668
2669   // Get version information
2670   static int zmajor()   { return ZMPEG3_MAJOR; };
2671   static int zminor()   { return ZMPEG3_MINOR; };
2672   static int zrelease() { return ZMPEG3_RELEASE; };
2673
2674   // Check for file compatibility.  Return 1 if compatible.
2675   static int check_sig(char *path);
2676
2677   // Open the MPEG stream.
2678   // An error code is put into *ret if it fails and error_return is nonzero.
2679   zmpeg3_t(const char *path);
2680   zmpeg3_t(const char *path, int &ret, int access=fs_t::io_UNBUFFERED, const char *title_path=0);
2681   zmpeg3_t(int fd, int &ret, int access=0);
2682   zmpeg3_t(FILE *fp, int &ret, int access=0);
2683   int init(const char *title_path=0);
2684   ~zmpeg3_t();
2685
2686   // Performance
2687   int set_cpus(int cpus);
2688   int set_pts_padding(int v);
2689
2690   // Query the MPEG3 stream about audio.
2691   int has_audio();
2692   int total_astreams();
2693   int audio_channels(int stream);
2694   double sample_rate(int stream);
2695   const char *audio_format(int stream);
2696
2697   // Total length obtained from the timecode.
2698   // For DVD files, this is unreliable.
2699   long audio_nudge(int stream); 
2700   long audio_samples(int stream); 
2701   int set_sample(long sample, int stream);
2702   long get_sample(int stream);
2703
2704   // Stream defines the number of the multiplexed stream to read.
2705   // If output argument is null the audio is not rendered.
2706   // Read a PCM buffer of audio from 1 channel and advance the position.
2707   int read_audio(void *output_v, int type, int channel, long samples, int stream);
2708   int read_audio(double *output_d, int channel, long samples, int stream);
2709   int read_audio(float *output_f, int channel, long samples, int stream);
2710   int read_audio(int *output_i, int channel, long samples, int stream);
2711   int read_audio(short *output_s, int channel, long samples, int stream);
2712   // Read a PCM buffer of audio from 1 channel without advancing the position.
2713   int reread_audio(void *output_v, int type, int channel, long samples, int stream);
2714   int reread_audio(double *output_d, int channel, long samples, int stream);
2715   int reread_audio(float *output_f, int channel, long samples, int stream);
2716   int reread_audio(int *output_i, int channel, long samples, int stream);
2717   int reread_audio(short *output_s, int channel, long samples, int stream);
2718
2719   // Read the next compressed audio chunk.  Store the size in size and return a 
2720   // Stream defines the number of the multiplexed stream to read.
2721   int read_audio_chunk(uint8_t *output, long *size, long max_size, int stream);
2722
2723   // Query the stream about video.
2724   int has_video();
2725   int total_vstreams();
2726   int video_width(int stream);
2727   int video_height(int stream);
2728   int coded_width(int stream);
2729   int coded_height(int stream);
2730   int video_pid(int stream);
2731   float aspect_ratio(int stream); // aspect ratio.  0 if none
2732   double frame_rate(int stream);  // Frames/sec
2733
2734   long video_frames(int stream);  // total length - for TOC files only.
2735   int set_frame(long frame, int stream); // Seek to a frame
2736   // int skip_frames(); /*???*/
2737   long get_frame(int stream);            // Tell current position
2738
2739   // Total bytes.  Used for absolute byte seeking.
2740   int64_t get_bytes();
2741
2742   // Seek all the tracks to the absolute byte in the 
2743   // file.  This eliminates the need for tocs but doesn't 
2744   // give frame accuracy.
2745   int seek_byte(int64_t byte);
2746   int64_t tell_byte();
2747
2748   int previous_frame(int stream);
2749   int end_of_audio(int stream);
2750   int end_of_video(int stream);
2751
2752   // Give the seconds time in the last packet read
2753   double get_time();
2754   double get_audio_time(int stream);
2755   double get_video_time(int stream);
2756   int get_cell_time(int no, double &time);
2757
2758   // Read input frame and scale to the output frame
2759   // The last row of **output_rows must contain 4 extra bytes for scratch work.
2760   int read_frame(uint8_t **output_rows, // row start pointers
2761     int in_x, int in_y, int in_w, int in_h, // Location in input frame
2762     int out_w, int out_h, // Dimensions of output_rows
2763     int color_model, int stream);
2764
2765   // Get the colormodel being used natively by the stream
2766   int colormodel(int stream);
2767   // Set the row stride to be used in read_yuvframe
2768   int set_rowspan(int bytes, int stream);
2769
2770   // Read a frame in the native color model used by the stream. 
2771   // The Y, U, and V planes are copied into the y, u, and v
2772   // BUFFERS Provided.
2773   // The input is cropped to the dimensions given but not scaled.
2774   int read_yuvframe(char *y_output, char *u_output, char *v_output,
2775     int in_x, int in_y, int in_w, int in_h, int stream);
2776
2777   // Read a frame in the native color model used by the stream. 
2778   // The Y, U, and V planes are not copied but the _output pointers
2779   // are redirected to the frame buffer.
2780   int read_yuvframe_ptr(char **y_output, char **u_output, char **v_output,
2781     int stream);
2782
2783   // Drop frames number of frames
2784   int drop_frames(long frames, int stream);
2785
2786   // Read the next compressed frame including headers.
2787   // Store the size in size and return a 1 if error.
2788   // Stream defines the number of the multiplexed stream to read.
2789   int read_video_chunk(uint8_t *output, long *size, long max_size,
2790     int stream);
2791
2792   // Master control
2793   int get_total_vts_titles();
2794   int set_vts_title(int title=-1);
2795   int get_total_interleaves();
2796   int set_interleave(int inlv=-1);
2797   int set_angle(int a=-1);
2798   int set_program(int no); // legacy
2799
2800   // Memory used by video caches.
2801   int64_t memory_usage();
2802   // write incoming datastream on file descr fd
2803   //   buffer access must be io_THREADED.  useful to record dvb device data
2804   //   bsz records up to bsz bytes of past buffer data in write_align
2805   int start_record(int fd, int bsz=0);
2806   int stop_record();
2807   void write_record(uint8_t *data, int len);
2808   // limit position for start of last full packet
2809   int64_t record_position() { return recd_pos - packet_size + 1; }
2810   // restart streams, discard device buffer and reinit file positions
2811   void restart();
2812   // enable/disable data xfr from reader thread
2813   int pause_reader(int v);
2814
2815   // subtitle functions
2816   // get number of subtitle tracks
2817   int subtitle_tracks() { return total_stracks; }
2818   // Enable overlay of a subtitle track.
2819   // track - the number of the subtitle track starting from 0
2820   // The same subtitle track is overlayed for all video tracks.
2821   // track=-1 to disable subtitles.
2822   int show_subtitle(int stream, int strk);
2823
2824   // Table of contents generation
2825   // Begin constructing table of contents
2826   static zmpeg3_t *start_toc(const char *path, const char *toc_path,
2827     int program=0, int64_t *total_bytes=0);
2828   // Set the maximum number of bytes per index track
2829   void set_index_bytes(int64_t bytes) { index_bytes = bytes; }
2830   // Process one packet
2831   int do_toc(int64_t *bytes_processed);
2832   // Write table of contents
2833   void stop_toc();
2834   int set_thumbnail_callback(int trk, int skim, int thumb, zthumbnail_cb fn, void *p);
2835   int get_thumbnail(int trk, int64_t &frn, uint8_t *&t, int &w, int &h);
2836   int set_cc_text_callback(int trk, zcc_text_cb fn);
2837
2838   // Get modification date of source file from table of contents.
2839   // Used to compare DVD source file to table of contents source.
2840   int64_t get_source_date() { return source_date; }
2841   // Get modification date of source file from source file.
2842   static int64_t calculate_source_date(char *path);
2843   static int64_t calculate_source_date(int fd);
2844   // Table of contents queries
2845   int index_tracks();
2846   int index_channels(int track);
2847   int index_zoom();
2848   int index_size(int track);
2849   float* index_data(int track, int channel);
2850   // Returns 1 if the file has a table of contents
2851   int has_toc() {
2852     return frame_offsets || sample_offsets ? 1 : 0;
2853   }
2854   // Return the path of the title number or 0 if no more titles.
2855   char* title_path(int number) {
2856     return number>=0 && number<demuxer->total_titles ?
2857       demuxer->titles[number]->fs->path : 0;
2858   }
2859
2860   static inline void complete_path(char *full_path, char *path) {
2861     char dir[zmpeg3_t::STRLEN];
2862     if( path[0] != '/' && getcwd(dir, sizeof(dir)) )
2863       sprintf(full_path, "%s/%s", dir, path);
2864     else
2865       strcpy(full_path, path);
2866   }
2867
2868   static inline void get_directory(char *directory, char *path) {
2869     char *ptr = strrchr(path, '/');
2870     int i = 0;
2871     if( ptr ) {
2872       int n = ptr-path;
2873       while( i < n ) {
2874         directory[i] = path[i];
2875         ++i;
2876       }
2877     }
2878     if( i == 0 ) directory[i++] = '.';
2879     directory[i] = 0;
2880   }
2881
2882   static inline void get_filename(char *filename, char *path) {
2883     char *ptr = strrchr(path, '/');
2884     if( ptr ) ++ptr;
2885     else ptr = path;
2886     strcpy(filename, ptr);
2887   }
2888
2889   static inline void joinpath(char *path, char *dir, char *filename) {
2890     sprintf(path, "%s/%s", dir, filename);
2891   }
2892
2893   static inline int64_t path_total_bytes(char *path) {
2894     struct stat64 st;
2895     return stat64(path, &st )<0 ? 0 : st.st_size;
2896   }
2897
2898 };
2899
2900 typedef zmpeg3_t::zlock_t                       zzlock_t;
2901 typedef zmpeg3_t::zblock_t                      zzblock_t;
2902 typedef zmpeg3_t::zrwlock_t                     zzrwlock_t;
2903 typedef zmpeg3_t::fs_t                          zfs_t;
2904 typedef   zfs_t::css_t                          zcss_t;
2905 typedef     zcss_t::key_t                       zkey_t;
2906 typedef     zcss_t::blk_t                       zblk_t;
2907 typedef     zcss_t::playkey_t                   zplaykey_t;
2908 typedef   zfs_t::buffer_t                       zbuffer_t;
2909 typedef zmpeg3_t::bits_t                        zbits_t;
2910 typedef zmpeg3_t::index_t                       zindex_t;
2911 typedef zmpeg3_t::bitfont_t                     zbitfont_t;
2912 typedef   zbitfont_t::bitchar_t                 zbitchar_t;
2913 typedef   zbitfont_t::static_init_t             zstatic_init_t;
2914 typedef zmpeg3_t::timecode_t                    ztimecode_t;
2915 typedef zmpeg3_t::audio_t                       zaudio_t;
2916 typedef   zaudio_t::imdct_complex_t             zimdct_complex_t;
2917 typedef   zaudio_t::imdct_al_table_t            zimdct_al_table_t;
2918 typedef   zaudio_t::audio_decoder_layer_t       zaudio_decoder_layer_t;
2919 typedef   zaudio_t::audio_decoder_ac3_t         zaudio_decoder_ac3_t;
2920 typedef   zaudio_t::audio_decoder_pcm_t         zaudio_decoder_pcm_t;
2921 typedef zmpeg3_t::VLCtab_t                      zVLCtab_t;
2922 typedef zmpeg3_t::DCTtab_t                      zDCTtab_t;
2923 typedef zmpeg3_t::slice_buffer_t                zslice_buffer_t;
2924 typedef zmpeg3_t::video_t                       zvideo_t;
2925 typedef   zvideo_t::cc_t                        zcc_t;
2926 typedef     zcc_t::svc_t                        zsvc_t;
2927 typedef       zsvc_t::win_t                     zwin_t;
2928 typedef       zsvc_t::chr_t                     zchr_t;
2929 typedef zmpeg3_t::slice_decoder_t               zslice_decoder_t;
2930 typedef zmpeg3_t::subtitle_t                    zsubtitle_t;
2931 typedef zmpeg3_t::demuxer_t                     zdemuxer_t;
2932 typedef   zdemuxer_t::zstream_t                 zzstream_t;
2933 typedef   zdemuxer_t::title_t                   ztitle_t;
2934 typedef     ztitle_t::cell_t                    zcell_t;
2935 typedef zmpeg3_t::cacheframe_t                  zcacheframe_t;
2936 typedef zmpeg3_t::cache_t                       zcache_t;
2937 typedef zmpeg3_t::atrack_t                      zatrack_t;
2938 typedef zmpeg3_t::vtrack_t                      zvtrack_t;
2939 typedef zmpeg3_t::strack_t                      zstrack_t;
2940 typedef zmpeg3_t::icell_t                       zicell_t;
2941 typedef zmpeg3_t::icell_table_t                 zicell_table_t;
2942 typedef zmpeg3_t::ifo_t                         zifo_t;
2943 #ifdef ZDVB
2944 typedef zmpeg3_t::dvb_t                         zdvb_t;
2945 typedef   zdvb_t::mgt_t                         zmgt_t;
2946 typedef     zmgt_t::mitem_t                     zmitem_t;
2947 typedef   zdvb_t::vct_t                         zvct_t;
2948 typedef     zvct_t::vitem_t                     zvitem_t;
2949 typedef       zvitem_t::ch_elts_t               zch_elts_t;
2950 typedef   zdvb_t::rrt_t                         zrrt_t;
2951 typedef     zrrt_t::ritem_t                     zritem_t;
2952 typedef       zritem_t::rating_vt               zrating_vt;
2953 typedef   zdvb_t::eit_t                         zeit_t;
2954 typedef     zeit_t::einfo_t                     zeinfo_t;
2955 typedef   zdvb_t::ett_t                         zett_t;
2956 typedef     zett_t::etext_t                     zetext_t;
2957 typedef   zdvb_t::stt_t                         zstt_t;
2958 #endif
2959
2960 /* legacy */
2961 extern "C" {
2962 #else
2963 typedef struct {} zmpeg3_t;
2964 #endif /*__cplusplus */
2965 typedef zmpeg3_t mpeg3_t;
2966
2967 int mpeg3_major(void);
2968 int mpeg3_minor(void);
2969 int mpeg3_release(void);
2970 int mpeg3_check_sig(char *path);
2971 int mpeg3_is_program_stream(zmpeg3_t * zsrc);
2972 int mpeg3_is_transport_stream(zmpeg3_t * zsrc);
2973 int mpeg3_is_video_stream(zmpeg3_t * zsrc);
2974 int mpeg3_is_audio_stream(zmpeg3_t * zsrc);
2975 int mpeg3_is_ifo_file(zmpeg3_t * zsrc);
2976 int mpeg3_create_title(zmpeg3_t * zsrc,int full_scan);
2977 zmpeg3_t *mpeg3_open(const char *path,int *error_return);
2978 zmpeg3_t *mpeg3_open_title(const char *title_path,const char *path,int *error_return);
2979 zmpeg3_t *mpeg3_zopen(const char *title_path,const char *path,int *error_return, int access);
2980 zmpeg3_t *mpeg3_open_copy(const char *path,zmpeg3_t *old_src,int *error_return);
2981 int mpeg3_close(zmpeg3_t *zsrc);
2982 int mpeg3_set_pts_padding(zmpeg3_t *zsrc, int v);
2983 int mpeg3_set_cpus(zmpeg3_t *zsrc,int cpus);
2984 int mpeg3_has_audio(zmpeg3_t *zsrc);
2985 int mpeg3_total_astreams(zmpeg3_t *zsrc);
2986 int mpeg3_audio_channels(zmpeg3_t *zsrc,int stream);
2987 int mpeg3_sample_rate(zmpeg3_t *zsrc,int stream);
2988 const char *mpeg3_audio_format(zmpeg3_t *zsrc,int stream);
2989 long mpeg3_get_audio_nudge(zmpeg3_t *zsrc,int stream);
2990 long mpeg3_audio_samples(zmpeg3_t *zsrc,int stream);
2991 int mpeg3_set_sample(zmpeg3_t *zsrc,long sample,int stream);
2992 long mpeg3_get_sample(zmpeg3_t *zsrc,int stream);
2993 int mpeg3_read_audio(zmpeg3_t *zsrc,float *output_f,short *output_i,int channel,
2994    long samples,int stream);
2995 int mpeg3_read_audio_d(zmpeg3_t *zsrc,double *output_d, int channel,
2996    long samples, int stream);
2997 int mpeg3_read_audio_f(zmpeg3_t *zsrc,float *output_f, int channel,
2998    long samples, int stream);
2999 int mpeg3_read_audio_i(zmpeg3_t *zsrc,int *output_i, int channel,
3000    long samples, int stream);
3001 int mpeg3_read_audio_s(zmpeg3_t *zsrc,short *output_s, int channel,
3002    long samples, int stream);
3003 int mpeg3_reread_audio_d(zmpeg3_t *zsrc,double *output_d, int channel,
3004    long samples, int stream);
3005 int mpeg3_reread_audio_f(zmpeg3_t *zsrc,float *output_f, int channel,
3006    long samples, int stream);
3007 int mpeg3_reread_audio_i(zmpeg3_t *zsrc,int *output_i, int channel,
3008    long samples, int stream);
3009 int mpeg3_reread_audio_s(zmpeg3_t *zsrc,short *output_s, int channel,
3010    long samples, int stream);
3011 int mpeg3_reread_audio(zmpeg3_t *zsrc,float *output_f,short *output_i,
3012    int channel,long samples,int stream);
3013 int mpeg3_read_audio_chunk(zmpeg3_t *zsrc,unsigned char *output,long *size,
3014    long max_size,int stream);
3015 int mpeg3_has_video(zmpeg3_t *zsrc);
3016 int mpeg3_total_vstreams(zmpeg3_t *zsrc);
3017 int mpeg3_video_width(zmpeg3_t *zsrc,int stream);
3018 int mpeg3_video_height(zmpeg3_t *zsrc,int stream);
3019 int mpeg3_coded_width(zmpeg3_t *zsrc,int stream);
3020 int mpeg3_coded_height(zmpeg3_t *zsrc,int stream);
3021 int mpeg3_video_pid(zmpeg3_t *zsrc,int stream);
3022 float mpeg3_aspect_ratio(zmpeg3_t *zsrc,int stream);
3023 double mpeg3_frame_rate(zmpeg3_t *zsrc,int stream);
3024 long mpeg3_video_frames(zmpeg3_t *zsrc,int stream);
3025 int mpeg3_set_frame(zmpeg3_t *zsrc,long frame,int stream);
3026 //int mpeg3_skip_frames(zmpeg3_t *zsrc);
3027 long mpeg3_get_frame(zmpeg3_t *zsrc,int stream);
3028 int64_t mpeg3_get_bytes(zmpeg3_t *zsrc);
3029 int mpeg3_seek_byte(zmpeg3_t *zsrc,int64_t byte);
3030 int64_t mpeg3_tell_byte(zmpeg3_t *zsrc);
3031 int mpeg3_previous_frame(zmpeg3_t *zsrc,int stream);
3032 int mpeg3_end_of_audio(zmpeg3_t *zsrc,int stream);
3033 int mpeg3_end_of_video(zmpeg3_t *zsrc,int stream);
3034 double mpeg3_get_time(zmpeg3_t *zsrc);
3035 double mpeg3_get_audio_time(zmpeg3_t *zsrc, int stream);
3036 double mpeg3_get_video_time(zmpeg3_t *zsrc, int stream);
3037 double mpeg3_get_cell_time(zmpeg3_t *zsrc, int no, double *time);
3038 int mpeg3_read_frame(zmpeg3_t *zsrc,unsigned char **output_rows,int in_x,
3039    int in_y,int in_w,int in_h,int out_w,int out_h,int color_model,int stream);
3040 int mpeg3_colormodel(zmpeg3_t *zsrc,int stream);
3041 int mpeg3_set_rowspan(zmpeg3_t *zsrc,int bytes,int stream);
3042 int mpeg3_read_yuvframe(zmpeg3_t *zsrc,char *y_output,char *u_output,
3043    char *v_output,int in_x,int in_y,int in_w,int in_h,int stream);
3044 int mpeg3_read_yuvframe_ptr(zmpeg3_t *zsrc,char **y_output,char **u_output,
3045    char **v_output,int stream);
3046 int mpeg3_drop_frames(zmpeg3_t *zsrc,long frames,int stream);
3047 int mpeg3_read_video_chunk(zmpeg3_t *zsrc,unsigned char *output,long *size,
3048    long max_size,int stream);
3049 int mpeg3_get_total_vts_titles(zmpeg3_t *zsrc);
3050 int mpeg3_set_vts_title(zmpeg3_t *zsrc,int title); // toc build only
3051 int mpeg3_get_total_interleaves(zmpeg3_t *zsrc);
3052 int mpeg3_set_interleave(zmpeg3_t *zsrc,int inlv); // toc build only
3053 int mpeg3_set_angle(zmpeg3_t *zsrc,int a); // toc build only
3054 int mpeg3_set_program(zmpeg3_t *zsrc,int no); // toc build only
3055 int64_t mpeg3_memory_usage(zmpeg3_t *zsrc);
3056 int mpeg3_get_thumbnail(zmpeg3_t *zsrc, int trk,
3057    int64_t *frn, uint8_t **t, int *w, int *h);
3058 int mpeg3_set_thumbnail_callback(zmpeg3_t *zsrc, int trk,
3059    int skim, int thumb, zthumbnail_cb fn, void *p);
3060 int mpeg3_set_cc_text_callback(zmpeg3_t *zsrc, int trk, zcc_text_cb fn);
3061 int mpeg3_subtitle_tracks(zmpeg3_t *zsrc);
3062 int mpeg3_show_subtitle(zmpeg3_t *zsrc,int vtrk, int strk);
3063 int mpeg3_display_subtitle(zmpeg3_t *zsrc,int stream,int sid,int id,
3064    uint8_t *yp,uint8_t *up,uint8_t *vp,uint8_t *ap,
3065    int x,int y,int w,int h,double start_msecs,double stop_msecs);
3066 int mpeg3_delete_subtitle(zmpeg3_t *zsrc,int stream,int sid,int id);
3067 zmpeg3_t *mpeg3_start_toc(char *path,char *toc_path,int program,int64_t *total_bytes);
3068 void mpeg3_set_index_bytes(zmpeg3_t *zsrc,int64_t bytes);
3069 int mpeg3_do_toc(zmpeg3_t *zsrc,int64_t *bytes_processed);
3070 void mpeg3_stop_toc(zmpeg3_t *zsrc);
3071 int64_t mpeg3_get_source_date(zmpeg3_t *zsrc);
3072 int64_t mpeg3_calculate_source_date(char *path);
3073 int mpeg3_index_tracks(zmpeg3_t *zsrc);
3074 int mpeg3_index_channels(zmpeg3_t *zsrc,int track);
3075 int mpeg3_index_zoom(zmpeg3_t *zsrc);
3076 int mpeg3_index_size(zmpeg3_t *zsrc,int track);
3077 float *mpeg3_index_data(zmpeg3_t *zsrc,int track,int channel);
3078 int mpeg3_has_toc(zmpeg3_t *zsrc);
3079 char *mpeg3_title_path(zmpeg3_t *zsrc,int number);
3080 // hooks needed for quicktime
3081 typedef struct {} mpeg3_layer_t;
3082 int mpeg3audio_dolayer3(mpeg3_layer_t *audio,
3083    char *frame, int frame_size, float **output, int render);
3084 int mpeg3_layer_header(mpeg3_layer_t *layer_data, unsigned char *data);
3085 void mpeg3_layer_reset(mpeg3_layer_t *zlayer_data);
3086 mpeg3_layer_t* mpeg3_new_layer();
3087 void mpeg3_delete_layer(mpeg3_layer_t *audio);
3088 // hooks needed for mplexlo
3089 void mpeg3_skip_video_frame(mpeg3_t *zsrc, int stream);
3090 int64_t mpeg3_video_tell_byte(mpeg3_t *zsrc, int stream);
3091 int64_t mpeg3_audio_tell_byte(mpeg3_t *zsrc, int stream);
3092 #ifdef ZDVB
3093 int mpeg3_dvb_channel_count(zmpeg3_t *zsrc);
3094 int mpeg3_dvb_get_channel(mpeg3_t *zsrc,int n, int *major, int *minor);
3095 int mpeg3_dvb_get_station_id(mpeg3_t *zsrc,int n, char *name);
3096 int mpeg3_dvb_total_astreams(mpeg3_t *zsrc,int n, int *count);
3097 int mpeg3_dvb_astream_number(mpeg3_t *zsrc,int n, int ord, int *stream, char *enc);
3098 int mpeg3_dvb_total_vstreams(mpeg3_t *zsrc,int n, int *count);
3099 int mpeg3_dvb_vstream_number(mpeg3_t *zsrc,int n, int ord, int *stream);
3100 int mpeg3_dvb_get_chan_info(mpeg3_t *zsrc,int n, int ord, int i, char *cp, int len);
3101 int mpeg3_dvb_get_system_time(mpeg3_t *zsrc, int64_t *tm);
3102 #endif
3103 #ifdef __cplusplus
3104 }
3105 #endif
3106 #endif