tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

nestegg.c (92756B)


      1 /*
      2 * Copyright © 2010 Mozilla Foundation
      3 *
      4 * This program is made available under an ISC-style license.  See the
      5 * accompanying file LICENSE for details.
      6 */
      7 #include <assert.h>
      8 #include <stddef.h>
      9 #include <stdlib.h>
     10 #include <string.h>
     11 
     12 #include "nestegg/nestegg.h"
     13 
     14 /* EBML Elements */
     15 #define ID_EBML                     0x1a45dfa3
     16 #define ID_EBML_VERSION             0x4286
     17 #define ID_EBML_READ_VERSION        0x42f7
     18 #define ID_EBML_MAX_ID_LENGTH       0x42f2
     19 #define ID_EBML_MAX_SIZE_LENGTH     0x42f3
     20 #define ID_DOCTYPE                  0x4282
     21 #define ID_DOCTYPE_VERSION          0x4287
     22 #define ID_DOCTYPE_READ_VERSION     0x4285
     23 
     24 /* Global Elements */
     25 #define ID_VOID                     0xec
     26 #define ID_CRC32                    0xbf
     27 
     28 /* WebM Elements */
     29 #define ID_SEGMENT                  0x18538067
     30 
     31 /* Seek Head Elements */
     32 #define ID_SEEK_HEAD                0x114d9b74
     33 #define ID_SEEK                     0x4dbb
     34 #define ID_SEEK_ID                  0x53ab
     35 #define ID_SEEK_POSITION            0x53ac
     36 
     37 /* Info Elements */
     38 #define ID_INFO                     0x1549a966
     39 #define ID_TIMECODE_SCALE           0x2ad7b1
     40 #define ID_DURATION                 0x4489
     41 
     42 /* Cluster Elements */
     43 #define ID_CLUSTER                  0x1f43b675
     44 #define ID_TIMECODE                 0xe7
     45 #define ID_BLOCK_GROUP              0xa0
     46 #define ID_SIMPLE_BLOCK             0xa3
     47 
     48 /* BlockGroup Elements */
     49 #define ID_BLOCK                    0xa1
     50 #define ID_BLOCK_ADDITIONS          0x75a1
     51 #define ID_BLOCK_DURATION           0x9b
     52 #define ID_REFERENCE_BLOCK          0xfb
     53 #define ID_DISCARD_PADDING          0x75a2
     54 
     55 /* BlockAdditions Elements */
     56 #define ID_BLOCK_MORE               0xa6
     57 
     58 /* BlockMore Elements */
     59 #define ID_BLOCK_ADD_ID             0xee
     60 #define ID_BLOCK_ADDITIONAL         0xa5
     61 
     62 /* Tracks Elements */
     63 #define ID_TRACKS                   0x1654ae6b
     64 #define ID_TRACK_ENTRY              0xae
     65 #define ID_TRACK_NUMBER             0xd7
     66 #define ID_TRACK_UID                0x73c5
     67 #define ID_TRACK_TYPE               0x83
     68 #define ID_FLAG_ENABLED             0xb9
     69 #define ID_FLAG_DEFAULT             0x88
     70 #define ID_FLAG_LACING              0x9c
     71 #define ID_TRACK_TIMECODE_SCALE     0x23314f
     72 #define ID_LANGUAGE                 0x22b59c
     73 #define ID_CODEC_ID                 0x86
     74 #define ID_CODEC_PRIVATE            0x63a2
     75 #define ID_CODEC_DELAY              0x56aa
     76 #define ID_SEEK_PREROLL             0x56bb
     77 #define ID_DEFAULT_DURATION         0x23e383
     78 
     79 /* Video Elements */
     80 #define ID_VIDEO                    0xe0
     81 #define ID_STEREO_MODE              0x53b8
     82 #define ID_ALPHA_MODE               0x53c0
     83 #define ID_PIXEL_WIDTH              0xb0
     84 #define ID_PIXEL_HEIGHT             0xba
     85 #define ID_PIXEL_CROP_BOTTOM        0x54aa
     86 #define ID_PIXEL_CROP_TOP           0x54bb
     87 #define ID_PIXEL_CROP_LEFT          0x54cc
     88 #define ID_PIXEL_CROP_RIGHT         0x54dd
     89 #define ID_DISPLAY_WIDTH            0x54b0
     90 #define ID_DISPLAY_HEIGHT           0x54ba
     91 #define ID_COLOUR                   0x55b0
     92 
     93 /* Audio Elements */
     94 #define ID_AUDIO                    0xe1
     95 #define ID_SAMPLING_FREQUENCY       0xb5
     96 #define ID_CHANNELS                 0x9f
     97 #define ID_BIT_DEPTH                0x6264
     98 
     99 /* Cues Elements */
    100 #define ID_CUES                     0x1c53bb6b
    101 #define ID_CUE_POINT                0xbb
    102 #define ID_CUE_TIME                 0xb3
    103 #define ID_CUE_TRACK_POSITIONS      0xb7
    104 #define ID_CUE_TRACK                0xf7
    105 #define ID_CUE_CLUSTER_POSITION     0xf1
    106 #define ID_CUE_BLOCK_NUMBER         0x5378
    107 
    108 /* Encoding Elements */
    109 #define ID_CONTENT_ENCODINGS        0x6d80
    110 #define ID_CONTENT_ENCODING         0x6240
    111 #define ID_CONTENT_ENCODING_TYPE    0x5033
    112 
    113 /* Encryption Elements */
    114 #define ID_CONTENT_ENCRYPTION       0x5035
    115 #define ID_CONTENT_ENC_ALGO         0x47e1
    116 #define ID_CONTENT_ENC_KEY_ID       0x47e2
    117 #define ID_CONTENT_ENC_AES_SETTINGS 0x47e7
    118 #define ID_AES_SETTINGS_CIPHER_MODE 0x47e8
    119 
    120 /* Colour Elements */
    121 #define ID_MATRIX_COEFFICIENTS      0x55b1
    122 #define ID_RANGE                    0x55b9
    123 #define ID_TRANSFER_CHARACTERISTICS 0x55ba
    124 #define ID_PRIMARIES                0x55bb
    125 #define ID_MASTERING_METADATA       0x55d0
    126 
    127 /* MasteringMetadata Elements */
    128 #define ID_PRIMARY_R_CHROMATICITY_X   0x55d1
    129 #define ID_PRIMARY_R_CHROMATICITY_Y   0x55d2
    130 #define ID_PRIMARY_G_CHROMATICITY_X   0x55d3
    131 #define ID_PRIMARY_G_CHROMATICITY_Y   0x55d4
    132 #define ID_PRIMARY_B_CHROMATICITY_X   0x55d5
    133 #define ID_PRIMARY_B_CHROMATICITY_Y   0x55d6
    134 #define ID_WHITE_POINT_CHROMATICITY_X 0x55d7
    135 #define ID_WHITE_POINT_CHROMATICITY_Y 0x55d8
    136 #define ID_LUMINANCE_MAX              0x55d9
    137 #define ID_LUMINANCE_MIN              0x55da
    138 
    139 /* Other Elements */
    140 #define ID_CHAPTERS                   0x1043a770
    141 #define ID_ATTACHMENTS                0x1941a469
    142 #define ID_TAGS                       0x1254c367
    143 
    144 /* EBML Types */
    145 enum ebml_type_enum {
    146  TYPE_UNKNOWN,
    147  TYPE_MASTER,
    148  TYPE_UINT,
    149  TYPE_FLOAT,
    150  TYPE_STRING,
    151  TYPE_BINARY
    152 };
    153 
    154 #define LIMIT_STRING                (1 << 20)
    155 #define LIMIT_BINARY                (1 << 24)
    156 #define LIMIT_BLOCK                 (1 << 30)
    157 #define LIMIT_FRAME                 (1 << 28)
    158 
    159 /* Field Flags */
    160 #define DESC_FLAG_NONE              0
    161 #define DESC_FLAG_MULTI             (1 << 0)
    162 #define DESC_FLAG_SUSPEND           (1 << 1)
    163 #define DESC_FLAG_OFFSET            (1 << 2)
    164 
    165 /* Block Header Flags */
    166 #define SIMPLE_BLOCK_FLAGS_KEYFRAME (1 << 7)
    167 #define BLOCK_FLAGS_LACING          6
    168 
    169 /* Lacing Constants */
    170 #define LACING_NONE                 0
    171 #define LACING_XIPH                 1
    172 #define LACING_FIXED                2
    173 #define LACING_EBML                 3
    174 
    175 /* Track Types */
    176 #define TRACK_TYPE_VIDEO            1
    177 #define TRACK_TYPE_AUDIO            2
    178 
    179 /* Track IDs */
    180 #define TRACK_ID_VP8                "V_VP8"
    181 #define TRACK_ID_VP9                "V_VP9"
    182 #define TRACK_ID_AV1                "V_AV1"
    183 #define TRACK_ID_VORBIS             "A_VORBIS"
    184 #define TRACK_ID_OPUS               "A_OPUS"
    185 #define TRACK_ID_AVC                "V_MPEG4/ISO/AVC"
    186 #define TRACK_ID_HEVC               "V_MPEGH/ISO/HEVC"
    187 #define TRACK_ID_AAC                "A_AAC"
    188 #define TRACK_ID_AAC_MP4_LC         "A_AAC/MPEG4/LC"
    189 #define TRACK_ID_AAC_MP4_LC_SBR     "A_AAC/MPEG4/LC/SBR"
    190 #define TRACK_ID_AAC_MP4_LTP        "A_AAC/MPEG4/LTP"
    191 #define TRACK_ID_AAC_MP4_MAIN       "A_AAC/MPEG4/MAIN"
    192 #define TRACK_ID_AAC_MP4_SSR        "A_AAC/MPEG4/SSR"
    193 #define TRACK_ID_FLAC               "A_FLAC"
    194 #define TRACK_ID_MP3                "A_MPEG/L3"
    195 #define TRACK_ID_PCM_FLOAT          "A_PCM/FLOAT/IEEE"
    196 #define TRACK_ID_PCM_INT_BE         "A_PCM/INT/BIG"
    197 #define TRACK_ID_PCM_INT_LE         "A_PCM/INT/LIT"
    198 
    199 /* Track Encryption */
    200 #define CONTENT_ENC_ALGO_AES        5
    201 #define AES_SETTINGS_CIPHER_CTR     1
    202 
    203 /* Packet Encryption */
    204 #define SIGNAL_BYTE_SIZE            1
    205 #define IV_SIZE                     8
    206 #define NUM_PACKETS_SIZE            1
    207 #define PACKET_OFFSET_SIZE          4
    208 
    209 /* Signal Byte */
    210 #define PACKET_ENCRYPTED            1
    211 #define ENCRYPTED_BIT_MASK          (1 << 0)
    212 
    213 #define PACKET_PARTITIONED          2
    214 #define PARTITIONED_BIT_MASK        (1 << 1)
    215 
    216 enum vint_mask {
    217  MASK_NONE,
    218  MASK_FIRST_BIT
    219 };
    220 
    221 struct ebml_binary {
    222  unsigned char * data;
    223  size_t length;
    224 };
    225 
    226 struct ebml_list_node {
    227  struct ebml_list_node * next;
    228  uint64_t id;
    229  void * data;
    230 };
    231 
    232 struct ebml_list {
    233  struct ebml_list_node * head;
    234  struct ebml_list_node * tail;
    235 };
    236 
    237 struct ebml_type {
    238  union ebml_value {
    239    uint64_t u;
    240    double f;
    241    int64_t i;
    242    char * s;
    243    struct ebml_binary b;
    244  } v;
    245  enum ebml_type_enum type;
    246  int read;
    247 };
    248 
    249 /* EBML Definitions */
    250 struct ebml {
    251  struct ebml_type ebml_version;
    252  struct ebml_type ebml_read_version;
    253  struct ebml_type ebml_max_id_length;
    254  struct ebml_type ebml_max_size_length;
    255  struct ebml_type doctype;
    256  struct ebml_type doctype_version;
    257  struct ebml_type doctype_read_version;
    258 };
    259 
    260 #define DOCTYPE_WEBM "webm"
    261 #define DOCTYPE_MKV  "matroska"
    262 
    263 /* Matroksa Definitions */
    264 struct seek {
    265  struct ebml_type id;
    266  struct ebml_type position;
    267 };
    268 
    269 struct seek_head {
    270  struct ebml_list seek;
    271 };
    272 
    273 struct info {
    274  struct ebml_type timecode_scale;
    275  struct ebml_type duration;
    276 };
    277 
    278 struct mastering_metadata {
    279  struct ebml_type primary_r_chromacity_x;
    280  struct ebml_type primary_r_chromacity_y;
    281  struct ebml_type primary_g_chromacity_x;
    282  struct ebml_type primary_g_chromacity_y;
    283  struct ebml_type primary_b_chromacity_x;
    284  struct ebml_type primary_b_chromacity_y;
    285  struct ebml_type white_point_chromaticity_x;
    286  struct ebml_type white_point_chromaticity_y;
    287  struct ebml_type luminance_max;
    288  struct ebml_type luminance_min;
    289 };
    290 
    291 struct colour {
    292  struct ebml_type matrix_coefficients;
    293  struct ebml_type range;
    294  struct ebml_type transfer_characteristics;
    295  struct ebml_type primaries;
    296  struct mastering_metadata mastering_metadata;
    297 };
    298 
    299 struct video {
    300  struct ebml_type stereo_mode;
    301  struct ebml_type alpha_mode;
    302  struct ebml_type pixel_width;
    303  struct ebml_type pixel_height;
    304  struct ebml_type pixel_crop_bottom;
    305  struct ebml_type pixel_crop_top;
    306  struct ebml_type pixel_crop_left;
    307  struct ebml_type pixel_crop_right;
    308  struct ebml_type display_width;
    309  struct ebml_type display_height;
    310  struct colour colour;
    311 };
    312 
    313 struct audio {
    314  struct ebml_type sampling_frequency;
    315  struct ebml_type channels;
    316  struct ebml_type bit_depth;
    317 };
    318 
    319 struct content_enc_aes_settings {
    320  struct ebml_type aes_settings_cipher_mode;
    321 };
    322 
    323 struct content_encryption {
    324  struct ebml_type content_enc_algo;
    325  struct ebml_type content_enc_key_id;
    326  struct ebml_list content_enc_aes_settings;
    327 };
    328 
    329 struct content_encoding {
    330  struct ebml_type content_encoding_type;
    331  struct ebml_list content_encryption;
    332 };
    333 
    334 struct content_encodings {
    335  struct ebml_list content_encoding;
    336 };
    337 
    338 struct track_entry {
    339  struct ebml_type number;
    340  struct ebml_type uid;
    341  struct ebml_type type;
    342  struct ebml_type flag_enabled;
    343  struct ebml_type flag_default;
    344  struct ebml_type flag_lacing;
    345  struct ebml_type track_timecode_scale;
    346  struct ebml_type language;
    347  struct ebml_type codec_id;
    348  struct ebml_type codec_private;
    349  struct ebml_type codec_delay;
    350  struct ebml_type seek_preroll;
    351  struct ebml_type default_duration;
    352  struct video video;
    353  struct audio audio;
    354  struct content_encodings content_encodings;
    355 };
    356 
    357 struct tracks {
    358  struct ebml_list track_entry;
    359 };
    360 
    361 struct cue_track_positions {
    362  struct ebml_type track;
    363  struct ebml_type cluster_position;
    364  struct ebml_type block_number;
    365 };
    366 
    367 struct cue_point {
    368  struct ebml_type time;
    369  struct ebml_list cue_track_positions;
    370 };
    371 
    372 struct cues {
    373  struct ebml_list cue_point;
    374 };
    375 
    376 struct segment {
    377  struct ebml_list seek_head;
    378  struct info info;
    379  struct tracks tracks;
    380  struct cues cues;
    381 };
    382 
    383 /* Misc. */
    384 struct pool_node {
    385  struct pool_node * next;
    386  void * data;
    387 };
    388 
    389 struct pool_ctx {
    390  struct pool_node * head;
    391 };
    392 
    393 struct list_node {
    394  struct list_node * previous;
    395  struct ebml_element_desc * node;
    396  unsigned char * data;
    397 };
    398 
    399 struct saved_state {
    400  int64_t stream_offset;
    401  uint64_t last_id;
    402  uint64_t last_size;
    403  int last_valid;
    404 };
    405 
    406 struct frame_encryption {
    407  unsigned char * iv;
    408  size_t length;
    409  uint8_t signal_byte;
    410  uint8_t num_partitions;
    411  uint32_t * partition_offsets;
    412 };
    413 
    414 struct frame {
    415  unsigned char * data;
    416  size_t length;
    417  struct frame_encryption * frame_encryption;
    418  struct frame * next;
    419 };
    420 
    421 struct block_additional {
    422  unsigned int id;
    423  unsigned char * data;
    424  size_t length;
    425  struct block_additional * next;
    426 };
    427 
    428 /* Public (opaque) Structures */
    429 struct nestegg {
    430  nestegg_io * io;
    431  nestegg_log log;
    432  struct pool_ctx * alloc_pool;
    433  uint64_t last_id;
    434  uint64_t last_size;
    435  int last_valid;
    436  struct list_node * ancestor;
    437  struct ebml ebml;
    438  struct segment segment;
    439  int64_t segment_offset;
    440  unsigned int track_count;
    441  /* Last read cluster. */
    442  uint64_t cluster_timecode;
    443  int read_cluster_timecode;
    444  struct saved_state saved;
    445 };
    446 
    447 struct nestegg_packet {
    448  uint64_t track;
    449  uint64_t timecode;
    450  uint64_t duration;
    451  int read_duration;
    452  struct frame * frame;
    453  struct block_additional * block_additional;
    454  int64_t discard_padding;
    455  int read_discard_padding;
    456  int64_t reference_block;
    457  int read_reference_block;
    458  uint8_t keyframe;
    459 };
    460 
    461 /* Element Descriptor */
    462 struct ebml_element_desc {
    463  char const * name;
    464  uint64_t id;
    465  enum ebml_type_enum type;
    466  size_t offset;
    467  unsigned int flags;
    468  struct ebml_element_desc * children;
    469  size_t size;
    470  size_t data_offset;
    471 };
    472 
    473 #define E_FIELD(ID, TYPE, STRUCT, FIELD) \
    474  { #ID, ID, TYPE, offsetof(STRUCT, FIELD), DESC_FLAG_NONE, NULL, 0, 0 }
    475 #define E_MASTER(ID, TYPE, STRUCT, FIELD) \
    476  { #ID, ID, TYPE, offsetof(STRUCT, FIELD), DESC_FLAG_MULTI, ne_ ## FIELD ## _elements, \
    477      sizeof(struct FIELD), 0 }
    478 #define E_SINGLE_MASTER_O(ID, TYPE, STRUCT, FIELD) \
    479  { #ID, ID, TYPE, offsetof(STRUCT, FIELD), DESC_FLAG_OFFSET, ne_ ## FIELD ## _elements, 0, \
    480      offsetof(STRUCT, FIELD ## _offset) }
    481 #define E_SINGLE_MASTER(ID, TYPE, STRUCT, FIELD) \
    482  { #ID, ID, TYPE, offsetof(STRUCT, FIELD), DESC_FLAG_NONE, ne_ ## FIELD ## _elements, 0, 0 }
    483 #define E_SUSPEND(ID, TYPE) \
    484  { #ID, ID, TYPE, 0, DESC_FLAG_SUSPEND, NULL, 0, 0 }
    485 #define E_LAST \
    486  { NULL, 0, 0, 0, DESC_FLAG_NONE, NULL, 0, 0 }
    487 
    488 /* EBML Element Lists */
    489 static struct ebml_element_desc ne_ebml_elements[] = {
    490  E_FIELD(ID_EBML_VERSION, TYPE_UINT, struct ebml, ebml_version),
    491  E_FIELD(ID_EBML_READ_VERSION, TYPE_UINT, struct ebml, ebml_read_version),
    492  E_FIELD(ID_EBML_MAX_ID_LENGTH, TYPE_UINT, struct ebml, ebml_max_id_length),
    493  E_FIELD(ID_EBML_MAX_SIZE_LENGTH, TYPE_UINT, struct ebml, ebml_max_size_length),
    494  E_FIELD(ID_DOCTYPE, TYPE_STRING, struct ebml, doctype),
    495  E_FIELD(ID_DOCTYPE_VERSION, TYPE_UINT, struct ebml, doctype_version),
    496  E_FIELD(ID_DOCTYPE_READ_VERSION, TYPE_UINT, struct ebml, doctype_read_version),
    497  E_LAST
    498 };
    499 
    500 /* WebM Element Lists */
    501 static struct ebml_element_desc ne_seek_elements[] = {
    502  E_FIELD(ID_SEEK_ID, TYPE_BINARY, struct seek, id),
    503  E_FIELD(ID_SEEK_POSITION, TYPE_UINT, struct seek, position),
    504  E_LAST
    505 };
    506 
    507 static struct ebml_element_desc ne_seek_head_elements[] = {
    508  E_MASTER(ID_SEEK, TYPE_MASTER, struct seek_head, seek),
    509  E_LAST
    510 };
    511 
    512 static struct ebml_element_desc ne_info_elements[] = {
    513  E_FIELD(ID_TIMECODE_SCALE, TYPE_UINT, struct info, timecode_scale),
    514  E_FIELD(ID_DURATION, TYPE_FLOAT, struct info, duration),
    515  E_LAST
    516 };
    517 
    518 static struct ebml_element_desc ne_mastering_metadata_elements[] = {
    519  E_FIELD(ID_PRIMARY_R_CHROMATICITY_X, TYPE_FLOAT, struct mastering_metadata, primary_r_chromacity_x),
    520  E_FIELD(ID_PRIMARY_R_CHROMATICITY_Y, TYPE_FLOAT, struct mastering_metadata, primary_r_chromacity_y),
    521  E_FIELD(ID_PRIMARY_G_CHROMATICITY_X, TYPE_FLOAT, struct mastering_metadata, primary_g_chromacity_x),
    522  E_FIELD(ID_PRIMARY_G_CHROMATICITY_Y, TYPE_FLOAT, struct mastering_metadata, primary_g_chromacity_y),
    523  E_FIELD(ID_PRIMARY_B_CHROMATICITY_X, TYPE_FLOAT, struct mastering_metadata, primary_b_chromacity_x),
    524  E_FIELD(ID_PRIMARY_B_CHROMATICITY_Y, TYPE_FLOAT, struct mastering_metadata, primary_b_chromacity_y),
    525  E_FIELD(ID_WHITE_POINT_CHROMATICITY_X, TYPE_FLOAT, struct mastering_metadata, white_point_chromaticity_x),
    526  E_FIELD(ID_WHITE_POINT_CHROMATICITY_Y, TYPE_FLOAT, struct mastering_metadata, white_point_chromaticity_y),
    527  E_FIELD(ID_LUMINANCE_MAX, TYPE_FLOAT, struct mastering_metadata, luminance_max),
    528  E_FIELD(ID_LUMINANCE_MIN, TYPE_FLOAT, struct mastering_metadata, luminance_min),
    529  E_LAST
    530 };
    531 
    532 static struct ebml_element_desc ne_colour_elements[] = {
    533  E_FIELD(ID_MATRIX_COEFFICIENTS, TYPE_UINT, struct colour, matrix_coefficients),
    534  E_FIELD(ID_RANGE, TYPE_UINT, struct colour, range),
    535  E_FIELD(ID_TRANSFER_CHARACTERISTICS, TYPE_UINT, struct colour, transfer_characteristics),
    536  E_FIELD(ID_PRIMARIES, TYPE_UINT, struct colour, primaries),
    537  E_SINGLE_MASTER(ID_MASTERING_METADATA, TYPE_MASTER, struct colour, mastering_metadata),
    538  E_LAST
    539 };
    540 
    541 static struct ebml_element_desc ne_video_elements[] = {
    542  E_FIELD(ID_STEREO_MODE, TYPE_UINT, struct video, stereo_mode),
    543  E_FIELD(ID_ALPHA_MODE, TYPE_UINT, struct video, alpha_mode),
    544  E_FIELD(ID_PIXEL_WIDTH, TYPE_UINT, struct video, pixel_width),
    545  E_FIELD(ID_PIXEL_HEIGHT, TYPE_UINT, struct video, pixel_height),
    546  E_FIELD(ID_PIXEL_CROP_BOTTOM, TYPE_UINT, struct video, pixel_crop_bottom),
    547  E_FIELD(ID_PIXEL_CROP_TOP, TYPE_UINT, struct video, pixel_crop_top),
    548  E_FIELD(ID_PIXEL_CROP_LEFT, TYPE_UINT, struct video, pixel_crop_left),
    549  E_FIELD(ID_PIXEL_CROP_RIGHT, TYPE_UINT, struct video, pixel_crop_right),
    550  E_FIELD(ID_DISPLAY_WIDTH, TYPE_UINT, struct video, display_width),
    551  E_FIELD(ID_DISPLAY_HEIGHT, TYPE_UINT, struct video, display_height),
    552  E_SINGLE_MASTER(ID_COLOUR, TYPE_MASTER, struct video, colour),
    553  E_LAST
    554 };
    555 
    556 static struct ebml_element_desc ne_audio_elements[] = {
    557  E_FIELD(ID_SAMPLING_FREQUENCY, TYPE_FLOAT, struct audio, sampling_frequency),
    558  E_FIELD(ID_CHANNELS, TYPE_UINT, struct audio, channels),
    559  E_FIELD(ID_BIT_DEPTH, TYPE_UINT, struct audio, bit_depth),
    560  E_LAST
    561 };
    562 
    563 static struct ebml_element_desc ne_content_enc_aes_settings_elements[] = {
    564  E_FIELD(ID_AES_SETTINGS_CIPHER_MODE, TYPE_UINT, struct content_enc_aes_settings, aes_settings_cipher_mode),
    565  E_LAST
    566 };
    567 
    568 static struct ebml_element_desc ne_content_encryption_elements[] = {
    569  E_FIELD(ID_CONTENT_ENC_ALGO, TYPE_UINT, struct content_encryption, content_enc_algo),
    570  E_FIELD(ID_CONTENT_ENC_KEY_ID, TYPE_BINARY, struct content_encryption, content_enc_key_id),
    571  E_MASTER(ID_CONTENT_ENC_AES_SETTINGS, TYPE_MASTER, struct content_encryption, content_enc_aes_settings),
    572  E_LAST
    573 };
    574 
    575 static struct ebml_element_desc ne_content_encoding_elements[] = {
    576  E_FIELD(ID_CONTENT_ENCODING_TYPE, TYPE_UINT, struct content_encoding, content_encoding_type),
    577  E_MASTER(ID_CONTENT_ENCRYPTION, TYPE_MASTER, struct content_encoding, content_encryption),
    578  E_LAST
    579 };
    580 
    581 static struct ebml_element_desc ne_content_encodings_elements[] = {
    582  E_MASTER(ID_CONTENT_ENCODING, TYPE_MASTER, struct content_encodings, content_encoding),
    583  E_LAST
    584 };
    585 
    586 static struct ebml_element_desc ne_track_entry_elements[] = {
    587  E_FIELD(ID_TRACK_NUMBER, TYPE_UINT, struct track_entry, number),
    588  E_FIELD(ID_TRACK_UID, TYPE_UINT, struct track_entry, uid),
    589  E_FIELD(ID_TRACK_TYPE, TYPE_UINT, struct track_entry, type),
    590  E_FIELD(ID_FLAG_ENABLED, TYPE_UINT, struct track_entry, flag_enabled),
    591  E_FIELD(ID_FLAG_DEFAULT, TYPE_UINT, struct track_entry, flag_default),
    592  E_FIELD(ID_FLAG_LACING, TYPE_UINT, struct track_entry, flag_lacing),
    593  E_FIELD(ID_TRACK_TIMECODE_SCALE, TYPE_FLOAT, struct track_entry, track_timecode_scale),
    594  E_FIELD(ID_LANGUAGE, TYPE_STRING, struct track_entry, language),
    595  E_FIELD(ID_CODEC_ID, TYPE_STRING, struct track_entry, codec_id),
    596  E_FIELD(ID_CODEC_PRIVATE, TYPE_BINARY, struct track_entry, codec_private),
    597  E_FIELD(ID_CODEC_DELAY, TYPE_UINT, struct track_entry, codec_delay),
    598  E_FIELD(ID_SEEK_PREROLL, TYPE_UINT, struct track_entry, seek_preroll),
    599  E_FIELD(ID_DEFAULT_DURATION, TYPE_UINT, struct track_entry, default_duration),
    600  E_SINGLE_MASTER(ID_VIDEO, TYPE_MASTER, struct track_entry, video),
    601  E_SINGLE_MASTER(ID_AUDIO, TYPE_MASTER, struct track_entry, audio),
    602  E_SINGLE_MASTER(ID_CONTENT_ENCODINGS, TYPE_MASTER, struct track_entry, content_encodings),
    603  E_LAST
    604 };
    605 
    606 static struct ebml_element_desc ne_tracks_elements[] = {
    607  E_MASTER(ID_TRACK_ENTRY, TYPE_MASTER, struct tracks, track_entry),
    608  E_LAST
    609 };
    610 
    611 static struct ebml_element_desc ne_cue_track_positions_elements[] = {
    612  E_FIELD(ID_CUE_TRACK, TYPE_UINT, struct cue_track_positions, track),
    613  E_FIELD(ID_CUE_CLUSTER_POSITION, TYPE_UINT, struct cue_track_positions, cluster_position),
    614  E_FIELD(ID_CUE_BLOCK_NUMBER, TYPE_UINT, struct cue_track_positions, block_number),
    615  E_LAST
    616 };
    617 
    618 static struct ebml_element_desc ne_cue_point_elements[] = {
    619  E_FIELD(ID_CUE_TIME, TYPE_UINT, struct cue_point, time),
    620  E_MASTER(ID_CUE_TRACK_POSITIONS, TYPE_MASTER, struct cue_point, cue_track_positions),
    621  E_LAST
    622 };
    623 
    624 static struct ebml_element_desc ne_cues_elements[] = {
    625  E_MASTER(ID_CUE_POINT, TYPE_MASTER, struct cues, cue_point),
    626  E_LAST
    627 };
    628 
    629 static struct ebml_element_desc ne_segment_elements[] = {
    630  E_MASTER(ID_SEEK_HEAD, TYPE_MASTER, struct segment, seek_head),
    631  E_SINGLE_MASTER(ID_INFO, TYPE_MASTER, struct segment, info),
    632  E_SUSPEND(ID_CLUSTER, TYPE_MASTER),
    633  E_SINGLE_MASTER(ID_TRACKS, TYPE_MASTER, struct segment, tracks),
    634  E_SINGLE_MASTER(ID_CUES, TYPE_MASTER, struct segment, cues),
    635  E_LAST
    636 };
    637 
    638 static struct ebml_element_desc ne_top_level_elements[] = {
    639  E_SINGLE_MASTER(ID_EBML, TYPE_MASTER, nestegg, ebml),
    640  E_SINGLE_MASTER_O(ID_SEGMENT, TYPE_MASTER, nestegg, segment),
    641  E_LAST
    642 };
    643 
    644 #undef E_FIELD
    645 #undef E_MASTER
    646 #undef E_SINGLE_MASTER_O
    647 #undef E_SINGLE_MASTER
    648 #undef E_SUSPEND
    649 #undef E_LAST
    650 
    651 static struct pool_ctx *
    652 ne_pool_init(void)
    653 {
    654  return calloc(1, sizeof(struct pool_ctx));
    655 }
    656 
    657 static void
    658 ne_pool_destroy(struct pool_ctx * pool)
    659 {
    660  struct pool_node * node = pool->head;
    661  while (node) {
    662    struct pool_node * old = node;
    663    node = node->next;
    664    free(old->data);
    665    free(old);
    666  }
    667  free(pool);
    668 }
    669 
    670 static void *
    671 ne_pool_alloc(size_t size, struct pool_ctx * pool)
    672 {
    673  struct pool_node * node;
    674 
    675  node = calloc(1, sizeof(*node));
    676  if (!node)
    677    return NULL;
    678 
    679  node->data = calloc(1, size);
    680  if (!node->data) {
    681    free(node);
    682    return NULL;
    683  }
    684 
    685  node->next = pool->head;
    686  pool->head = node;
    687 
    688  return node->data;
    689 }
    690 
    691 static void *
    692 ne_alloc(size_t size)
    693 {
    694  return calloc(1, size);
    695 }
    696 
    697 static int
    698 ne_io_read(nestegg_io * io, void * buffer, size_t length)
    699 {
    700  return io->read(buffer, length, io->userdata);
    701 }
    702 
    703 static int
    704 ne_io_seek(nestegg_io * io, int64_t offset, int whence)
    705 {
    706  return io->seek(offset, whence, io->userdata);
    707 }
    708 
    709 static int
    710 ne_io_read_skip(nestegg_io * io, size_t length)
    711 {
    712  size_t get;
    713  unsigned char buf[8192];
    714  int r = 1;
    715 
    716  while (length > 0) {
    717    get = length < sizeof(buf) ? length : sizeof(buf);
    718    r = ne_io_read(io, buf, get);
    719    if (r != 1)
    720      break;
    721    length -= get;
    722  }
    723 
    724  return r;
    725 }
    726 
    727 static int64_t
    728 ne_io_tell(nestegg_io * io)
    729 {
    730  return io->tell(io->userdata);
    731 }
    732 
    733 static int
    734 ne_bare_read_vint(nestegg_io * io, uint64_t * value, uint64_t * length, enum vint_mask maskflag)
    735 {
    736  int r;
    737  unsigned char b;
    738  size_t maxlen = 8;
    739  unsigned int count = 1, mask = 1 << 7;
    740 
    741  r = ne_io_read(io, &b, 1);
    742  if (r != 1)
    743    return r;
    744 
    745  while (count < maxlen) {
    746    if ((b & mask) != 0)
    747      break;
    748    mask >>= 1;
    749    count += 1;
    750  }
    751 
    752  if (length)
    753    *length = count;
    754  *value = b;
    755 
    756  if (maskflag == MASK_FIRST_BIT)
    757    *value = b & ~mask;
    758 
    759  while (--count) {
    760    r = ne_io_read(io, &b, 1);
    761    if (r != 1)
    762      return r;
    763    *value <<= 8;
    764    *value |= b;
    765  }
    766 
    767  return 1;
    768 }
    769 
    770 static int
    771 ne_read_id(nestegg_io * io, uint64_t * value, uint64_t * length)
    772 {
    773  return ne_bare_read_vint(io, value, length, MASK_NONE);
    774 }
    775 
    776 static int
    777 ne_read_vint(nestegg_io * io, uint64_t * value, uint64_t * length)
    778 {
    779  return ne_bare_read_vint(io, value, length, MASK_FIRST_BIT);
    780 }
    781 
    782 static int
    783 ne_read_svint(nestegg_io * io, int64_t * value, uint64_t * length)
    784 {
    785  int r;
    786  uint64_t uvalue;
    787  uint64_t ulength;
    788  int64_t svint_subtr[] = {
    789    0x3f, 0x1fff,
    790    0xfffff, 0x7ffffff,
    791    0x3ffffffffLL, 0x1ffffffffffLL,
    792    0xffffffffffffLL, 0x7fffffffffffffLL
    793  };
    794 
    795  r = ne_bare_read_vint(io, &uvalue, &ulength, MASK_FIRST_BIT);
    796  if (r != 1)
    797    return r;
    798  *value = uvalue - svint_subtr[ulength - 1];
    799  if (length)
    800    *length = ulength;
    801  return r;
    802 }
    803 
    804 static int
    805 ne_read_uint(nestegg_io * io, uint64_t * val, uint64_t length)
    806 {
    807  unsigned char b;
    808  int r;
    809 
    810  if (length == 0 || length > 8)
    811    return -1;
    812  r = ne_io_read(io, &b, 1);
    813  if (r != 1)
    814    return r;
    815  *val = b;
    816  while (--length) {
    817    r = ne_io_read(io, &b, 1);
    818    if (r != 1)
    819      return r;
    820    *val <<= 8;
    821    *val |= b;
    822  }
    823  return 1;
    824 }
    825 
    826 static int
    827 ne_read_int(nestegg_io * io, int64_t * val, uint64_t length)
    828 {
    829  int r;
    830  uint64_t uval, base;
    831 
    832  r = ne_read_uint(io, &uval, length);
    833  if (r != 1)
    834    return r;
    835 
    836  if (length < sizeof(int64_t)) {
    837    base = 1;
    838    base <<= length * 8 - 1;
    839    if (uval >= base) {
    840      base = 1;
    841      base <<= length * 8;
    842    } else {
    843      base = 0;
    844    }
    845    *val = uval - base;
    846  } else {
    847    *val = (int64_t) uval;
    848  }
    849 
    850  return 1;
    851 }
    852 
    853 static int
    854 ne_read_float(nestegg_io * io, double * val, uint64_t length)
    855 {
    856  union {
    857    uint64_t u;
    858    struct {
    859 #if defined(__FLOAT_WORD_ORDER__) && __FLOAT_WORD_ORDER__ == __ORDER_BIG_ENDIAN__
    860      uint32_t _pad;
    861      float f;
    862 #else
    863      float f;
    864      uint32_t _pad;
    865 #endif
    866    } f;
    867    double d;
    868  } value;
    869  int r;
    870 
    871  /* Length == 10 not implemented. */
    872  if (length != 4 && length != 8)
    873    return -1;
    874  r = ne_read_uint(io, &value.u, length);
    875  if (r != 1)
    876    return r;
    877  if (length == 4)
    878    *val = value.f.f;
    879  else
    880    *val = value.d;
    881  return 1;
    882 }
    883 
    884 static int
    885 ne_read_string(nestegg * ctx, char ** val, uint64_t length)
    886 {
    887  char * str;
    888  int r;
    889 
    890  if (length > LIMIT_STRING)
    891    return -1;
    892  str = ne_pool_alloc(length + 1, ctx->alloc_pool);
    893  if (!str)
    894    return -1;
    895  if (length) {
    896    r = ne_io_read(ctx->io, (unsigned char *) str, length);
    897    if (r != 1)
    898      return r;
    899  }
    900  str[length] = '\0';
    901  *val = str;
    902  return 1;
    903 }
    904 
    905 static int
    906 ne_read_binary(nestegg * ctx, struct ebml_binary * val, uint64_t length)
    907 {
    908  if (length == 0 || length > LIMIT_BINARY)
    909    return -1;
    910  val->data = ne_pool_alloc(length, ctx->alloc_pool);
    911  if (!val->data)
    912    return -1;
    913  val->length = length;
    914  return ne_io_read(ctx->io, val->data, length);
    915 }
    916 
    917 static int
    918 ne_get_uint(struct ebml_type type, uint64_t * value)
    919 {
    920  if (!type.read)
    921    return -1;
    922 
    923  assert(type.type == TYPE_UINT);
    924 
    925  *value = type.v.u;
    926 
    927  return 0;
    928 }
    929 
    930 static int
    931 ne_get_float(struct ebml_type type, double * value)
    932 {
    933  if (!type.read)
    934    return -1;
    935 
    936  assert(type.type == TYPE_FLOAT);
    937 
    938  *value = type.v.f;
    939 
    940  return 0;
    941 }
    942 
    943 static int
    944 ne_get_string(struct ebml_type type, char ** value)
    945 {
    946  if (!type.read)
    947    return -1;
    948 
    949  assert(type.type == TYPE_STRING);
    950 
    951  *value = type.v.s;
    952 
    953  return 0;
    954 }
    955 
    956 static int
    957 ne_get_binary(struct ebml_type type, struct ebml_binary * value)
    958 {
    959  if (!type.read)
    960    return -1;
    961 
    962  assert(type.type == TYPE_BINARY);
    963 
    964  *value = type.v.b;
    965 
    966  return 0;
    967 }
    968 
    969 static int
    970 ne_is_ancestor_element(uint64_t id, struct list_node * ancestor)
    971 {
    972  struct ebml_element_desc * element;
    973 
    974  for (; ancestor; ancestor = ancestor->previous)
    975    for (element = ancestor->node; element->id; ++element)
    976      if (element->id == id)
    977        return 1;
    978 
    979  return 0;
    980 }
    981 
    982 static struct ebml_element_desc *
    983 ne_find_element(uint64_t id, struct ebml_element_desc * elements)
    984 {
    985  struct ebml_element_desc * element;
    986 
    987  for (element = elements; element->id; ++element)
    988    if (element->id == id)
    989      return element;
    990 
    991  return NULL;
    992 }
    993 
    994 static int
    995 ne_ctx_push(nestegg * ctx, struct ebml_element_desc * ancestor, void * data)
    996 {
    997  struct list_node * item;
    998 
    999  item = ne_alloc(sizeof(*item));
   1000  if (!item)
   1001    return -1;
   1002  item->previous = ctx->ancestor;
   1003  item->node = ancestor;
   1004  item->data = data;
   1005  ctx->ancestor = item;
   1006  return 0;
   1007 }
   1008 
   1009 static void
   1010 ne_ctx_pop(nestegg * ctx)
   1011 {
   1012  struct list_node * item;
   1013 
   1014  item = ctx->ancestor;
   1015  ctx->ancestor = item->previous;
   1016  free(item);
   1017 }
   1018 
   1019 static int
   1020 ne_ctx_save(nestegg * ctx, struct saved_state * s)
   1021 {
   1022  s->stream_offset = ne_io_tell(ctx->io);
   1023  if (s->stream_offset < 0)
   1024    return -1;
   1025  s->last_id = ctx->last_id;
   1026  s->last_size = ctx->last_size;
   1027  s->last_valid = ctx->last_valid;
   1028  return 0;
   1029 }
   1030 
   1031 static int
   1032 ne_ctx_restore(nestegg * ctx, struct saved_state * s)
   1033 {
   1034  int r;
   1035 
   1036  if (s->stream_offset < 0)
   1037    return -1;
   1038  r = ne_io_seek(ctx->io, s->stream_offset, NESTEGG_SEEK_SET);
   1039  if (r != 0)
   1040    return -1;
   1041  ctx->last_id = s->last_id;
   1042  ctx->last_size = s->last_size;
   1043  ctx->last_valid = s->last_valid;
   1044  return 0;
   1045 }
   1046 
   1047 static int
   1048 ne_peek_element(nestegg * ctx, uint64_t * id, uint64_t * size)
   1049 {
   1050  int r;
   1051 
   1052  if (ctx->last_valid) {
   1053    if (id)
   1054      *id = ctx->last_id;
   1055    if (size)
   1056      *size = ctx->last_size;
   1057    return 1;
   1058  }
   1059 
   1060  r = ne_read_id(ctx->io, &ctx->last_id, NULL);
   1061  if (r != 1)
   1062    return r;
   1063 
   1064  r = ne_read_vint(ctx->io, &ctx->last_size, NULL);
   1065  if (r != 1)
   1066    return r;
   1067 
   1068  if (id)
   1069    *id = ctx->last_id;
   1070  if (size)
   1071    *size = ctx->last_size;
   1072 
   1073  ctx->last_valid = 1;
   1074 
   1075  return 1;
   1076 }
   1077 
   1078 static int
   1079 ne_read_element(nestegg * ctx, uint64_t * id, uint64_t * size)
   1080 {
   1081  int r;
   1082 
   1083  r = ne_peek_element(ctx, id, size);
   1084  if (r != 1)
   1085    return r;
   1086 
   1087  ctx->last_valid = 0;
   1088 
   1089  return 1;
   1090 }
   1091 
   1092 static int
   1093 ne_read_master(nestegg * ctx, struct ebml_element_desc * desc)
   1094 {
   1095  struct ebml_list * list;
   1096  struct ebml_list_node * node, * oldtail;
   1097 
   1098  assert(desc->type == TYPE_MASTER && desc->flags & DESC_FLAG_MULTI);
   1099 
   1100  ctx->log(ctx, NESTEGG_LOG_DEBUG, "multi master element %llx (%s)",
   1101           desc->id, desc->name);
   1102 
   1103  list = (struct ebml_list *) (ctx->ancestor->data + desc->offset);
   1104 
   1105  node = ne_pool_alloc(sizeof(*node), ctx->alloc_pool);
   1106  if (!node)
   1107    return -1;
   1108  node->id = desc->id;
   1109  node->data = ne_pool_alloc(desc->size, ctx->alloc_pool);
   1110  if (!node->data)
   1111    return -1;
   1112 
   1113  oldtail = list->tail;
   1114  if (oldtail)
   1115    oldtail->next = node;
   1116  list->tail = node;
   1117  if (!list->head)
   1118    list->head = node;
   1119 
   1120  ctx->log(ctx, NESTEGG_LOG_DEBUG, " -> using data %p", node->data);
   1121 
   1122  if (ne_ctx_push(ctx, desc->children, node->data) < 0)
   1123    return -1;
   1124 
   1125  return 0;
   1126 }
   1127 
   1128 static int
   1129 ne_read_single_master(nestegg * ctx, struct ebml_element_desc * desc)
   1130 {
   1131  assert(desc->type == TYPE_MASTER && !(desc->flags & DESC_FLAG_MULTI));
   1132 
   1133  ctx->log(ctx, NESTEGG_LOG_DEBUG, "single master element %llx (%s)",
   1134           desc->id, desc->name);
   1135  ctx->log(ctx, NESTEGG_LOG_DEBUG, " -> using data %p (%u)",
   1136           ctx->ancestor->data + desc->offset, desc->offset);
   1137 
   1138  return ne_ctx_push(ctx, desc->children, ctx->ancestor->data + desc->offset);
   1139 }
   1140 
   1141 static int
   1142 ne_read_simple(nestegg * ctx, struct ebml_element_desc * desc, size_t length)
   1143 {
   1144  struct ebml_type * storage;
   1145  int r = -1;
   1146 
   1147  storage = (struct ebml_type *) (ctx->ancestor->data + desc->offset);
   1148 
   1149  if (storage->read) {
   1150    ctx->log(ctx, NESTEGG_LOG_DEBUG, "element %llx (%s) already read, skipping %u",
   1151             desc->id, desc->name, length);
   1152    return ne_io_read_skip(ctx->io, length);
   1153  }
   1154 
   1155  storage->type = desc->type;
   1156 
   1157  ctx->log(ctx, NESTEGG_LOG_DEBUG, "element %llx (%s) -> %p (%u)",
   1158           desc->id, desc->name, storage, desc->offset);
   1159 
   1160  switch (desc->type) {
   1161  case TYPE_UINT:
   1162    r = ne_read_uint(ctx->io, &storage->v.u, length);
   1163    break;
   1164  case TYPE_FLOAT:
   1165    r = ne_read_float(ctx->io, &storage->v.f, length);
   1166    break;
   1167  case TYPE_STRING:
   1168    r = ne_read_string(ctx, &storage->v.s, length);
   1169    break;
   1170  case TYPE_BINARY:
   1171    r = ne_read_binary(ctx, &storage->v.b, length);
   1172    break;
   1173  case TYPE_MASTER:
   1174  case TYPE_UNKNOWN:
   1175  default:
   1176    assert(0);
   1177    break;
   1178  }
   1179 
   1180  if (r == 1)
   1181    storage->read = 1;
   1182 
   1183  return r;
   1184 }
   1185 
   1186 static int
   1187 ne_parse(nestegg * ctx, struct ebml_element_desc * top_level, int64_t max_offset)
   1188 {
   1189  int r;
   1190  int64_t * data_offset;
   1191  uint64_t id, size, peeked_id;
   1192  struct ebml_element_desc * element;
   1193 
   1194  assert(ctx->ancestor);
   1195 
   1196  for (;;) {
   1197    if (max_offset > 0 && ne_io_tell(ctx->io) >= max_offset) {
   1198      /* Reached end of offset allowed for parsing - return gracefully */
   1199      r = 1;
   1200      break;
   1201    }
   1202    r = ne_peek_element(ctx, &id, &size);
   1203    if (r != 1)
   1204      break;
   1205    peeked_id = id;
   1206 
   1207    element = ne_find_element(id, ctx->ancestor->node);
   1208    if (element) {
   1209      if (element->flags & DESC_FLAG_SUSPEND) {
   1210        assert(element->id == ID_CLUSTER && element->type == TYPE_MASTER);
   1211        ctx->log(ctx, NESTEGG_LOG_DEBUG, "suspend parse at %llx", id);
   1212        r = 1;
   1213        break;
   1214      }
   1215 
   1216      r = ne_read_element(ctx, &id, &size);
   1217      if (r != 1)
   1218        break;
   1219      assert(id == peeked_id);
   1220 
   1221      if (element->flags & DESC_FLAG_OFFSET) {
   1222        data_offset = (int64_t *) (ctx->ancestor->data + element->data_offset);
   1223        *data_offset = ne_io_tell(ctx->io);
   1224        if (*data_offset < 0) {
   1225          r = -1;
   1226          break;
   1227        }
   1228      }
   1229 
   1230      if (element->type == TYPE_MASTER) {
   1231        if (element->flags & DESC_FLAG_MULTI) {
   1232          if (ne_read_master(ctx, element) < 0)
   1233            break;
   1234        } else {
   1235          if (ne_read_single_master(ctx, element) < 0)
   1236            break;
   1237        }
   1238        continue;
   1239      } else {
   1240        r = ne_read_simple(ctx, element, size);
   1241        if (r < 0)
   1242          break;
   1243      }
   1244    } else if (ne_is_ancestor_element(id, ctx->ancestor->previous)) {
   1245      ctx->log(ctx, NESTEGG_LOG_DEBUG, "parent element %llx", id);
   1246      if (top_level && ctx->ancestor->node == top_level) {
   1247        ctx->log(ctx, NESTEGG_LOG_DEBUG, "*** parse about to back up past top_level");
   1248        r = 1;
   1249        break;
   1250      }
   1251      ne_ctx_pop(ctx);
   1252    } else {
   1253      r = ne_read_element(ctx, &id, &size);
   1254      if (r != 1)
   1255        break;
   1256 
   1257      if (id != ID_VOID && id != ID_CRC32)
   1258        ctx->log(ctx, NESTEGG_LOG_DEBUG, "unknown element %llx", id);
   1259      r = ne_io_read_skip(ctx->io, size);
   1260      if (r != 1)
   1261        break;
   1262    }
   1263  }
   1264 
   1265  if (r != 1)
   1266    while (ctx->ancestor)
   1267      ne_ctx_pop(ctx);
   1268 
   1269  return r;
   1270 }
   1271 
   1272 static int
   1273 ne_read_block_encryption(nestegg * ctx, struct track_entry const * entry,
   1274                         uint64_t * encoding_type, uint64_t * encryption_algo,
   1275                         uint64_t * encryption_mode)
   1276 {
   1277  struct content_encoding * encoding;
   1278  struct content_encryption * encryption;
   1279  struct content_enc_aes_settings * aes_settings;
   1280 
   1281  *encoding_type = 0;
   1282  if (entry->content_encodings.content_encoding.head) {
   1283    encoding = entry->content_encodings.content_encoding.head->data;
   1284    if (ne_get_uint(encoding->content_encoding_type, encoding_type) != 0)
   1285      return -1;
   1286 
   1287    if (*encoding_type == NESTEGG_ENCODING_ENCRYPTION) {
   1288      /* Metadata states content is encrypted */
   1289      if (!encoding->content_encryption.head)
   1290        return -1;
   1291 
   1292      encryption = encoding->content_encryption.head->data;
   1293      if (ne_get_uint(encryption->content_enc_algo, encryption_algo) != 0) {
   1294        ctx->log(ctx, NESTEGG_LOG_ERROR, "No ContentEncAlgo element found");
   1295        return -1;
   1296      }
   1297 
   1298      if (*encryption_algo != CONTENT_ENC_ALGO_AES) {
   1299        ctx->log(ctx, NESTEGG_LOG_ERROR, "Disallowed ContentEncAlgo used");
   1300        return -1;
   1301      }
   1302 
   1303      if (!encryption->content_enc_aes_settings.head) {
   1304        ctx->log(ctx, NESTEGG_LOG_ERROR, "No ContentEncAESSettings element found");
   1305        return -1;
   1306      }
   1307 
   1308      aes_settings = encryption->content_enc_aes_settings.head->data;
   1309      *encryption_mode = AES_SETTINGS_CIPHER_CTR;
   1310      ne_get_uint(aes_settings->aes_settings_cipher_mode, encryption_mode);
   1311 
   1312      if (*encryption_mode != AES_SETTINGS_CIPHER_CTR) {
   1313        ctx->log(ctx, NESTEGG_LOG_ERROR, "Disallowed AESSettingsCipherMode used");
   1314        return -1;
   1315      }
   1316    }
   1317  }
   1318  return 1;
   1319 }
   1320 
   1321 static int
   1322 ne_read_xiph_lace_value(nestegg_io * io, uint64_t * value, size_t * consumed)
   1323 {
   1324  int r;
   1325  uint64_t lace;
   1326 
   1327  r = ne_read_uint(io, &lace, 1);
   1328  if (r != 1)
   1329    return r;
   1330  *consumed += 1;
   1331 
   1332  *value = lace;
   1333  while (lace == 255) {
   1334    r = ne_read_uint(io, &lace, 1);
   1335    if (r != 1)
   1336      return r;
   1337    *consumed += 1;
   1338    *value += lace;
   1339  }
   1340 
   1341  return 1;
   1342 }
   1343 
   1344 static int
   1345 ne_read_xiph_lacing(nestegg_io * io, size_t block, size_t * read, uint64_t n, uint64_t * sizes)
   1346 {
   1347  int r;
   1348  size_t i = 0;
   1349  uint64_t sum = 0;
   1350 
   1351  while (--n) {
   1352    r = ne_read_xiph_lace_value(io, &sizes[i], read);
   1353    if (r != 1)
   1354      return r;
   1355    sum += sizes[i];
   1356    i += 1;
   1357  }
   1358 
   1359  if (*read + sum > block)
   1360    return -1;
   1361 
   1362  /* Last frame is the remainder of the block. */
   1363  sizes[i] = block - *read - sum;
   1364  return 1;
   1365 }
   1366 
   1367 static int
   1368 ne_read_ebml_lacing(nestegg_io * io, size_t block, size_t * read, uint64_t n, uint64_t * sizes)
   1369 {
   1370  int r;
   1371  uint64_t lace, sum, length;
   1372  int64_t slace;
   1373  size_t i = 0;
   1374 
   1375  r = ne_read_vint(io, &lace, &length);
   1376  if (r != 1)
   1377    return r;
   1378  *read += length;
   1379 
   1380  sizes[i] = lace;
   1381  sum = sizes[i];
   1382 
   1383  i += 1;
   1384  n -= 1;
   1385 
   1386  while (--n) {
   1387    r = ne_read_svint(io, &slace, &length);
   1388    if (r != 1)
   1389      return r;
   1390    *read += length;
   1391    sizes[i] = sizes[i - 1] + slace;
   1392    sum += sizes[i];
   1393    i += 1;
   1394  }
   1395 
   1396  if (*read + sum > block)
   1397    return -1;
   1398 
   1399  /* Last frame is the remainder of the block. */
   1400  sizes[i] = block - *read - sum;
   1401  return 1;
   1402 }
   1403 
   1404 static uint64_t
   1405 ne_get_timecode_scale(nestegg * ctx)
   1406 {
   1407  uint64_t scale;
   1408 
   1409  if (ne_get_uint(ctx->segment.info.timecode_scale, &scale) != 0)
   1410    scale = 1000000;
   1411 
   1412  return scale;
   1413 }
   1414 
   1415 static int
   1416 ne_map_track_number_to_index(nestegg * ctx,
   1417                             unsigned int track_number,
   1418                             unsigned int * track_index)
   1419 {
   1420  struct ebml_list_node * node;
   1421  struct track_entry * t_entry;
   1422  uint64_t t_number = 0;
   1423 
   1424  if (!track_index)
   1425    return -1;
   1426  *track_index = 0;
   1427 
   1428  if (track_number == 0)
   1429    return -1;
   1430 
   1431  node = ctx->segment.tracks.track_entry.head;
   1432  while (node) {
   1433    assert(node->id == ID_TRACK_ENTRY);
   1434    t_entry = node->data;
   1435    if (ne_get_uint(t_entry->number, &t_number) != 0)
   1436      return -1;
   1437    if (t_number == track_number)
   1438      return 0;
   1439    *track_index += 1;
   1440    node = node->next;
   1441  }
   1442 
   1443  return -1;
   1444 }
   1445 
   1446 static struct track_entry *
   1447 ne_find_track_entry(nestegg * ctx, unsigned int track)
   1448 {
   1449  struct ebml_list_node * node;
   1450  unsigned int tracks = 0;
   1451 
   1452  node = ctx->segment.tracks.track_entry.head;
   1453  while (node) {
   1454    assert(node->id == ID_TRACK_ENTRY);
   1455    if (track == tracks)
   1456      return node->data;
   1457    tracks += 1;
   1458    node = node->next;
   1459  }
   1460 
   1461  return NULL;
   1462 }
   1463 
   1464 static struct frame *
   1465 ne_alloc_frame(void)
   1466 {
   1467  struct frame * f = ne_alloc(sizeof(*f));
   1468 
   1469  if (!f)
   1470    return NULL;
   1471 
   1472  f->data = NULL;
   1473  f->length = 0;
   1474  f->frame_encryption = NULL;
   1475  f->next = NULL;
   1476 
   1477  return f;
   1478 }
   1479 
   1480 static struct frame_encryption *
   1481 ne_alloc_frame_encryption(void)
   1482 {
   1483  struct frame_encryption * f = ne_alloc(sizeof(*f));
   1484 
   1485  if (!f)
   1486    return NULL;
   1487 
   1488  f->iv = NULL;
   1489  f->length = 0;
   1490  f->signal_byte = 0;
   1491  f->num_partitions = 0;
   1492  f->partition_offsets = NULL;
   1493 
   1494  return f;
   1495 }
   1496 
   1497 static void
   1498 ne_free_frame(struct frame * f)
   1499 {
   1500  if (f->frame_encryption) {
   1501    free(f->frame_encryption->iv);
   1502    free(f->frame_encryption->partition_offsets);
   1503  }
   1504 
   1505  free(f->frame_encryption);
   1506  free(f->data);
   1507  free(f);
   1508 }
   1509 
   1510 static int
   1511 ne_read_block(nestegg * ctx, uint64_t block_id, uint64_t block_size, nestegg_packet ** data)
   1512 {
   1513  int r;
   1514  int64_t timecode, abs_timecode;
   1515  nestegg_packet * pkt;
   1516  struct frame * f, * last;
   1517  struct track_entry * entry;
   1518  double track_scale;
   1519  uint64_t track_number, length, frame_sizes[256], cluster_tc, flags, frames, tc_scale, total,
   1520           encoding_type, encryption_algo, encryption_mode;
   1521  unsigned int i, lacing, track;
   1522  uint8_t signal_byte, keyframe = NESTEGG_PACKET_HAS_KEYFRAME_UNKNOWN, j = 0;
   1523  size_t consumed = 0, data_size, encryption_size;
   1524 
   1525  *data = NULL;
   1526 
   1527  if (block_size > LIMIT_BLOCK)
   1528    return -1;
   1529 
   1530  r = ne_read_vint(ctx->io, &track_number, &length);
   1531  if (r != 1)
   1532    return r;
   1533 
   1534  if (track_number == 0)
   1535    return -1;
   1536 
   1537  consumed += length;
   1538 
   1539  r = ne_read_int(ctx->io, &timecode, 2);
   1540  if (r != 1)
   1541    return r;
   1542 
   1543  consumed += 2;
   1544 
   1545  r = ne_read_uint(ctx->io, &flags, 1);
   1546  if (r != 1)
   1547    return r;
   1548 
   1549  consumed += 1;
   1550 
   1551  frames = 0;
   1552 
   1553  /* Simple blocks have an explicit flag for if the contents a keyframes*/
   1554  if (block_id == ID_SIMPLE_BLOCK)
   1555    keyframe = (flags & SIMPLE_BLOCK_FLAGS_KEYFRAME) == SIMPLE_BLOCK_FLAGS_KEYFRAME ?
   1556                                                        NESTEGG_PACKET_HAS_KEYFRAME_TRUE :
   1557                                                        NESTEGG_PACKET_HAS_KEYFRAME_FALSE;
   1558 
   1559  /* Flags are different between Block and SimpleBlock, but lacing is
   1560     encoded the same way. */
   1561  lacing = (flags & BLOCK_FLAGS_LACING) >> 1;
   1562 
   1563  switch (lacing) {
   1564  case LACING_NONE:
   1565    frames = 1;
   1566    break;
   1567  case LACING_XIPH:
   1568  case LACING_FIXED:
   1569  case LACING_EBML:
   1570    r = ne_read_uint(ctx->io, &frames, 1);
   1571    if (r != 1)
   1572      return r;
   1573    consumed += 1;
   1574    frames += 1;
   1575    break;
   1576  default:
   1577    assert(0);
   1578    return -1;
   1579  }
   1580 
   1581  if (frames > 256)
   1582    return -1;
   1583 
   1584  switch (lacing) {
   1585  case LACING_NONE:
   1586    frame_sizes[0] = block_size - consumed;
   1587    break;
   1588  case LACING_XIPH:
   1589    if (frames == 1)
   1590      return -1;
   1591    r = ne_read_xiph_lacing(ctx->io, block_size, &consumed, frames, frame_sizes);
   1592    if (r != 1)
   1593      return r;
   1594    break;
   1595  case LACING_FIXED:
   1596    if ((block_size - consumed) % frames)
   1597      return -1;
   1598    for (i = 0; i < frames; ++i)
   1599      frame_sizes[i] = (block_size - consumed) / frames;
   1600    break;
   1601  case LACING_EBML:
   1602    if (frames == 1)
   1603      return -1;
   1604    r = ne_read_ebml_lacing(ctx->io, block_size, &consumed, frames, frame_sizes);
   1605    if (r != 1)
   1606      return r;
   1607    break;
   1608  default:
   1609    assert(0);
   1610    return -1;
   1611  }
   1612 
   1613  /* Sanity check unlaced frame sizes against total block size. */
   1614  total = consumed;
   1615  for (i = 0; i < frames; ++i)
   1616    total += frame_sizes[i];
   1617  if (total > block_size)
   1618    return -1;
   1619 
   1620  if (ne_map_track_number_to_index(ctx, track_number, &track) != 0)
   1621    return -1;
   1622 
   1623  entry = ne_find_track_entry(ctx, track);
   1624  if (!entry)
   1625    return -1;
   1626 
   1627  r = ne_read_block_encryption(ctx, entry, &encoding_type, &encryption_algo, &encryption_mode);
   1628  if (r != 1)
   1629    return r;
   1630 
   1631  /* Encryption does not support lacing */
   1632  if (lacing != LACING_NONE && encoding_type == NESTEGG_ENCODING_ENCRYPTION) {
   1633    ctx->log(ctx, NESTEGG_LOG_ERROR, "Encrypted blocks may not also be laced");
   1634    return -1;
   1635  }
   1636 
   1637  track_scale = 1.0;
   1638 
   1639  tc_scale = ne_get_timecode_scale(ctx);
   1640  if (tc_scale == 0)
   1641    return -1;
   1642 
   1643  if (!ctx->read_cluster_timecode)
   1644    return -1;
   1645  cluster_tc = ctx->cluster_timecode;
   1646 
   1647  abs_timecode = timecode + cluster_tc;
   1648  if (abs_timecode < 0) {
   1649      /* Ignore the spec and negative timestamps */
   1650      ctx->log(ctx, NESTEGG_LOG_WARNING, "ignoring negative timecode: %lld", abs_timecode);
   1651      abs_timecode = 0;
   1652  }
   1653 
   1654  pkt = ne_alloc(sizeof(*pkt));
   1655  if (!pkt)
   1656    return -1;
   1657  pkt->track = track;
   1658  pkt->timecode = abs_timecode * tc_scale * track_scale;
   1659  pkt->keyframe = keyframe;
   1660 
   1661  ctx->log(ctx, NESTEGG_LOG_DEBUG, "%sblock t %lld pts %f f %llx frames: %llu",
   1662           block_id == ID_BLOCK ? "" : "simple", pkt->track, pkt->timecode / 1e9, flags, frames);
   1663 
   1664  last = NULL;
   1665  for (i = 0; i < frames; ++i) {
   1666    if (frame_sizes[i] > LIMIT_FRAME) {
   1667      nestegg_free_packet(pkt);
   1668      return -1;
   1669    }
   1670    f = ne_alloc_frame();
   1671    if (!f) {
   1672      nestegg_free_packet(pkt);
   1673      return -1;
   1674    }
   1675    /* Parse encryption */
   1676    if (encoding_type == NESTEGG_ENCODING_ENCRYPTION) {
   1677      r = ne_io_read(ctx->io, &signal_byte, SIGNAL_BYTE_SIZE);
   1678      if (r != 1) {
   1679        ne_free_frame(f);
   1680        nestegg_free_packet(pkt);
   1681        return r;
   1682      }
   1683      f->frame_encryption = ne_alloc_frame_encryption();
   1684      if (!f->frame_encryption) {
   1685        ne_free_frame(f);
   1686        nestegg_free_packet(pkt);
   1687        return -1;
   1688      }
   1689      f->frame_encryption->signal_byte = signal_byte;
   1690      if ((signal_byte & ENCRYPTED_BIT_MASK) == PACKET_ENCRYPTED) {
   1691        f->frame_encryption->iv = ne_alloc(IV_SIZE);
   1692        if (!f->frame_encryption->iv) {
   1693          ne_free_frame(f);
   1694          nestegg_free_packet(pkt);
   1695          return -1;
   1696        }
   1697        r = ne_io_read(ctx->io, f->frame_encryption->iv, IV_SIZE);
   1698        if (r != 1) {
   1699          ne_free_frame(f);
   1700          nestegg_free_packet(pkt);
   1701          return r;
   1702        }
   1703        f->frame_encryption->length = IV_SIZE;
   1704        encryption_size = SIGNAL_BYTE_SIZE + IV_SIZE;
   1705 
   1706        if ((signal_byte & PARTITIONED_BIT_MASK) == PACKET_PARTITIONED) {
   1707          r = ne_io_read(ctx->io, &f->frame_encryption->num_partitions, NUM_PACKETS_SIZE);
   1708          if (r != 1) {
   1709            ne_free_frame(f);
   1710            nestegg_free_packet(pkt);
   1711            return r;
   1712          }
   1713 
   1714          encryption_size += NUM_PACKETS_SIZE + f->frame_encryption->num_partitions * PACKET_OFFSET_SIZE;
   1715          f->frame_encryption->partition_offsets = ne_alloc(f->frame_encryption->num_partitions * PACKET_OFFSET_SIZE);
   1716 
   1717          for (j = 0; j < f->frame_encryption->num_partitions; ++j) {
   1718            uint64_t value = 0;
   1719            r = ne_read_uint(ctx->io, &value, PACKET_OFFSET_SIZE);
   1720            if (r != 1) {
   1721              break;
   1722            }
   1723 
   1724            f->frame_encryption->partition_offsets[j] = (uint32_t) value;
   1725          }
   1726 
   1727          /* If any of the partition offsets did not return 1, then fail. */
   1728          if (j != f->frame_encryption->num_partitions) {
   1729            ne_free_frame(f);
   1730            nestegg_free_packet(pkt);
   1731            return r;
   1732          }
   1733        }
   1734      } else {
   1735        encryption_size = SIGNAL_BYTE_SIZE;
   1736      }
   1737    } else {
   1738      encryption_size = 0;
   1739    }
   1740    if (encryption_size > frame_sizes[i]) {
   1741      ne_free_frame(f);
   1742      nestegg_free_packet(pkt);
   1743      return -1;
   1744    }
   1745    data_size = frame_sizes[i] - encryption_size;
   1746    /* Encryption parsed */
   1747    f->data = ne_alloc(data_size);
   1748    if (!f->data) {
   1749      ne_free_frame(f);
   1750      nestegg_free_packet(pkt);
   1751      return -1;
   1752    }
   1753    f->length = data_size;
   1754    r = ne_io_read(ctx->io, f->data, data_size);
   1755    if (r != 1) {
   1756      ne_free_frame(f);
   1757      nestegg_free_packet(pkt);
   1758      return r;
   1759    }
   1760 
   1761    if (!last)
   1762      pkt->frame = f;
   1763    else
   1764      last->next = f;
   1765    last = f;
   1766  }
   1767 
   1768  *data = pkt;
   1769 
   1770  return 1;
   1771 }
   1772 
   1773 static int
   1774 ne_read_block_additions(nestegg * ctx, uint64_t block_size, struct block_additional ** pkt_block_additional)
   1775 {
   1776  int r;
   1777  uint64_t id, size, data_size;
   1778  int64_t block_additions_end, block_more_end;
   1779  void * data;
   1780  int has_data;
   1781  struct block_additional * block_additional;
   1782  uint64_t add_id;
   1783 
   1784  assert(*pkt_block_additional == NULL);
   1785 
   1786  block_additions_end = ne_io_tell(ctx->io) + block_size;
   1787 
   1788  while (ne_io_tell(ctx->io) < block_additions_end) {
   1789    add_id = 1;
   1790    data = NULL;
   1791    has_data = 0;
   1792    data_size = 0;
   1793    r = ne_read_element(ctx, &id, &size);
   1794    if (r != 1)
   1795      return r;
   1796 
   1797    if (id != ID_BLOCK_MORE) {
   1798      /* We don't know what this element is, so skip over it */
   1799      if (id != ID_VOID && id != ID_CRC32)
   1800        ctx->log(ctx, NESTEGG_LOG_DEBUG,
   1801                 "unknown element %llx in BlockAdditions", id);
   1802      r = ne_io_read_skip(ctx->io, size);
   1803      if (r != 1)
   1804        return r;
   1805      continue;
   1806    }
   1807 
   1808    block_more_end = ne_io_tell(ctx->io) + size;
   1809 
   1810    while (ne_io_tell(ctx->io) < block_more_end) {
   1811      r = ne_read_element(ctx, &id, &size);
   1812      if (r != 1) {
   1813        free(data);
   1814        return r;
   1815      }
   1816 
   1817      if (id == ID_BLOCK_ADD_ID) {
   1818        r = ne_read_uint(ctx->io, &add_id, size);
   1819        if (r != 1) {
   1820          free(data);
   1821          return r;
   1822        }
   1823 
   1824        if (add_id == 0) {
   1825          ctx->log(ctx, NESTEGG_LOG_ERROR, "Disallowed BlockAddId 0 used");
   1826          free(data);
   1827          return -1;
   1828        }
   1829      } else if (id == ID_BLOCK_ADDITIONAL) {
   1830        if (has_data) {
   1831          /* BlockAdditional is supposed to only occur once in a
   1832             BlockMore. */
   1833          ctx->log(ctx, NESTEGG_LOG_ERROR,
   1834                   "Multiple BlockAdditional elements in a BlockMore");
   1835          free(data);
   1836          return -1;
   1837        }
   1838 
   1839        has_data = 1;
   1840        data_size = size;
   1841        if (data_size != 0 && data_size < LIMIT_FRAME) {
   1842          data = ne_alloc(data_size);
   1843          if (!data)
   1844            return -1;
   1845          r = ne_io_read(ctx->io, data, data_size);
   1846          if (r != 1) {
   1847            free(data);
   1848            return r;
   1849          }
   1850        }
   1851      } else {
   1852        /* We don't know what this element is, so skip over it */
   1853        if (id != ID_VOID && id != ID_CRC32)
   1854          ctx->log(ctx, NESTEGG_LOG_DEBUG,
   1855                   "unknown element %llx in BlockMore", id);
   1856        r = ne_io_read_skip(ctx->io, size);
   1857        if (r != 1) {
   1858          free(data);
   1859          return r;
   1860        }
   1861      }
   1862    }
   1863 
   1864    if (has_data == 0) {
   1865      ctx->log(ctx, NESTEGG_LOG_ERROR,
   1866               "No BlockAdditional element in a BlockMore");
   1867      return -1;
   1868    }
   1869 
   1870    block_additional = ne_alloc(sizeof(*block_additional));
   1871    block_additional->next = *pkt_block_additional;
   1872    block_additional->id = add_id;
   1873    block_additional->data = data;
   1874    block_additional->length = data_size;
   1875    *pkt_block_additional = block_additional;
   1876  }
   1877 
   1878  return 1;
   1879 }
   1880 
   1881 static uint64_t
   1882 ne_buf_read_id(unsigned char const * p, size_t length)
   1883 {
   1884  uint64_t id = 0;
   1885 
   1886  while (length--) {
   1887    id <<= 8;
   1888    id |= *p++;
   1889  }
   1890 
   1891  return id;
   1892 }
   1893 
   1894 static struct seek *
   1895 ne_find_seek_for_id(struct ebml_list_node * seek_head, uint64_t id)
   1896 {
   1897  struct ebml_list * head;
   1898  struct ebml_list_node * seek;
   1899  struct ebml_binary binary_id;
   1900  struct seek * s;
   1901 
   1902  while (seek_head) {
   1903    assert(seek_head->id == ID_SEEK_HEAD);
   1904    head = seek_head->data;
   1905    seek = head->head;
   1906 
   1907    while (seek) {
   1908      assert(seek->id == ID_SEEK);
   1909      s = seek->data;
   1910 
   1911      if (ne_get_binary(s->id, &binary_id) == 0 &&
   1912          ne_buf_read_id(binary_id.data, binary_id.length) == id)
   1913        return s;
   1914 
   1915      seek = seek->next;
   1916    }
   1917 
   1918    seek_head = seek_head->next;
   1919  }
   1920 
   1921  return NULL;
   1922 }
   1923 
   1924 static struct cue_track_positions *
   1925 ne_find_cue_position_for_track(nestegg * ctx, struct ebml_list_node * node, unsigned int track)
   1926 {
   1927  struct cue_track_positions * pos = NULL;
   1928  uint64_t track_number;
   1929  unsigned int t;
   1930 
   1931  while (node) {
   1932    assert(node->id == ID_CUE_TRACK_POSITIONS);
   1933    pos = node->data;
   1934    if (ne_get_uint(pos->track, &track_number) != 0)
   1935      return NULL;
   1936 
   1937    if (ne_map_track_number_to_index(ctx, track_number, &t) != 0)
   1938      return NULL;
   1939 
   1940    if (t == track)
   1941      return pos;
   1942 
   1943    node = node->next;
   1944  }
   1945 
   1946  return NULL;
   1947 }
   1948 
   1949 static struct cue_point *
   1950 ne_find_cue_point_for_tstamp(nestegg * ctx, struct ebml_list_node * cue_point, unsigned int track, uint64_t scale, uint64_t tstamp)
   1951 {
   1952  uint64_t time;
   1953  struct cue_point * c, * prev = NULL;
   1954 
   1955  while (cue_point) {
   1956    assert(cue_point->id == ID_CUE_POINT);
   1957    c = cue_point->data;
   1958 
   1959    if (!prev)
   1960      prev = c;
   1961 
   1962    if (ne_get_uint(c->time, &time) == 0 && time * scale > tstamp)
   1963      break;
   1964 
   1965    if (ne_find_cue_position_for_track(ctx, c->cue_track_positions.head, track) != NULL)
   1966      prev = c;
   1967 
   1968    cue_point = cue_point->next;
   1969  }
   1970 
   1971  return prev;
   1972 }
   1973 
   1974 static void
   1975 ne_null_log_callback(nestegg * ctx, unsigned int severity, char const * fmt, ...)
   1976 {
   1977  if (ctx && severity && fmt)
   1978    return;
   1979 }
   1980 
   1981 static int
   1982 ne_init_cue_points(nestegg * ctx, int64_t max_offset)
   1983 {
   1984  int r;
   1985  struct ebml_list_node * node = ctx->segment.cues.cue_point.head;
   1986  struct seek * found;
   1987  uint64_t seek_pos, id;
   1988  struct saved_state state;
   1989 
   1990  /* If there are no cues loaded, check for cues element in the seek head
   1991     and load it. */
   1992  if (!node) {
   1993    found = ne_find_seek_for_id(ctx->segment.seek_head.head, ID_CUES);
   1994    if (!found)
   1995      return -1;
   1996 
   1997    if (ne_get_uint(found->position, &seek_pos) != 0)
   1998      return -1;
   1999 
   2000    /* Save old parser state. */
   2001    r = ne_ctx_save(ctx, &state);
   2002    if (r != 0)
   2003      return -1;
   2004 
   2005    /* Seek and set up parser state for segment-level element (Cues). */
   2006    r = ne_io_seek(ctx->io, ctx->segment_offset + seek_pos, NESTEGG_SEEK_SET);
   2007    if (r != 0)
   2008      return -1;
   2009    ctx->last_valid = 0;
   2010 
   2011    r = ne_read_element(ctx, &id, NULL);
   2012    if (r != 1)
   2013      return -1;
   2014 
   2015    if (id != ID_CUES)
   2016      return -1;
   2017 
   2018    assert(ctx->ancestor == NULL);
   2019    if (ne_ctx_push(ctx, ne_top_level_elements, ctx) < 0)
   2020      return -1;
   2021    if (ne_ctx_push(ctx, ne_segment_elements, &ctx->segment) < 0)
   2022      return -1;
   2023    if (ne_ctx_push(ctx, ne_cues_elements, &ctx->segment.cues) < 0)
   2024      return -1;
   2025    /* parser will run until end of cues element. */
   2026    ctx->log(ctx, NESTEGG_LOG_DEBUG, "seek: parsing cue elements");
   2027    r = ne_parse(ctx, ne_cues_elements, max_offset);
   2028    while (ctx->ancestor)
   2029      ne_ctx_pop(ctx);
   2030 
   2031    /* Reset parser state to original state and seek back to old position. */
   2032    if (ne_ctx_restore(ctx, &state) != 0)
   2033      return -1;
   2034 
   2035    if (r < 0)
   2036      return -1;
   2037 
   2038    node = ctx->segment.cues.cue_point.head;
   2039    if (!node)
   2040      return -1;
   2041  }
   2042 
   2043  return 0;
   2044 }
   2045 
   2046 /* Three functions that implement the nestegg_io interface, operating on a
   2047   io_buffer. */
   2048 struct io_buffer {
   2049  unsigned char const * buffer;
   2050  size_t length;
   2051  int64_t offset;
   2052 };
   2053 
   2054 static int
   2055 ne_buffer_read(void * buffer, size_t length, void * userdata)
   2056 {
   2057  struct io_buffer * iob = userdata;
   2058  size_t available = iob->length - iob->offset;
   2059 
   2060  if (available == 0)
   2061    return 0;
   2062 
   2063  if (available < length)
   2064    return -1;
   2065 
   2066  memcpy(buffer, iob->buffer + iob->offset, length);
   2067  iob->offset += length;
   2068 
   2069  return 1;
   2070 }
   2071 
   2072 static int
   2073 ne_buffer_seek(int64_t offset, int whence, void * userdata)
   2074 {
   2075  struct io_buffer * iob = userdata;
   2076  int64_t o = iob->offset;
   2077 
   2078  switch(whence) {
   2079  case NESTEGG_SEEK_SET:
   2080    o = offset;
   2081    break;
   2082  case NESTEGG_SEEK_CUR:
   2083    o += offset;
   2084    break;
   2085  case NESTEGG_SEEK_END:
   2086    o = iob->length + offset;
   2087    break;
   2088  }
   2089 
   2090  if (o < 0 || o > (int64_t) iob->length)
   2091    return -1;
   2092 
   2093  iob->offset = o;
   2094  return 0;
   2095 }
   2096 
   2097 static int64_t
   2098 ne_buffer_tell(void * userdata)
   2099 {
   2100  struct io_buffer * iob = userdata;
   2101  return iob->offset;
   2102 }
   2103 
   2104 static int
   2105 ne_context_new(nestegg ** context, nestegg_io io, nestegg_log callback)
   2106 {
   2107  nestegg * ctx;
   2108 
   2109  if (!(io.read && io.seek && io.tell))
   2110    return -1;
   2111 
   2112  ctx = ne_alloc(sizeof(*ctx));
   2113  if (!ctx)
   2114    return -1;
   2115 
   2116  ctx->io = ne_alloc(sizeof(*ctx->io));
   2117  if (!ctx->io) {
   2118    nestegg_destroy(ctx);
   2119    return -1;
   2120  }
   2121  *ctx->io = io;
   2122  ctx->log = callback;
   2123  ctx->alloc_pool = ne_pool_init();
   2124  if (!ctx->alloc_pool) {
   2125    nestegg_destroy(ctx);
   2126    return -1;
   2127  }
   2128 
   2129  if (!ctx->log)
   2130    ctx->log = ne_null_log_callback;
   2131 
   2132  *context = ctx;
   2133  return 0;
   2134 }
   2135 
   2136 static int
   2137 ne_match_doc_type(nestegg_io io, int64_t max_offset, const char* doc_type)
   2138 {
   2139  int r;
   2140  uint64_t id;
   2141  char * doctype;
   2142  nestegg * ctx;
   2143 
   2144  if (ne_context_new(&ctx, io, NULL) != 0)
   2145    return -1;
   2146 
   2147  r = ne_peek_element(ctx, &id, NULL);
   2148  if (r != 1) {
   2149    nestegg_destroy(ctx);
   2150    return 0;
   2151  }
   2152 
   2153  if (id != ID_EBML) {
   2154    nestegg_destroy(ctx);
   2155    return 0;
   2156  }
   2157 
   2158  if (ne_ctx_push(ctx, ne_top_level_elements, ctx) < 0) {
   2159    nestegg_destroy(ctx);
   2160    return -1;
   2161  }
   2162 
   2163  /* we don't check the return value of ne_parse, that might fail because
   2164     max_offset is not on a valid element end point. We only want to check
   2165     the EBML ID and that the doctype is equal to given doc type. */
   2166  ne_parse(ctx, NULL, max_offset);
   2167  while (ctx->ancestor)
   2168    ne_ctx_pop(ctx);
   2169 
   2170  if (ne_get_string(ctx->ebml.doctype, &doctype) != 0 ||
   2171      strcmp(doctype, doc_type) != 0) {
   2172    nestegg_destroy(ctx);
   2173    return 0;
   2174  }
   2175 
   2176  nestegg_destroy(ctx);
   2177 
   2178  return 1;
   2179 }
   2180 
   2181 static void
   2182 ne_free_block_additions(struct block_additional * block_additional)
   2183 {
   2184  while (block_additional) {
   2185    struct block_additional * tmp = block_additional;
   2186    block_additional = block_additional->next;
   2187    free(tmp->data);
   2188    free(tmp);
   2189  }
   2190 }
   2191 
   2192 int
   2193 nestegg_init(nestegg ** context, nestegg_io io, nestegg_log callback, int64_t max_offset)
   2194 {
   2195  int r;
   2196  uint64_t id, version, docversion;
   2197  struct ebml_list_node * track;
   2198  char * doctype;
   2199  nestegg * ctx;
   2200 
   2201  if (ne_context_new(&ctx, io, callback) != 0)
   2202    return -1;
   2203 
   2204  r = ne_peek_element(ctx, &id, NULL);
   2205  if (r != 1) {
   2206    nestegg_destroy(ctx);
   2207    return -1;
   2208  }
   2209 
   2210  if (id != ID_EBML) {
   2211    nestegg_destroy(ctx);
   2212    return -1;
   2213  }
   2214 
   2215  ctx->log(ctx, NESTEGG_LOG_DEBUG, "ctx %p", ctx);
   2216 
   2217  if (ne_ctx_push(ctx, ne_top_level_elements, ctx) < 0) {
   2218    nestegg_destroy(ctx);
   2219    return -1;
   2220  }
   2221 
   2222  r = ne_parse(ctx, NULL, max_offset);
   2223  while (ctx->ancestor)
   2224    ne_ctx_pop(ctx);
   2225 
   2226  if (r != 1) {
   2227    nestegg_destroy(ctx);
   2228    return -1;
   2229  }
   2230 
   2231  if (ne_get_uint(ctx->ebml.ebml_read_version, &version) != 0)
   2232    version = 1;
   2233  if (version != 1) {
   2234    nestegg_destroy(ctx);
   2235    return -1;
   2236  }
   2237 
   2238  if (ne_get_string(ctx->ebml.doctype, &doctype) != 0)
   2239    doctype = DOCTYPE_MKV;
   2240  if (!!strcmp(doctype, DOCTYPE_WEBM) && !!strcmp(doctype, DOCTYPE_MKV)) {
   2241    nestegg_destroy(ctx);
   2242    return -1;
   2243  }
   2244 
   2245  if (ne_get_uint(ctx->ebml.doctype_read_version, &docversion) != 0)
   2246    docversion = 1;
   2247  if (docversion < 1 || docversion > 2) {
   2248    nestegg_destroy(ctx);
   2249    return -1;
   2250  }
   2251 
   2252  if (!ctx->segment.tracks.track_entry.head) {
   2253    nestegg_destroy(ctx);
   2254    return -1;
   2255  }
   2256 
   2257  track = ctx->segment.tracks.track_entry.head;
   2258  ctx->track_count = 0;
   2259 
   2260  while (track) {
   2261    ctx->track_count += 1;
   2262    track = track->next;
   2263  }
   2264 
   2265  r = ne_ctx_save(ctx, &ctx->saved);
   2266  if (r != 0) {
   2267    nestegg_destroy(ctx);
   2268    return -1;
   2269  }
   2270 
   2271  *context = ctx;
   2272 
   2273  return 0;
   2274 }
   2275 
   2276 void
   2277 nestegg_destroy(nestegg * ctx)
   2278 {
   2279  assert(ctx->ancestor == NULL);
   2280  if (ctx->alloc_pool)
   2281    ne_pool_destroy(ctx->alloc_pool);
   2282  free(ctx->io);
   2283  free(ctx);
   2284 }
   2285 
   2286 int
   2287 nestegg_duration(nestegg * ctx, uint64_t * duration)
   2288 {
   2289  uint64_t tc_scale;
   2290  double unscaled_duration;
   2291 
   2292  if (ne_get_float(ctx->segment.info.duration, &unscaled_duration) != 0)
   2293    return -1;
   2294 
   2295  tc_scale = ne_get_timecode_scale(ctx);
   2296  if (tc_scale == 0)
   2297    return -1;
   2298 
   2299  if (unscaled_duration != unscaled_duration ||
   2300      unscaled_duration < 0 || unscaled_duration >= (double) UINT64_MAX ||
   2301      (uint64_t) unscaled_duration > UINT64_MAX / tc_scale)
   2302    return -1;
   2303 
   2304  *duration = (uint64_t) (unscaled_duration * tc_scale);
   2305  return 0;
   2306 }
   2307 
   2308 int
   2309 nestegg_tstamp_scale(nestegg * ctx, uint64_t * scale)
   2310 {
   2311  *scale = ne_get_timecode_scale(ctx);
   2312  if (*scale == 0)
   2313    return -1;
   2314  return 0;
   2315 }
   2316 
   2317 int
   2318 nestegg_track_count(nestegg * ctx, unsigned int * tracks)
   2319 {
   2320  *tracks = ctx->track_count;
   2321  return 0;
   2322 }
   2323 
   2324 int
   2325 nestegg_get_cue_point(nestegg * ctx, unsigned int cluster_num, int64_t max_offset,
   2326                      int64_t * start_pos, int64_t * end_pos, uint64_t * tstamp)
   2327 {
   2328  int range_obtained = 0;
   2329  unsigned int cluster_count = 0;
   2330  struct cue_point * cue_point;
   2331  struct cue_track_positions * pos;
   2332  uint64_t seek_pos, track_number, tc_scale, time;
   2333  struct ebml_list_node * cues_node = ctx->segment.cues.cue_point.head;
   2334  struct ebml_list_node * cue_pos_node = NULL;
   2335  unsigned int track = 0, track_count = 0, track_index;
   2336 
   2337  if (!start_pos || !end_pos || !tstamp)
   2338    return -1;
   2339 
   2340  /* Initialise return values */
   2341  *start_pos = -1;
   2342  *end_pos = -1;
   2343  *tstamp = 0;
   2344 
   2345  if (!cues_node) {
   2346    ne_init_cue_points(ctx, max_offset);
   2347    cues_node = ctx->segment.cues.cue_point.head;
   2348    /* Verify cues have been added to context. */
   2349    if (!cues_node)
   2350      return -1;
   2351  }
   2352 
   2353  nestegg_track_count(ctx, &track_count);
   2354 
   2355  tc_scale = ne_get_timecode_scale(ctx);
   2356  if (tc_scale == 0)
   2357    return -1;
   2358 
   2359  while (cues_node && !range_obtained) {
   2360    assert(cues_node->id == ID_CUE_POINT);
   2361    cue_point = cues_node->data;
   2362    cue_pos_node = cue_point->cue_track_positions.head;
   2363    while (cue_pos_node) {
   2364      assert(cue_pos_node->id == ID_CUE_TRACK_POSITIONS);
   2365      pos = cue_pos_node->data;
   2366      for (track = 0; track < track_count; ++track) {
   2367        if (ne_get_uint(pos->track, &track_number) != 0)
   2368          return -1;
   2369 
   2370        if (ne_map_track_number_to_index(ctx, track_number, &track_index) != 0)
   2371          return -1;
   2372 
   2373        if (track_index == track) {
   2374          if (ne_get_uint(pos->cluster_position, &seek_pos) != 0)
   2375            return -1;
   2376          if (cluster_count == cluster_num) {
   2377            *start_pos = ctx->segment_offset + seek_pos;
   2378            if (ne_get_uint(cue_point->time, &time) != 0)
   2379              return -1;
   2380            *tstamp = time * tc_scale;
   2381          } else if (cluster_count == cluster_num + 1) {
   2382            *end_pos = ctx->segment_offset + seek_pos - 1;
   2383            range_obtained = 1;
   2384            break;
   2385          }
   2386          cluster_count++;
   2387        }
   2388      }
   2389      cue_pos_node = cue_pos_node->next;
   2390    }
   2391    cues_node = cues_node->next;
   2392  }
   2393 
   2394  return 0;
   2395 }
   2396 
   2397 int
   2398 nestegg_offset_seek(nestegg * ctx, uint64_t offset)
   2399 {
   2400  int r;
   2401 
   2402  if (offset > INT64_MAX)
   2403    return -1;
   2404 
   2405  /* Seek and set up parser state for segment-level element (Cluster). */
   2406  r = ne_io_seek(ctx->io, offset, NESTEGG_SEEK_SET);
   2407  if (r != 0)
   2408    return -1;
   2409  ctx->last_valid = 0;
   2410 
   2411  assert(ctx->ancestor == NULL);
   2412 
   2413  return 0;
   2414 }
   2415 
   2416 int
   2417 nestegg_track_seek(nestegg * ctx, unsigned int track, uint64_t tstamp)
   2418 {
   2419  int r;
   2420  struct cue_point * cue_point;
   2421  struct cue_track_positions * pos;
   2422  uint64_t seek_pos, tc_scale;
   2423 
   2424  /* If there are no cues loaded, check for cues element in the seek head
   2425     and load it. */
   2426  if (!ctx->segment.cues.cue_point.head) {
   2427    r = ne_init_cue_points(ctx, -1);
   2428    if (r != 0)
   2429      return -1;
   2430  }
   2431 
   2432  tc_scale = ne_get_timecode_scale(ctx);
   2433  if (tc_scale == 0)
   2434    return -1;
   2435 
   2436  cue_point = ne_find_cue_point_for_tstamp(ctx, ctx->segment.cues.cue_point.head,
   2437                                           track, tc_scale, tstamp);
   2438  if (!cue_point)
   2439    return -1;
   2440 
   2441  pos = ne_find_cue_position_for_track(ctx, cue_point->cue_track_positions.head, track);
   2442  if (pos == NULL)
   2443    return -1;
   2444 
   2445  if (ne_get_uint(pos->cluster_position, &seek_pos) != 0)
   2446    return -1;
   2447 
   2448  /* Seek to (we assume) the start of a Cluster element. */
   2449  r = nestegg_offset_seek(ctx, ctx->segment_offset + seek_pos);
   2450  if (r != 0)
   2451    return -1;
   2452 
   2453  return 0;
   2454 }
   2455 
   2456 int
   2457 nestegg_track_type(nestegg * ctx, unsigned int track)
   2458 {
   2459  struct track_entry * entry;
   2460  uint64_t type;
   2461 
   2462  entry = ne_find_track_entry(ctx, track);
   2463  if (!entry)
   2464    return -1;
   2465 
   2466  if (ne_get_uint(entry->type, &type) != 0)
   2467    return -1;
   2468 
   2469  if (type == TRACK_TYPE_VIDEO)
   2470    return NESTEGG_TRACK_VIDEO;
   2471 
   2472  if (type == TRACK_TYPE_AUDIO)
   2473    return NESTEGG_TRACK_AUDIO;
   2474 
   2475  return NESTEGG_TRACK_UNKNOWN;
   2476 }
   2477 
   2478 int
   2479 nestegg_track_codec_id(nestegg * ctx, unsigned int track)
   2480 {
   2481  char * codec_id;
   2482  struct track_entry * entry;
   2483 
   2484  entry = ne_find_track_entry(ctx, track);
   2485  if (!entry)
   2486    return -1;
   2487 
   2488  if (ne_get_string(entry->codec_id, &codec_id) != 0)
   2489    return -1;
   2490 
   2491  ctx->log(ctx, NESTEGG_LOG_DEBUG, "nestegg_track_codec_id: %s\n", codec_id);
   2492  if (strcmp(codec_id, TRACK_ID_VP8) == 0)
   2493    return NESTEGG_CODEC_VP8;
   2494 
   2495  if (strcmp(codec_id, TRACK_ID_VP9) == 0)
   2496    return NESTEGG_CODEC_VP9;
   2497 
   2498  if (strcmp(codec_id, TRACK_ID_AV1) == 0)
   2499    return NESTEGG_CODEC_AV1;
   2500 
   2501  if (strcmp(codec_id, TRACK_ID_VORBIS) == 0)
   2502    return NESTEGG_CODEC_VORBIS;
   2503 
   2504  if (strcmp(codec_id, TRACK_ID_OPUS) == 0)
   2505    return NESTEGG_CODEC_OPUS;
   2506 
   2507  if (strcmp(codec_id, TRACK_ID_AVC) == 0)
   2508    return NESTEGG_CODEC_AVC;
   2509 
   2510  if (strcmp(codec_id, TRACK_ID_HEVC) == 0)
   2511    return NESTEGG_CODEC_HEVC;
   2512 
   2513  if (strcmp(codec_id, TRACK_ID_AAC) == 0 ||
   2514      strcmp(codec_id, TRACK_ID_AAC_MP4_LC) == 0 ||
   2515      strcmp(codec_id, TRACK_ID_AAC_MP4_LC_SBR) == 0 ||
   2516      strcmp(codec_id, TRACK_ID_AAC_MP4_LTP) == 0 ||
   2517      strcmp(codec_id, TRACK_ID_AAC_MP4_MAIN) == 0 ||
   2518      strcmp(codec_id, TRACK_ID_AAC_MP4_SSR) == 0)
   2519    return NESTEGG_CODEC_AAC;
   2520 
   2521  if (strcmp(codec_id, TRACK_ID_FLAC) == 0)
   2522    return NESTEGG_CODEC_FLAC;
   2523 
   2524  if (strcmp(codec_id, TRACK_ID_MP3) == 0)
   2525    return NESTEGG_CODEC_MP3;
   2526 
   2527  if (strcmp(codec_id, TRACK_ID_PCM_FLOAT) == 0 ||
   2528      strcmp(codec_id, TRACK_ID_PCM_INT_BE) == 0 ||
   2529      strcmp(codec_id, TRACK_ID_PCM_INT_LE) == 0)
   2530    return NESTEGG_CODEC_PCM;
   2531 
   2532  return NESTEGG_CODEC_UNKNOWN;
   2533 }
   2534 
   2535 int
   2536 nestegg_track_codec_data_count(nestegg * ctx, unsigned int track,
   2537                               unsigned int * count)
   2538 {
   2539  struct track_entry * entry;
   2540  struct ebml_binary codec_private;
   2541  int codec_id;
   2542  unsigned char * p;
   2543 
   2544  *count = 0;
   2545 
   2546  entry = ne_find_track_entry(ctx, track);
   2547  if (!entry)
   2548    return -1;
   2549 
   2550  codec_id = nestegg_track_codec_id(ctx, track);
   2551 
   2552  /* Usually don't have codec private */
   2553  if (codec_id == NESTEGG_CODEC_MP3 || codec_id == NESTEGG_CODEC_VP8 ||
   2554      codec_id == NESTEGG_CODEC_VP9) {
   2555    *count = 0;
   2556    return 0;
   2557  }
   2558 
   2559  /* Usually one codec private */
   2560  if (codec_id == NESTEGG_CODEC_OPUS || codec_id == NESTEGG_CODEC_PCM ||
   2561      codec_id == NESTEGG_CODEC_AAC  || codec_id == NESTEGG_CODEC_FLAC ||
   2562      codec_id == NESTEGG_CODEC_AVC || codec_id == NESTEGG_CODEC_HEVC ||
   2563      codec_id == NESTEGG_CODEC_AV1) {
   2564    *count = 1;
   2565    return 0;
   2566  }
   2567 
   2568  /* Vorbis spec requires three headers in the codec private */
   2569  if (codec_id != NESTEGG_CODEC_VORBIS)
   2570    return -1;
   2571 
   2572  if (ne_get_binary(entry->codec_private, &codec_private) != 0)
   2573    return -1;
   2574 
   2575  if (codec_private.length < 1)
   2576    return -1;
   2577 
   2578  p = codec_private.data;
   2579  *count = *p + 1;
   2580 
   2581  if (*count > 3)
   2582    return -1;
   2583 
   2584  return 0;
   2585 }
   2586 
   2587 int
   2588 nestegg_track_codec_data(nestegg * ctx, unsigned int track, unsigned int item,
   2589                         unsigned char ** data, size_t * length)
   2590 {
   2591  struct track_entry * entry;
   2592  struct ebml_binary codec_private;
   2593  unsigned int count = 0;
   2594 
   2595  *data = NULL;
   2596  *length = 0;
   2597 
   2598  entry = ne_find_track_entry(ctx, track);
   2599  if (!entry)
   2600    return -1;
   2601 
   2602  if (nestegg_track_codec_data_count(ctx, track, &count) != 0 || count == 0)
   2603    return -1;
   2604 
   2605  if (ne_get_binary(entry->codec_private, &codec_private) != 0)
   2606    return -1;
   2607 
   2608  if (nestegg_track_codec_id(ctx, track) == NESTEGG_CODEC_VORBIS) {
   2609    uint64_t count;
   2610    uint64_t sizes[3];
   2611    size_t total;
   2612    unsigned char * p;
   2613    unsigned int i;
   2614    int r;
   2615 
   2616    nestegg_io io;
   2617    struct io_buffer userdata;
   2618    userdata.buffer = codec_private.data;
   2619    userdata.length = codec_private.length;
   2620    userdata.offset = 0;
   2621 
   2622    io.read = ne_buffer_read;
   2623    io.seek = ne_buffer_seek;
   2624    io.tell = ne_buffer_tell;
   2625    io.userdata = &userdata;
   2626 
   2627    total = 0;
   2628 
   2629    r = ne_read_uint(&io, &count, 1);
   2630    if (r != 1)
   2631      return r;
   2632    total += 1;
   2633    count += 1;
   2634 
   2635    if (count > 3)
   2636      return -1;
   2637    r = ne_read_xiph_lacing(&io, codec_private.length, &total, count, sizes);
   2638    if (r != 1)
   2639      return r;
   2640 
   2641    if (item >= count)
   2642      return -1;
   2643 
   2644    p = codec_private.data + total;
   2645    for (i = 0; i < item; ++i) {
   2646      p += sizes[i];
   2647    }
   2648    assert((size_t) (p - codec_private.data) <= codec_private.length &&
   2649           codec_private.length - (p - codec_private.data) >= sizes[item]);
   2650    *data = p;
   2651    *length = sizes[item];
   2652  } else {
   2653    if (item >= 1)
   2654      return -1;
   2655 
   2656    *data = codec_private.data;
   2657    *length = codec_private.length;
   2658  }
   2659 
   2660  return 0;
   2661 }
   2662 
   2663 int
   2664 nestegg_track_video_params(nestegg * ctx, unsigned int track,
   2665                           nestegg_video_params * params)
   2666 {
   2667  struct track_entry * entry;
   2668  uint64_t value;
   2669  double fvalue;
   2670 
   2671  memset(params, 0, sizeof(*params));
   2672 
   2673  entry = ne_find_track_entry(ctx, track);
   2674  if (!entry)
   2675    return -1;
   2676 
   2677  if (nestegg_track_type(ctx, track) != NESTEGG_TRACK_VIDEO)
   2678    return -1;
   2679 
   2680  value = 0;
   2681  ne_get_uint(entry->video.stereo_mode, &value);
   2682  if (value <= NESTEGG_VIDEO_STEREO_TOP_BOTTOM ||
   2683      value == NESTEGG_VIDEO_STEREO_RIGHT_LEFT)
   2684    params->stereo_mode = value;
   2685 
   2686  value = 0;
   2687  ne_get_uint(entry->video.alpha_mode, &value);
   2688  params->alpha_mode = value;
   2689 
   2690  if (ne_get_uint(entry->video.pixel_width, &value) != 0)
   2691    return -1;
   2692  params->width = value;
   2693 
   2694  if (ne_get_uint(entry->video.pixel_height, &value) != 0)
   2695    return -1;
   2696  params->height = value;
   2697 
   2698  value = 0;
   2699  ne_get_uint(entry->video.pixel_crop_bottom, &value);
   2700  params->crop_bottom = value;
   2701 
   2702  value = 0;
   2703  ne_get_uint(entry->video.pixel_crop_top, &value);
   2704  params->crop_top = value;
   2705 
   2706  value = 0;
   2707  ne_get_uint(entry->video.pixel_crop_left, &value);
   2708  params->crop_left = value;
   2709 
   2710  value = 0;
   2711  ne_get_uint(entry->video.pixel_crop_right, &value);
   2712  params->crop_right = value;
   2713 
   2714  value = params->width;
   2715  ne_get_uint(entry->video.display_width, &value);
   2716  params->display_width = value;
   2717 
   2718  value = params->height;
   2719  ne_get_uint(entry->video.display_height, &value);
   2720  params->display_height = value;
   2721 
   2722  value = 2;
   2723  ne_get_uint(entry->video.colour.matrix_coefficients, &value);
   2724  params->matrix_coefficients = value;
   2725 
   2726  value = 0;
   2727  ne_get_uint(entry->video.colour.range, &value);
   2728  params->range = value;
   2729 
   2730  value = 2;
   2731  ne_get_uint(entry->video.colour.transfer_characteristics, &value);
   2732  params->transfer_characteristics = value;
   2733 
   2734  value = 2;
   2735  ne_get_uint(entry->video.colour.primaries, &value);
   2736  params->primaries = value;
   2737 
   2738  fvalue = strtod("NaN", NULL);
   2739  ne_get_float(entry->video.colour.mastering_metadata.primary_r_chromacity_x, &fvalue);
   2740  params->primary_r_chromacity_x = fvalue;
   2741 
   2742  fvalue = strtod("NaN", NULL);
   2743  ne_get_float(entry->video.colour.mastering_metadata.primary_r_chromacity_y, &fvalue);
   2744  params->primary_r_chromacity_y = fvalue;
   2745 
   2746  fvalue = strtod("NaN", NULL);
   2747  ne_get_float(entry->video.colour.mastering_metadata.primary_g_chromacity_x, &fvalue);
   2748  params->primary_g_chromacity_x = fvalue;
   2749 
   2750  fvalue = strtod("NaN", NULL);
   2751  ne_get_float(entry->video.colour.mastering_metadata.primary_g_chromacity_y, &fvalue);
   2752  params->primary_g_chromacity_y = fvalue;
   2753 
   2754  fvalue = strtod("NaN", NULL);
   2755  ne_get_float(entry->video.colour.mastering_metadata.primary_b_chromacity_x, &fvalue);
   2756  params->primary_b_chromacity_x = fvalue;
   2757 
   2758  fvalue = strtod("NaN", NULL);
   2759  ne_get_float(entry->video.colour.mastering_metadata.primary_b_chromacity_y, &fvalue);
   2760  params->primary_b_chromacity_y = fvalue;
   2761 
   2762  fvalue = strtod("NaN", NULL);
   2763  ne_get_float(entry->video.colour.mastering_metadata.white_point_chromaticity_x, &fvalue);
   2764  params->white_point_chromaticity_x = fvalue;
   2765 
   2766  fvalue = strtod("NaN", NULL);
   2767  ne_get_float(entry->video.colour.mastering_metadata.white_point_chromaticity_y, &fvalue);
   2768  params->white_point_chromaticity_y = fvalue;
   2769 
   2770  fvalue = strtod("NaN", NULL);
   2771  ne_get_float(entry->video.colour.mastering_metadata.luminance_max, &fvalue);
   2772  params->luminance_max = fvalue;
   2773 
   2774  fvalue = strtod("NaN", NULL);
   2775  ne_get_float(entry->video.colour.mastering_metadata.luminance_min, &fvalue);
   2776  params->luminance_min = fvalue;
   2777 
   2778  return 0;
   2779 }
   2780 
   2781 int
   2782 nestegg_track_audio_params(nestegg * ctx, unsigned int track,
   2783                           nestegg_audio_params * params)
   2784 {
   2785  struct track_entry * entry;
   2786  uint64_t value;
   2787 
   2788  memset(params, 0, sizeof(*params));
   2789 
   2790  entry = ne_find_track_entry(ctx, track);
   2791  if (!entry)
   2792    return -1;
   2793 
   2794  if (nestegg_track_type(ctx, track) != NESTEGG_TRACK_AUDIO)
   2795    return -1;
   2796 
   2797  params->rate = 8000;
   2798  ne_get_float(entry->audio.sampling_frequency, &params->rate);
   2799 
   2800  value = 1;
   2801  ne_get_uint(entry->audio.channels, &value);
   2802  params->channels = value;
   2803 
   2804  value = 16;
   2805  ne_get_uint(entry->audio.bit_depth, &value);
   2806  params->depth = value;
   2807 
   2808  value = 0;
   2809  ne_get_uint(entry->codec_delay, &value);
   2810  params->codec_delay = value;
   2811 
   2812  value = 0;
   2813  ne_get_uint(entry->seek_preroll, &value);
   2814  params->seek_preroll = value;
   2815 
   2816  return 0;
   2817 }
   2818 
   2819 int
   2820 nestegg_track_encoding(nestegg * ctx, unsigned int track)
   2821 {
   2822  struct track_entry * entry;
   2823  struct content_encoding * encoding;
   2824  uint64_t encoding_value;
   2825 
   2826  entry = ne_find_track_entry(ctx, track);
   2827  if (!entry) {
   2828    ctx->log(ctx, NESTEGG_LOG_ERROR, "No track entry found");
   2829    return -1;
   2830  }
   2831 
   2832  if (!entry->content_encodings.content_encoding.head) {
   2833    /* Default encoding is compression */
   2834    return NESTEGG_ENCODING_COMPRESSION;
   2835  }
   2836 
   2837  encoding = entry->content_encodings.content_encoding.head->data;
   2838 
   2839  encoding_value = NESTEGG_ENCODING_COMPRESSION;
   2840  ne_get_uint(encoding->content_encoding_type, &encoding_value);
   2841  if (encoding_value != NESTEGG_ENCODING_COMPRESSION && encoding_value != NESTEGG_ENCODING_ENCRYPTION) {
   2842    ctx->log(ctx, NESTEGG_LOG_ERROR, "Invalid ContentEncoding element found");
   2843    return -1;
   2844  }
   2845 
   2846  return encoding_value;
   2847 }
   2848 
   2849 int
   2850 nestegg_track_content_enc_key_id(nestegg * ctx, unsigned int track, unsigned char const ** content_enc_key_id,
   2851                                 size_t * content_enc_key_id_length)
   2852 {
   2853  struct track_entry * entry;
   2854  struct content_encoding * encoding;
   2855  struct content_encryption * encryption;
   2856  struct content_enc_aes_settings * aes_settings;
   2857  struct nestegg_encryption_params;
   2858  uint64_t value;
   2859  struct ebml_binary enc_key_id;
   2860 
   2861  entry = ne_find_track_entry(ctx, track);
   2862  if (!entry) {
   2863    ctx->log(ctx, NESTEGG_LOG_ERROR, "No track entry found");
   2864    return -1;
   2865  }
   2866 
   2867  if (!entry->content_encodings.content_encoding.head) {
   2868    ctx->log(ctx, NESTEGG_LOG_ERROR, "No ContentEncoding element found");
   2869    return -1;
   2870  }
   2871 
   2872  encoding = entry->content_encodings.content_encoding.head->data;
   2873 
   2874  value = 0;
   2875  ne_get_uint(encoding->content_encoding_type, &value);
   2876  if (value != NESTEGG_ENCODING_ENCRYPTION) {
   2877    ctx->log(ctx, NESTEGG_LOG_ERROR, "Disallowed ContentEncodingType found");
   2878    return -1;
   2879  }
   2880 
   2881  if (!encoding->content_encryption.head) {
   2882    ctx->log(ctx, NESTEGG_LOG_ERROR, "No ContentEncryption element found");
   2883    return -1;
   2884  }
   2885 
   2886  encryption = encoding->content_encryption.head->data;
   2887 
   2888  value = 0;
   2889  ne_get_uint(encryption->content_enc_algo, &value);
   2890 
   2891  if (value != CONTENT_ENC_ALGO_AES) {
   2892    ctx->log(ctx, NESTEGG_LOG_ERROR, "Disallowed ContentEncAlgo found");
   2893    return -1;
   2894  }
   2895 
   2896  if (!encryption->content_enc_aes_settings.head) {
   2897    ctx->log(ctx, NESTEGG_LOG_ERROR, "No ContentEncAesSettings element found");
   2898    return -1;
   2899  }
   2900 
   2901  aes_settings = encryption->content_enc_aes_settings.head->data;
   2902  value = AES_SETTINGS_CIPHER_CTR;
   2903  ne_get_uint(aes_settings->aes_settings_cipher_mode, &value);
   2904 
   2905  if (value != AES_SETTINGS_CIPHER_CTR) {
   2906    ctx->log(ctx, NESTEGG_LOG_ERROR, "Disallowed AESSettingCipherMode used");
   2907    return -1;
   2908  }
   2909 
   2910  if (ne_get_binary(encryption->content_enc_key_id, &enc_key_id) != 0) {
   2911    ctx->log(ctx, NESTEGG_LOG_ERROR, "Could not retrieve track ContentEncKeyId");
   2912    return -1;
   2913  }
   2914 
   2915  *content_enc_key_id = enc_key_id.data;
   2916  *content_enc_key_id_length = enc_key_id.length;
   2917 
   2918  return 0;
   2919 }
   2920 
   2921 int
   2922 nestegg_track_default_duration(nestegg * ctx, unsigned int track,
   2923                               uint64_t * duration)
   2924 {
   2925  struct track_entry * entry;
   2926  uint64_t value;
   2927 
   2928  entry = ne_find_track_entry(ctx, track);
   2929  if (!entry)
   2930    return -1;
   2931 
   2932  if (ne_get_uint(entry->default_duration, &value) != 0)
   2933    return -1;
   2934  *duration = value;
   2935 
   2936  return 0;
   2937 }
   2938 
   2939 int
   2940 nestegg_read_reset(nestegg * ctx)
   2941 {
   2942  assert(ctx->ancestor == NULL);
   2943  return ne_ctx_restore(ctx, &ctx->saved);
   2944 }
   2945 
   2946 int
   2947 nestegg_read_packet(nestegg * ctx, nestegg_packet ** pkt)
   2948 {
   2949  int r, read_block = 0;
   2950  uint64_t id, size;
   2951 
   2952  *pkt = NULL;
   2953 
   2954  assert(ctx->ancestor == NULL);
   2955 
   2956  /* Prepare for read_reset to resume parsing from this point upon error. */
   2957  r = ne_ctx_save(ctx, &ctx->saved);
   2958  if (r != 0)
   2959    return -1;
   2960 
   2961  while (!read_block) {
   2962    r = ne_read_element(ctx, &id, &size);
   2963    if (r != 1)
   2964      return r;
   2965 
   2966    switch (id) {
   2967    case ID_CLUSTER: {
   2968      r = ne_read_element(ctx, &id, &size);
   2969      if (r != 1)
   2970        return r;
   2971 
   2972      /* Matroska may place a CRC32 before the Timecode. Skip and continue parsing. */
   2973      if (id == ID_CRC32) {
   2974        r = ne_io_read_skip(ctx->io, size);
   2975        if (r != 1)
   2976          return r;
   2977 
   2978        r = ne_read_element(ctx, &id, &size);
   2979        if (r != 1)
   2980          return r;
   2981      }
   2982 
   2983      /* Timecode must be the first element in a Cluster, per WebM spec. */
   2984      if (id != ID_TIMECODE)
   2985        return -1;
   2986 
   2987      r = ne_read_uint(ctx->io, &ctx->cluster_timecode, size);
   2988      if (r != 1)
   2989        return r;
   2990      ctx->read_cluster_timecode = 1;
   2991      break;
   2992    }
   2993    case ID_SIMPLE_BLOCK:
   2994      r = ne_read_block(ctx, id, size, pkt);
   2995      if (r != 1)
   2996        return r;
   2997 
   2998      read_block = 1;
   2999      break;
   3000    case ID_BLOCK_GROUP: {
   3001      int64_t block_group_end;
   3002      uint64_t block_duration = 0;
   3003      int read_block_duration = 0;
   3004      int64_t discard_padding = 0;
   3005      int read_discard_padding = 0;
   3006      int64_t reference_block = 0;
   3007      int read_reference_block = 0;
   3008      struct block_additional * block_additional = NULL;
   3009      uint64_t tc_scale;
   3010 
   3011      block_group_end = ne_io_tell(ctx->io) + size;
   3012 
   3013      /* Read the entire BlockGroup manually. */
   3014      while (ne_io_tell(ctx->io) < block_group_end) {
   3015        r = ne_read_element(ctx, &id, &size);
   3016        if (r != 1) {
   3017          ne_free_block_additions(block_additional);
   3018          if (*pkt) {
   3019            nestegg_free_packet(*pkt);
   3020            *pkt = NULL;
   3021          }
   3022          return r;
   3023        }
   3024 
   3025        switch (id) {
   3026        case ID_BLOCK: {
   3027          if (*pkt) {
   3028            ctx->log(ctx, NESTEGG_LOG_DEBUG,
   3029                     "read_packet: multiple Blocks in BlockGroup, dropping previously read Block");
   3030            nestegg_free_packet(*pkt);
   3031          }
   3032          r = ne_read_block(ctx, id, size, pkt);
   3033          if (r != 1) {
   3034            ne_free_block_additions(block_additional);
   3035            if (*pkt) {
   3036              nestegg_free_packet(*pkt);
   3037              *pkt = NULL;
   3038            }
   3039            return r;
   3040          }
   3041 
   3042          read_block = 1;
   3043          break;
   3044        }
   3045        case ID_BLOCK_DURATION: {
   3046          r = ne_read_uint(ctx->io, &block_duration, size);
   3047          if (r != 1) {
   3048            ne_free_block_additions(block_additional);
   3049            if (*pkt) {
   3050              nestegg_free_packet(*pkt);
   3051              *pkt = NULL;
   3052            }
   3053            return r;
   3054          }
   3055          tc_scale = ne_get_timecode_scale(ctx);
   3056          if (tc_scale == 0) {
   3057            ne_free_block_additions(block_additional);
   3058            if (*pkt) {
   3059              nestegg_free_packet(*pkt);
   3060              *pkt = NULL;
   3061            }
   3062            return -1;
   3063          }
   3064          block_duration *= tc_scale;
   3065          read_block_duration = 1;
   3066          break;
   3067        }
   3068        case ID_DISCARD_PADDING: {
   3069          r = ne_read_int(ctx->io, &discard_padding, size);
   3070          if (r != 1) {
   3071            ne_free_block_additions(block_additional);
   3072            if (*pkt) {
   3073              nestegg_free_packet(*pkt);
   3074              *pkt = NULL;
   3075            }
   3076            return r;
   3077          }
   3078          read_discard_padding = 1;
   3079          break;
   3080        }
   3081        case ID_BLOCK_ADDITIONS: {
   3082          /* There should only be one BlockAdditions; treat multiple as an error. */
   3083          if (block_additional) {
   3084            ne_free_block_additions(block_additional);
   3085            if (*pkt) {
   3086              nestegg_free_packet(*pkt);
   3087              *pkt = NULL;
   3088            }
   3089            return -1;
   3090          }
   3091          r = ne_read_block_additions(ctx, size, &block_additional);
   3092          if (r != 1) {
   3093            ne_free_block_additions(block_additional);
   3094            if (*pkt) {
   3095              nestegg_free_packet(*pkt);
   3096              *pkt = NULL;
   3097            }
   3098            return r;
   3099          }
   3100          break;
   3101        }
   3102        case ID_REFERENCE_BLOCK: {
   3103          r = ne_read_int(ctx->io, &reference_block, size);
   3104          if (r != 1) {
   3105            ne_free_block_additions(block_additional);
   3106            if (*pkt) {
   3107              nestegg_free_packet(*pkt);
   3108              *pkt = NULL;
   3109            }
   3110            return r;
   3111          }
   3112          read_reference_block = 1;
   3113          break;
   3114        }
   3115        default:
   3116          /* We don't know what this element is, so skip over it */
   3117          if (id != ID_VOID && id != ID_CRC32)
   3118            ctx->log(ctx, NESTEGG_LOG_DEBUG,
   3119                     "read_packet: unknown element %llx in BlockGroup", id);
   3120          r = ne_io_read_skip(ctx->io, size);
   3121          if (r != 1) {
   3122            ne_free_block_additions(block_additional);
   3123            if (*pkt) {
   3124              nestegg_free_packet(*pkt);
   3125              *pkt = NULL;
   3126            }
   3127            return r;
   3128          }
   3129        }
   3130      }
   3131 
   3132      assert(read_block == (*pkt != NULL));
   3133      if (*pkt) {
   3134        (*pkt)->duration = block_duration;
   3135        (*pkt)->read_duration = read_block_duration;
   3136        (*pkt)->discard_padding = discard_padding;
   3137        (*pkt)->read_discard_padding = read_discard_padding;
   3138        (*pkt)->reference_block = reference_block;
   3139        (*pkt)->read_reference_block = read_reference_block;
   3140        (*pkt)->block_additional = block_additional;
   3141        if ((*pkt)->read_reference_block)
   3142          /* If a packet has a reference block it contains
   3143             predictive frames and no keyframes */
   3144          (*pkt)->keyframe = NESTEGG_PACKET_HAS_KEYFRAME_FALSE;
   3145      } else {
   3146        ne_free_block_additions(block_additional);
   3147      }
   3148      break;
   3149    }
   3150    default:
   3151      ctx->log(ctx, NESTEGG_LOG_DEBUG, "read_packet: unknown element %llx", id);
   3152      r = ne_io_read_skip(ctx->io, size);
   3153      if (r != 1)
   3154        return r;
   3155    }
   3156  }
   3157 
   3158  return 1;
   3159 }
   3160 
   3161 int
   3162 nestegg_read_last_packet(nestegg * context, unsigned int track,
   3163                         nestegg_packet ** packet)
   3164 {
   3165  struct saved_state saved;
   3166  uint64_t max_end_ns = 0;
   3167  nestegg_packet * last_packet = NULL;
   3168 
   3169  if (!context || !packet) {
   3170    return -1;
   3171  }
   3172 
   3173  *packet = NULL;
   3174 
   3175  /* Save and restore the parser state later. */
   3176  ne_ctx_save(context, &saved);
   3177 
   3178  for (;;) {
   3179    nestegg_packet * pkt = NULL;
   3180    unsigned int pkt_track = 0;
   3181    int r = nestegg_read_packet(context, &pkt);
   3182    if (r == 0) {
   3183      /* EOS */
   3184      break;
   3185    }
   3186    if (r < 0) {
   3187      if (pkt) {
   3188        nestegg_free_packet(pkt);
   3189      }
   3190      if (last_packet) {
   3191        nestegg_free_packet(last_packet);
   3192        last_packet = NULL;
   3193      }
   3194      ne_ctx_restore(context, &saved);
   3195      return -1;
   3196    }
   3197 
   3198    if (nestegg_packet_track(pkt, &pkt_track) == 0 && pkt_track == track) {
   3199      /* Calculate the end timestamp of this packet */
   3200      uint64_t ts = 0;
   3201      uint64_t dur = 0;
   3202      uint64_t end_ns = 0;
   3203      nestegg_packet_tstamp(pkt, &ts);
   3204      if (nestegg_packet_duration(pkt, &dur) != 0) {
   3205        dur = 0;
   3206      }
   3207      end_ns = ts + dur;
   3208      if (end_ns >= max_end_ns) {
   3209        if (last_packet) {
   3210          nestegg_free_packet(last_packet);
   3211        }
   3212        last_packet = pkt;
   3213        max_end_ns = end_ns;
   3214        pkt = NULL;
   3215      }
   3216    }
   3217 
   3218    if (pkt) {
   3219      nestegg_free_packet(pkt);
   3220    }
   3221  }
   3222 
   3223  ne_ctx_restore(context, &saved);
   3224 
   3225  if (!last_packet) {
   3226    return -1;
   3227  }
   3228  *packet = last_packet;
   3229  return 0;
   3230 }
   3231 
   3232 void
   3233 nestegg_free_packet(nestegg_packet * pkt)
   3234 {
   3235  struct frame * frame;
   3236 
   3237  while (pkt->frame) {
   3238    frame = pkt->frame;
   3239    pkt->frame = frame->next;
   3240 
   3241    ne_free_frame(frame);
   3242  }
   3243 
   3244  ne_free_block_additions(pkt->block_additional);
   3245 
   3246  free(pkt);
   3247 }
   3248 
   3249 int
   3250 nestegg_packet_has_keyframe(nestegg_packet * pkt)
   3251 {
   3252  return pkt->keyframe;
   3253 }
   3254 
   3255 int
   3256 nestegg_packet_track(nestegg_packet * pkt, unsigned int * track)
   3257 {
   3258  *track = pkt->track;
   3259  return 0;
   3260 }
   3261 
   3262 int
   3263 nestegg_packet_tstamp(nestegg_packet * pkt, uint64_t * tstamp)
   3264 {
   3265  *tstamp = pkt->timecode;
   3266  return 0;
   3267 }
   3268 
   3269 int
   3270 nestegg_packet_duration(nestegg_packet * pkt, uint64_t * duration)
   3271 {
   3272  if (!pkt->read_duration)
   3273    return -1;
   3274  *duration = pkt->duration;
   3275  return 0;
   3276 }
   3277 
   3278 int
   3279 nestegg_packet_discard_padding(nestegg_packet * pkt, int64_t * discard_padding)
   3280 {
   3281  if (!pkt->read_discard_padding)
   3282    return -1;
   3283  *discard_padding = pkt->discard_padding;
   3284  return 0;
   3285 }
   3286 
   3287 int
   3288 nestegg_packet_reference_block(nestegg_packet * pkt, int64_t * reference_block)
   3289 {
   3290  if (!pkt->read_reference_block)
   3291    return -1;
   3292  *reference_block = pkt->reference_block;
   3293  return 0;
   3294 }
   3295 
   3296 int
   3297 nestegg_packet_count(nestegg_packet * pkt, unsigned int * count)
   3298 {
   3299  struct frame * f = pkt->frame;
   3300 
   3301  *count = 0;
   3302 
   3303  while (f) {
   3304    *count += 1;
   3305    f = f->next;
   3306  }
   3307 
   3308  return 0;
   3309 }
   3310 
   3311 int
   3312 nestegg_packet_data(nestegg_packet * pkt, unsigned int item,
   3313                    unsigned char ** data, size_t * length)
   3314 {
   3315  struct frame * f = pkt->frame;
   3316  unsigned int count = 0;
   3317 
   3318  *data = NULL;
   3319  *length = 0;
   3320 
   3321  while (f) {
   3322    if (count == item) {
   3323      *data = f->data;
   3324      *length = f->length;
   3325      return 0;
   3326    }
   3327    count += 1;
   3328    f = f->next;
   3329  }
   3330 
   3331  return -1;
   3332 }
   3333 
   3334 int
   3335 nestegg_packet_additional_data(nestegg_packet * pkt, unsigned int id,
   3336                               unsigned char ** data, size_t * length)
   3337 {
   3338  struct block_additional * a = pkt->block_additional;
   3339 
   3340  *data = NULL;
   3341  *length = 0;
   3342 
   3343  while (a) {
   3344    if (a->id == id) {
   3345      *data = a->data;
   3346      *length = a->length;
   3347      return 0;
   3348    }
   3349    a = a->next;
   3350  }
   3351 
   3352  return -1;
   3353 }
   3354 
   3355 int
   3356 nestegg_packet_encryption(nestegg_packet * pkt)
   3357 {
   3358  struct frame * f = pkt->frame;
   3359  unsigned char encrypted_bit;
   3360  unsigned char partitioned_bit;
   3361 
   3362  if (!f->frame_encryption)
   3363    return NESTEGG_PACKET_HAS_SIGNAL_BYTE_FALSE;
   3364 
   3365  /* Should never have parsed blocks with both encryption and lacing */
   3366  assert(f->next == NULL);
   3367 
   3368  encrypted_bit = f->frame_encryption->signal_byte & ENCRYPTED_BIT_MASK;
   3369  partitioned_bit = f->frame_encryption->signal_byte & PARTITIONED_BIT_MASK;
   3370 
   3371  if (encrypted_bit != PACKET_ENCRYPTED)
   3372    return NESTEGG_PACKET_HAS_SIGNAL_BYTE_UNENCRYPTED;
   3373 
   3374  if (partitioned_bit == PACKET_PARTITIONED)
   3375    return NESTEGG_PACKET_HAS_SIGNAL_BYTE_PARTITIONED;
   3376 
   3377  return NESTEGG_PACKET_HAS_SIGNAL_BYTE_ENCRYPTED;
   3378 }
   3379 
   3380 int
   3381 nestegg_packet_iv(nestegg_packet * pkt, unsigned char const ** iv, size_t * length)
   3382 {
   3383  struct frame * f = pkt->frame;
   3384  unsigned char encrypted_bit;
   3385 
   3386  *iv = NULL;
   3387  *length = 0;
   3388  if (!f->frame_encryption)
   3389    return -1;
   3390 
   3391  /* Should never have parsed blocks with both encryption and lacing */
   3392  assert(f->next == NULL);
   3393 
   3394  encrypted_bit = f->frame_encryption->signal_byte & ENCRYPTED_BIT_MASK;
   3395 
   3396  if (encrypted_bit != PACKET_ENCRYPTED)
   3397    return 0;
   3398 
   3399  *iv = f->frame_encryption->iv;
   3400  *length = f->frame_encryption->length;
   3401  return 0;
   3402 }
   3403 
   3404 int
   3405 nestegg_packet_offsets(nestegg_packet * pkt,
   3406                       uint32_t const ** partition_offsets,
   3407                       uint8_t * num_partitions)
   3408 {
   3409  struct frame * f = pkt->frame;
   3410  unsigned char encrypted_bit;
   3411  unsigned char partitioned_bit;
   3412 
   3413  *partition_offsets = NULL;
   3414  *num_partitions = 0;
   3415 
   3416  if (!f->frame_encryption)
   3417    return -1;
   3418 
   3419  /* Should never have parsed blocks with both encryption and lacing */
   3420  assert(f->next == NULL);
   3421 
   3422  encrypted_bit = f->frame_encryption->signal_byte & ENCRYPTED_BIT_MASK;
   3423  partitioned_bit = f->frame_encryption->signal_byte & PARTITIONED_BIT_MASK;
   3424 
   3425  if (encrypted_bit != PACKET_ENCRYPTED || partitioned_bit != PACKET_PARTITIONED)
   3426    return -1;
   3427 
   3428  *num_partitions = f->frame_encryption->num_partitions;
   3429  *partition_offsets = f->frame_encryption->partition_offsets;
   3430  return 0;
   3431 }
   3432 
   3433 int
   3434 nestegg_has_cues(nestegg * ctx)
   3435 {
   3436  return ctx->segment.cues.cue_point.head ||
   3437    ne_find_seek_for_id(ctx->segment.seek_head.head, ID_CUES);
   3438 }
   3439 
   3440 static int ne_sniff(unsigned char const* buffer, size_t length,
   3441                         const char* doc_type)
   3442 {
   3443  nestegg_io io;
   3444  struct io_buffer userdata;
   3445 
   3446  userdata.buffer = buffer;
   3447  userdata.length = length;
   3448  userdata.offset = 0;
   3449 
   3450  io.read = ne_buffer_read;
   3451  io.seek = ne_buffer_seek;
   3452  io.tell = ne_buffer_tell;
   3453  io.userdata = &userdata;
   3454  return ne_match_doc_type(io, length, doc_type);
   3455 }
   3456 
   3457 int nestegg_sniff_webm(unsigned char const* buffer, size_t length)
   3458 {
   3459  return ne_sniff(buffer, length, DOCTYPE_WEBM);
   3460 }
   3461 
   3462 int nestegg_sniff_mkv(unsigned char const* buffer, size_t length)
   3463 {
   3464  return ne_sniff(buffer, length, DOCTYPE_MKV);
   3465 }
   3466 
   3467 /* Count frames in a Block/SimpleBlock from its lacing header, then skip the
   3468   remaining payload. Sets frames_out on success; returns 1 on success, <0 on error. */
   3469 static int
   3470 ne_read_block_lacing(nestegg * ctx, uint64_t block_size, uint64_t* frames_out)
   3471 {
   3472  int r;
   3473  int64_t timecode;
   3474  uint64_t track_number, length, flags, frames, header_bytes, remaining;
   3475  unsigned int lacing;
   3476 
   3477  if (block_size > LIMIT_BLOCK)
   3478    return -1;
   3479 
   3480  r = ne_read_vint(ctx->io, &track_number, &length);
   3481  if (r != 1)
   3482    return r;
   3483 
   3484  if (track_number == 0)
   3485    return -1;
   3486 
   3487  r = ne_read_int(ctx->io, &timecode, 2);
   3488  if (r != 1)
   3489    return r;
   3490 
   3491  r = ne_read_uint(ctx->io, &flags, 1);
   3492  if (r != 1)
   3493    return r;
   3494 
   3495  frames = 0;
   3496  lacing = (flags & BLOCK_FLAGS_LACING) >> 1;
   3497 
   3498  switch (lacing) {
   3499  case LACING_NONE:
   3500    frames = 1;
   3501    break;
   3502  case LACING_XIPH:
   3503  case LACING_FIXED:
   3504  case LACING_EBML:
   3505    r = ne_read_uint(ctx->io, &frames, 1);
   3506    if (r != 1)
   3507      return r;
   3508    frames += 1;
   3509    break;
   3510  default:
   3511    assert(0);
   3512    return -1;
   3513  }
   3514 
   3515  if (frames > 256)
   3516    return -1;
   3517 
   3518   /* Skip the remainder of the block payload. */
   3519  header_bytes = length + 2 + 1 + (lacing == LACING_NONE ? 0 : 1);
   3520  if (block_size < header_bytes)
   3521    return -1;
   3522  remaining = block_size - header_bytes;
   3523  if (remaining) {
   3524    r = ne_io_read_skip(ctx->io, remaining);
   3525    if (r != 1)
   3526      return r;
   3527  }
   3528 
   3529  *frames_out = frames;
   3530  return 1;
   3531 }
   3532 
   3533 /* Consume the payload of a SimpleBlock or BlockGroup:
   3534   - If block-like, count frames via lacing and add to frames_out.
   3535   - If not, skip the payload.
   3536   Always advances I/O to the end of the element.
   3537   Returns 1 on success, <0 on error. */
   3538 static int
   3539 ne_sum_block_or_group(nestegg * ctx, uint64_t id, uint64_t size, uint64_t * frames_out)
   3540 {
   3541  int r;
   3542 
   3543  if (id == ID_SIMPLE_BLOCK) {
   3544    uint64_t frames;
   3545    frames = 0;
   3546    r = ne_read_block_lacing(ctx, size, &frames);
   3547    if (r != 1)
   3548      return r;
   3549    *frames_out += frames;
   3550    return 1;
   3551  }
   3552 
   3553  if (id == ID_BLOCK_GROUP) {
   3554    int64_t group_end;
   3555    group_end = ne_io_tell(ctx->io) + (int64_t) size;
   3556    while (ne_io_tell(ctx->io) < group_end) {
   3557      uint64_t gid, gsize;
   3558      r = ne_read_element(ctx, &gid, &gsize);
   3559      if (r != 1)
   3560        return r;
   3561 
   3562      if (gid == ID_BLOCK) {
   3563        uint64_t frames;
   3564        frames = 0;
   3565        r = ne_read_block_lacing(ctx, gsize, &frames);
   3566        if (r != 1)
   3567          return r;
   3568        *frames_out += frames;
   3569      } else {
   3570        r = ne_io_read_skip(ctx->io, gsize);
   3571        if (r != 1)
   3572          return r;
   3573      }
   3574    }
   3575    return 1;
   3576  }
   3577 
   3578  /* Not a block-like element: skip its payload. */
   3579  r = ne_io_read_skip(ctx->io, size);
   3580  if (r != 1)
   3581    return r;
   3582 
   3583  return 1;
   3584 }
   3585 
   3586 /* Returns non-zero if 'size' equals the EBML unknown-size pattern for any VINT
   3587   length. Patterns (data bits all 1): 0x7F, 0x3FFF, 0x1FFFFF, 0x0FFFFFFF,
   3588   0x07FFFFFFFF, 0x03FFFFFFFFFF, 0x01FFFFFFFFFFFF, 0x00FFFFFFFFFFFFFF. */
   3589 static int
   3590 ne_size_is_unknown(uint64_t size)
   3591 {
   3592  int len;
   3593  for (len = 1; len <= 8; ++len) {
   3594    uint64_t mask;
   3595    if (len == 8)
   3596      mask = 0x00FFFFFFFFFFFFFFULL;  /* 56 data bits = all ones */
   3597    else
   3598      mask = (1ULL << (7 * len)) - 1ULL; /* 7 data bits per byte */
   3599    if (size == mask)
   3600      return 1;
   3601  }
   3602  return 0;
   3603 }
   3604 
   3605 /* Read ONE Cluster and return the sum of frames of ALL SimpleBlock/Block in it.
   3606   Returns 1 on success (Cluster found), 0 on clean EOS before any Cluster,
   3607   <0 on error. */
   3608 static int
   3609 ne_read_cluster_frames_count(nestegg * ctx, uint64_t * frames_out)
   3610 {
   3611  int r;
   3612  uint64_t id, size;
   3613  int64_t cluster_end;
   3614  uint64_t totalFrames;
   3615 
   3616  assert(ctx->ancestor == NULL);
   3617 
   3618  /* Find the next Cluster at the top level. */
   3619  for (;;) {
   3620    r = ne_read_element(ctx, &id, &size);
   3621    if (r == 0)
   3622      return 0; /* EOS before any Cluster */
   3623    if (r != 1)
   3624      return r;
   3625 
   3626    if (id != ID_CLUSTER) {
   3627      /* Not a Cluster: consume and keep scanning. */
   3628      r = ne_io_read_skip(ctx->io, size);
   3629      if (r != 1)
   3630        return r;
   3631      continue;
   3632    }
   3633 
   3634    totalFrames = 0;
   3635 
   3636    if (ne_size_is_unknown(size)) {
   3637      for (;;) {
   3638        uint64_t nid, nsize;
   3639 
   3640        r = ne_peek_element(ctx, &nid, &nsize);
   3641        if (r == 0)
   3642          break; /* EOS ends the unknown-sized Cluster */
   3643        if (r != 1)
   3644          return r;
   3645 
   3646        /* Stop at next top-level element without consuming it. */
   3647        if (nid == ID_EBML        ||
   3648            nid == ID_SEGMENT     ||
   3649            nid == ID_SEEK_HEAD   ||
   3650            nid == ID_INFO        ||
   3651            nid == ID_TRACKS      ||
   3652            nid == ID_CHAPTERS    ||
   3653            nid == ID_CLUSTER     ||
   3654            nid == ID_CUES        ||
   3655            nid == ID_ATTACHMENTS ||
   3656            nid == ID_TAGS) {
   3657          break;
   3658        }
   3659 
   3660        r = ne_read_element(ctx, &nid, &nsize);
   3661        if (r != 1)
   3662          return r;
   3663 
   3664        /* Sum frames for blocks; skip other children. */
   3665        r = ne_sum_block_or_group(ctx, nid, nsize, &totalFrames);
   3666        if (r != 1)
   3667          return r;
   3668      }
   3669 
   3670      *frames_out = totalFrames;
   3671      ctx->log(ctx, NESTEGG_LOG_DEBUG,
   3672               "ne_read_cluster_frames_count: totalFrames=%llu (unknown-sized Cluster)",
   3673               totalFrames);
   3674      return 1;
   3675    }
   3676 
   3677    /* Known-sized Cluster: read until cluster_end. */
   3678    cluster_end = ne_io_tell(ctx->io) + (int64_t) size;
   3679 
   3680    while (ne_io_tell(ctx->io) < cluster_end) {
   3681      uint64_t cid, csize;
   3682      r = ne_read_element(ctx, &cid, &csize);
   3683      if (r != 1)
   3684        return r;
   3685 
   3686      /* Sum frames for blocks; skip other children. */
   3687      r = ne_sum_block_or_group(ctx, cid, csize, &totalFrames);
   3688      if (r != 1)
   3689        return r;
   3690    }
   3691 
   3692    *frames_out = totalFrames;
   3693    ctx->log(ctx, NESTEGG_LOG_DEBUG,
   3694             "ne_read_cluster_frames_count: totalFrames=%llu", totalFrames);
   3695    return 1;
   3696  }
   3697 }
   3698 
   3699 int
   3700 nestegg_read_total_frames_count(nestegg * context, uint64_t * frames_out)
   3701 {
   3702  struct saved_state saved;
   3703  uint64_t totalFrames;
   3704  int r;
   3705 
   3706  if (!context || !frames_out)
   3707    return -1;
   3708 
   3709  ne_ctx_save(context, &saved);
   3710 
   3711  totalFrames = 0;
   3712  for (;;) {
   3713    uint64_t clusterFrames;
   3714    clusterFrames = 0;
   3715    r = ne_read_cluster_frames_count(context, &clusterFrames);
   3716    if (r == 0) {
   3717      /* EOS */
   3718      break;
   3719    }
   3720    if (r < 0) {
   3721      ne_ctx_restore(context, &saved);
   3722      return -1;
   3723    }
   3724    totalFrames += clusterFrames;
   3725  }
   3726 
   3727  ne_ctx_restore(context, &saved);
   3728 
   3729  *frames_out = totalFrames;
   3730  return 0;
   3731 }