1 /*
2  * Matroska demuxer
3  * Copyright (C) 2004 Aurelien Jacobs <aurel@gnuage.org>
4  * Based on the one written by Ronald Bultje for gstreamer
5  * and on demux_mkv.cpp from Moritz Bunkus.
6  *
7  * This file is part of MPlayer.
8  *
9  * MPlayer is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * MPlayer is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with MPlayer; if not, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23 
24 #include "config.h"
25 
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <ctype.h>
29 #include <inttypes.h>
30 
31 #include "stream/stream.h"
32 #include "demuxer.h"
33 #include "stheader.h"
34 #include "ebml.h"
35 #include "matroska.h"
36 #include "demux_real.h"
37 
38 #include "sub/ass_mp.h"
39 #include "mp_msg.h"
40 #include "help_mp.h"
41 
42 #include "sub/vobsub.h"
43 #include "sub/subreader.h"
44 #include "sub/sub.h"
45 
46 #include "libavutil/common.h"
47 
48 #ifdef CONFIG_QTX_CODECS
49 #include "loader/qtx/qtxsdk/components.h"
50 #endif
51 
52 #if CONFIG_ZLIB
53 #include <zlib.h>
54 #endif
55 
56 #include "libavutil/lzo.h"
57 #include "libavutil/intreadwrite.h"
58 #include "libavutil/avstring.h"
59 
60 static const unsigned char sipr_swaps[38][2] = {
61     {0,63},{1,22},{2,44},{3,90},{5,81},{7,31},{8,86},{9,58},{10,36},{12,68},
62     {13,39},{14,73},{15,53},{16,69},{17,57},{19,88},{20,34},{21,71},{24,46},
63     {25,94},{26,54},{28,75},{29,50},{32,70},{33,92},{35,74},{38,85},{40,56},
64     {42,87},{43,65},{45,59},{48,79},{49,93},{51,89},{55,95},{61,76},{67,83},
65     {77,80}
66 };
67 
68 // Map flavour to bytes per second
69 #define SIPR_FLAVORS 4
70 #define ATRC_FLAVORS 8
71 #define COOK_FLAVORS 34
72 static const int sipr_fl2bps[SIPR_FLAVORS] = { 813, 1062, 625, 2000 };
73 static const int atrc_fl2bps[ATRC_FLAVORS] = {
74     8269, 11714, 13092, 16538, 18260, 22050, 33075, 44100 };
75 static const int cook_fl2bps[COOK_FLAVORS] = {
76     1000, 1378, 2024, 2584, 4005, 5513, 8010, 4005, 750, 2498,
77     4048, 5513, 8010, 11973, 8010, 2584, 4005, 2067, 2584, 2584,
78     4005, 4005, 5513, 5513, 8010, 12059, 1550, 8010, 12059, 5513,
79     12016, 16408, 22911, 33506
80 };
81 
82 typedef struct {
83     uint32_t order, type, scope;
84     uint32_t comp_algo;
85     uint8_t *comp_settings;
86     size_t comp_settings_len;
87 } mkv_content_encoding_t;
88 
89 typedef struct mkv_track {
90     int tnum;
91     char *name;
92 
93     char *codec_id;
94     int ms_compat;
95     char *language;
96 
97     int type;
98 
99     uint32_t v_width, v_height, v_dwidth, v_dheight;
100     float v_frate;
101 
102     uint32_t a_formattag;
103     uint32_t a_channels, a_bps;
104     float a_sfreq;
105 
106     float default_duration;
107 
108     int default_track;
109 
110     void *private_data;
111     size_t private_size;
112 
113     /* stuff for realmedia */
114     int realmedia;
115     int64_t rv_kf_base;
116     int rv_kf_pts;
117     float rv_pts;               /* previous video timestamp */
118     float ra_pts;               /* previous audio timestamp */
119 
120     /** realaudio descrambling */
121     int sub_packet_size;        ///< sub packet size, per stream
122     int sub_packet_h;           ///< number of coded frames per block
123     int coded_framesize;        ///< coded frame size, per stream
124     int audiopk_size;           ///< audio packet size
125     unsigned char *audio_buf;   ///< place to store reordered audio data
126     float *audio_timestamp;     ///< timestamp for each audio packet
127     int sub_packet_cnt;         ///< number of subpacket already received
128     int audio_filepos;          ///< file position of first audio packet in block
129 
130     /* stuff for quicktime */
131     int fix_i_bps;
132     float qt_last_a_pts;
133 
134     int subtitle_type;
135 
136     /* The timecodes of video frames might have to be reordered if they're
137        in display order (the timecodes, not the frames themselves!). In this
138        case demux packets have to be cached with the help of these variables. */
139     int reorder_timecodes;
140     demux_packet_t **cached_dps;
141     int num_cached_dps, num_allocated_dps;
142     float max_pts;
143 
144     /* generic content encoding support */
145     mkv_content_encoding_t *encodings;
146     int num_encodings;
147 
148     /* For VobSubs and SSA/ASS */
149     sh_sub_t *sh_sub;
150 } mkv_track_t;
151 
152 typedef struct mkv_index {
153     int tnum;
154     uint64_t timecode, filepos;
155 } mkv_index_t;
156 
157 typedef struct mkv_demuxer {
158     off_t segment_start;
159 
160     float duration, last_pts;
161     uint64_t last_filepos;
162 
163     mkv_track_t **tracks;
164     int num_tracks;
165 
166     uint64_t tc_scale, cluster_tc, first_tc;
167     int has_first_tc;
168 
169     uint64_t cluster_size;
170     uint64_t blockgroup_size;
171 
172     mkv_index_t *indexes;
173     int num_indexes;
174 
175     off_t *parsed_cues;
176     int parsed_cues_num;
177     off_t *parsed_seekhead;
178     int parsed_seekhead_num;
179 
180     uint64_t *cluster_positions;
181     int num_cluster_pos;
182 
183     int64_t skip_to_timecode;
184     int v_skip_to_keyframe, a_skip_to_keyframe;
185 
186     int64_t stop_timecode;
187 
188     int last_aid;
189     int audio_tracks[MAX_A_STREAMS];
190 } mkv_demuxer_t;
191 
192 #define REALHEADER_SIZE    16
193 #define RVPROPERTIES_SIZE  34
194 #define RAPROPERTIES4_SIZE 56
195 #define RAPROPERTIES5_SIZE 70
196 
197 /**
198  * \brief ensures there is space for at least one additional element
199  * \param arrayp array to grow
200  * \param nelem current number of elements in array
201  * \param elsize size of one array element
202  */
grow_array(void * arrayp,int nelem,size_t elsize)203 static void av_noinline grow_array(void *arrayp, int nelem, size_t elsize)
204 {
205     void **array = arrayp;
206     void *oldp = *array;
207     if (nelem & 31)
208         return;
209     if (nelem > UINT_MAX / elsize - 32)
210         *array = NULL;
211     else
212         *array = realloc(*array, (nelem + 32) * elsize);
213     if (!*array)
214         free(oldp);
215 }
216 
demux_mkv_find_track_by_num(mkv_demuxer_t * d,int n,int type)217 static mkv_track_t *demux_mkv_find_track_by_num(mkv_demuxer_t *d, int n,
218                                                 int type)
219 {
220     int i, id;
221 
222     for (i = 0, id = 0; i < d->num_tracks; i++)
223         if (d->tracks[i] != NULL && d->tracks[i]->type == type)
224             if (id++ == n)
225                 return d->tracks[i];
226 
227     return NULL;
228 }
229 
add_cluster_position(mkv_demuxer_t * mkv_d,uint64_t position)230 static void add_cluster_position(mkv_demuxer_t *mkv_d, uint64_t position)
231 {
232     int i = mkv_d->num_cluster_pos;
233 
234     while (i--)
235         if (mkv_d->cluster_positions[i] == position)
236             return;
237 
238     grow_array(&mkv_d->cluster_positions, mkv_d->num_cluster_pos,
239                sizeof(uint64_t));
240     if (!mkv_d->cluster_positions) {
241         mkv_d->num_cluster_pos = 0;
242         return;
243     }
244     mkv_d->cluster_positions[mkv_d->num_cluster_pos++] = position;
245 }
246 
247 
248 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
aac_get_sample_rate_index(uint32_t sample_rate)249 static int aac_get_sample_rate_index(uint32_t sample_rate)
250 {
251     static const int srates[] = {
252         92017, 75132, 55426, 46009, 37566, 27713,
253         23004, 18783, 13856, 11502, 9391, 0
254     };
255     int i = 0;
256     while (sample_rate < srates[i])
257         i++;
258     return i;
259 }
260 
261 /** \brief Free cached demux packets
262  *
263  * Reordering the timecodes requires caching of demux packets. This function
264  * frees all these cached packets and the memory for the cached pointers
265  * itself.
266  *
267  * \param demuxer The demuxer for which the cache is to be freed.
268  */
free_cached_dps(demuxer_t * demuxer)269 static void free_cached_dps(demuxer_t *demuxer)
270 {
271     mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
272     mkv_track_t *track;
273     int i, k;
274 
275     for (k = 0; k < mkv_d->num_tracks; k++) {
276         track = mkv_d->tracks[k];
277         for (i = 0; i < track->num_cached_dps; i++)
278             free_demux_packet(track->cached_dps[i]);
279         free(track->cached_dps);
280         track->cached_dps = NULL;
281         track->num_cached_dps = 0;
282         track->num_allocated_dps = 0;
283         track->max_pts = 0;
284     }
285 }
286 
demux_mkv_decode(mkv_track_t * track,uint8_t * src,uint8_t ** dest,size_t * size,uint32_t type)287 static int demux_mkv_decode(mkv_track_t *track, uint8_t *src,
288                             uint8_t **dest, size_t *size, uint32_t type)
289 {
290     int i, result;
291     int modified = 0;
292 
293     *dest = src;
294     if (track->num_encodings <= 0)
295         return 0;
296 
297     for (i = 0; i < track->num_encodings; i++) {
298         if (!(track->encodings[i].scope & type))
299             continue;
300 
301 #if CONFIG_ZLIB
302         if (track->encodings[i].comp_algo == 0) {
303             /* zlib encoded track */
304             z_stream zstream;
305 
306             zstream.zalloc = (alloc_func) 0;
307             zstream.zfree = (free_func) 0;
308             zstream.opaque = (voidpf) 0;
309             if (inflateInit(&zstream) != Z_OK) {
310                 mp_msg(MSGT_DEMUX, MSGL_WARN,
311                        MSGTR_MPDEMUX_MKV_ZlibInitializationFailed);
312                 return modified;
313             }
314             zstream.next_in = (Bytef *) src;
315             zstream.avail_in = *size;
316 
317             modified = 1;
318             *dest = NULL;
319             zstream.avail_out = *size;
320             do {
321                 if (*size > SIZE_MAX - 4000 - AV_LZO_INPUT_PADDING)
322                     goto zlib_fail;
323 
324                 *size += 4000;
325                 *dest = realloc(*dest, *size + AV_LZO_INPUT_PADDING);
326                 if (!*dest)
327                     goto zlib_fail;
328                 zstream.next_out = (Bytef *) (*dest + zstream.total_out);
329                 result = inflate(&zstream, Z_NO_FLUSH);
330                 if (result != Z_OK && result != Z_STREAM_END) {
331 zlib_fail:
332                     mp_msg(MSGT_DEMUX, MSGL_WARN,
333                            MSGTR_MPDEMUX_MKV_ZlibDecompressionFailed);
334                     free(*dest);
335                     *dest = NULL;
336                     inflateEnd(&zstream);
337                     return modified;
338                 }
339                 zstream.avail_out += 4000;
340             } while (zstream.avail_out == 4000 && zstream.avail_in != 0
341                      && result != Z_STREAM_END);
342 
343             *size = zstream.total_out;
344             inflateEnd(&zstream);
345         }
346 #endif
347         if (track->encodings[i].comp_algo == 2) {
348             /* lzo encoded track */
349             int out_avail;
350             int dstlen = *size > SIZE_MAX/3 ? *size : *size * 3;
351 
352             *dest = NULL;
353             while (1) {
354                 // Max of both because we might decompress the input multiple
355                 // times. Makes no sense but is possible.
356                 int padding = FFMAX(AV_LZO_OUTPUT_PADDING, AV_LZO_INPUT_PADDING);
357                 int srclen = *size;
358                 if (dstlen > SIZE_MAX - padding)
359                     goto lzo_fail;
360                 *dest = realloc(*dest, dstlen + padding);
361                 if (!*dest)
362                     goto lzo_fail;
363                 out_avail = dstlen;
364                 result = av_lzo1x_decode(*dest, &out_avail, src, &srclen);
365                 if (result == 0)
366                     break;
367                 if (!(result & AV_LZO_OUTPUT_FULL)) {
368 lzo_fail:
369                     mp_msg(MSGT_DEMUX, MSGL_WARN,
370                            MSGTR_MPDEMUX_MKV_LzoDecompressionFailed);
371                     free(*dest);
372                     *dest = NULL;
373                     return modified;
374                 }
375                 mp_msg(MSGT_DEMUX, MSGL_DBG2,
376                        "[mkv] lzo decompression buffer too small.\n");
377                 if (dstlen > (SIZE_MAX - padding)/2)
378                     goto lzo_fail;
379                 dstlen *= 2;
380             }
381             *size = dstlen - out_avail;
382         }
383       else if (track->encodings[i].comp_algo == 3)
384         {
385           *dest = malloc (*size + track->encodings[i].comp_settings_len);
386           memcpy(*dest, track->encodings[i].comp_settings,
387                  track->encodings[i].comp_settings_len);
388           memcpy(*dest + track->encodings[i].comp_settings_len, src, *size);
389           *size += track->encodings[i].comp_settings_len;
390           modified = 1;
391         }
392     }
393 
394     return modified;
395 }
396 
397 
demux_mkv_read_info(demuxer_t * demuxer)398 static int demux_mkv_read_info(demuxer_t *demuxer)
399 {
400     mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
401     stream_t *s = demuxer->stream;
402     uint64_t length, l;
403     int il;
404     uint64_t tc_scale = 1000000;
405     double duration = 0.;
406 
407     length = ebml_read_length(s, NULL);
408     while (length > 0) {
409         switch (ebml_read_id(s, &il)) {
410         case MATROSKA_ID_TIMECODESCALE:
411         {
412             uint64_t num = ebml_read_uint(s, &l);
413             if (num == EBML_UINT_INVALID)
414                 return 1;
415             tc_scale = num;
416             mp_msg(MSGT_DEMUX, MSGL_V,
417                    "[mkv] | + timecode scale: %" PRIu64 "\n", tc_scale);
418             break;
419         }
420 
421         case MATROSKA_ID_DURATION:
422         {
423             double num = ebml_read_float(s, &l);
424             if (num == EBML_FLOAT_INVALID)
425                 return 1;
426             duration = num;
427             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + duration: %.3fs\n",
428                    duration * tc_scale / 1000000000.0);
429             break;
430         }
431 
432         default:
433             ebml_read_skip(s, &l);
434             break;
435         }
436         length -= l + il;
437     }
438     mkv_d->tc_scale = tc_scale;
439     mkv_d->duration = duration * tc_scale / 1000000000.0;
440     return 0;
441 }
442 
443 /**
444  * \brief free array of kv_content_encoding_t
445  * \param encodings pointer to array
446  * \param numencodings number of encodings in array
447  */
demux_mkv_free_encodings(mkv_content_encoding_t * encodings,int numencodings)448 static void demux_mkv_free_encodings(mkv_content_encoding_t *encodings,
449                                      int numencodings)
450 {
451     while (numencodings-- > 0)
452         free(encodings[numencodings].comp_settings);
453     free(encodings);
454 }
455 
demux_mkv_read_trackencodings(demuxer_t * demuxer,mkv_track_t * track)456 static int demux_mkv_read_trackencodings(demuxer_t *demuxer,
457                                          mkv_track_t *track)
458 {
459     stream_t *s = demuxer->stream;
460     mkv_content_encoding_t *ce, e;
461     uint64_t len, length, l;
462     int il, n;
463 
464     ce = malloc(sizeof(*ce));
465     n = 0;
466 
467     len = length = ebml_read_length(s, &il);
468     len += il;
469     while (length > 0) {
470         switch (ebml_read_id(s, &il)) {
471         case MATROSKA_ID_CONTENTENCODING:
472         {
473             uint64_t len;
474             int i;
475 
476             memset(&e, 0, sizeof(e));
477             e.scope = 1;
478 
479             len = ebml_read_length(s, &i);
480             l = len + i;
481 
482             while (len > 0) {
483                 uint64_t num, l;
484                 int il;
485 
486                 switch (ebml_read_id(s, &il)) {
487                 case MATROSKA_ID_CONTENTENCODINGORDER:
488                     num = ebml_read_uint(s, &l);
489                     if (num == EBML_UINT_INVALID)
490                         goto err_out;
491                     e.order = num;
492                     break;
493 
494                 case MATROSKA_ID_CONTENTENCODINGSCOPE:
495                     num = ebml_read_uint(s, &l);
496                     if (num == EBML_UINT_INVALID)
497                         goto err_out;
498                     e.scope = num;
499                     break;
500 
501                 case MATROSKA_ID_CONTENTENCODINGTYPE:
502                     num = ebml_read_uint(s, &l);
503                     if (num == EBML_UINT_INVALID)
504                         goto err_out;
505                     e.type = num;
506                     break;
507 
508                 case MATROSKA_ID_CONTENTCOMPRESSION:
509                 {
510                     uint64_t le;
511 
512                     le = ebml_read_length(s, &i);
513                     l = le + i;
514 
515                     while (le > 0) {
516                         uint64_t l;
517                         int il;
518 
519                         switch (ebml_read_id(s, &il)) {
520                         case MATROSKA_ID_CONTENTCOMPALGO:
521                             num = ebml_read_uint(s, &l);
522                             if (num == EBML_UINT_INVALID)
523                                 goto err_out;
524                             e.comp_algo = num;
525                             break;
526 
527                         case MATROSKA_ID_CONTENTCOMPSETTINGS:
528                             l = ebml_read_length(s, &i);
529                             if (l > SIZE_MAX)
530                                 goto err_out;
531                             e.comp_settings = malloc(l);
532                             stream_read(s, e.comp_settings, l);
533                             e.comp_settings_len = l;
534                             l += i;
535                             break;
536 
537                         default:
538                             ebml_read_skip(s, &l);
539                             break;
540                         }
541                         le -= l + il;
542                     }
543 
544                     if (e.type == 1) {
545                         mp_msg(MSGT_DEMUX, MSGL_WARN,
546                                MSGTR_MPDEMUX_MKV_TrackEncrypted,
547                                track->tnum);
548                     } else if (e.type != 0) {
549                         mp_msg(MSGT_DEMUX, MSGL_WARN,
550                                MSGTR_MPDEMUX_MKV_UnknownContentEncoding,
551                                track->tnum);
552                     }
553 
554                     if (e.comp_algo != 0 && e.comp_algo != 2 && e.comp_algo != 3) {
555                         mp_msg(MSGT_DEMUX, MSGL_WARN,
556                                MSGTR_MPDEMUX_MKV_UnknownCompression,
557                                track->tnum, e.comp_algo);
558                     }
559 #if !CONFIG_ZLIB
560                     else if (e.comp_algo == 0) {
561                         mp_msg(MSGT_DEMUX, MSGL_WARN,
562                                MSGTR_MPDEMUX_MKV_ZlibCompressionUnsupported,
563                                track->tnum);
564                     }
565 #endif
566 
567                     break;
568                 }
569 
570                 default:
571                     ebml_read_skip(s, &l);
572                     break;
573                 }
574                 len -= l + il;
575             }
576             for (i = 0; i < n; i++)
577                 if (e.order <= ce[i].order)
578                     break;
579             ce = realloc(ce, (n + 1) * sizeof(*ce));
580             memmove(ce + i + 1, ce + i, (n - i) * sizeof(*ce));
581             memcpy(ce + i, &e, sizeof(e));
582             n++;
583             break;
584         }
585 
586         default:
587             ebml_read_skip(s, &l);
588             break;
589         }
590 
591         length -= l + il;
592     }
593 
594     track->encodings = ce;
595     track->num_encodings = n;
596     return len;
597 
598 err_out:
599     demux_mkv_free_encodings(ce, n);
600     return 0;
601 }
602 
demux_mkv_read_trackaudio(demuxer_t * demuxer,mkv_track_t * track)603 static int demux_mkv_read_trackaudio(demuxer_t *demuxer, mkv_track_t *track)
604 {
605     stream_t *s = demuxer->stream;
606     uint64_t len, length, l;
607     int il;
608 
609     track->a_sfreq = 8000.0;
610     track->a_channels = 1;
611 
612     len = length = ebml_read_length(s, &il);
613     len += il;
614     while (length > 0) {
615         switch (ebml_read_id(s, &il)) {
616         case MATROSKA_ID_AUDIOSAMPLINGFREQ:
617         {
618             double num = ebml_read_float(s, &l);
619             if (num == EBML_FLOAT_INVALID)
620                 return 0;
621             track->a_sfreq = num;
622             mp_msg(MSGT_DEMUX, MSGL_V,
623                    "[mkv] |   + Sampling frequency: %f\n", track->a_sfreq);
624             break;
625         }
626 
627         case MATROSKA_ID_AUDIOBITDEPTH:
628         {
629             uint64_t num = ebml_read_uint(s, &l);
630             if (num == EBML_UINT_INVALID)
631                 return 0;
632             track->a_bps = num;
633             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |   + Bit depth: %u\n",
634                    track->a_bps);
635             break;
636         }
637 
638         case MATROSKA_ID_AUDIOCHANNELS:
639         {
640             uint64_t num = ebml_read_uint(s, &l);
641             if (num == EBML_UINT_INVALID)
642                 return 0;
643             track->a_channels = num;
644             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |   + Channels: %u\n",
645                    track->a_channels);
646             break;
647         }
648 
649         default:
650             ebml_read_skip(s, &l);
651             break;
652         }
653         length -= l + il;
654     }
655     return len;
656 }
657 
demux_mkv_read_trackvideo(demuxer_t * demuxer,mkv_track_t * track)658 static int demux_mkv_read_trackvideo(demuxer_t *demuxer, mkv_track_t *track)
659 {
660     stream_t *s = demuxer->stream;
661     uint64_t len, length, l;
662     int il;
663 
664     len = length = ebml_read_length(s, &il);
665     len += il;
666     while (length > 0) {
667         switch (ebml_read_id(s, &il)) {
668         case MATROSKA_ID_VIDEOFRAMERATE:
669         {
670             double num = ebml_read_float(s, &l);
671             if (num == EBML_FLOAT_INVALID)
672                 return 0;
673             track->v_frate = num;
674             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |   + Frame rate: %f\n",
675                    track->v_frate);
676             if (track->v_frate > 0)
677                 track->default_duration = 1 / track->v_frate;
678             break;
679         }
680 
681         case MATROSKA_ID_VIDEODISPLAYWIDTH:
682         {
683             uint64_t num = ebml_read_uint(s, &l);
684             if (num == EBML_UINT_INVALID)
685                 return 0;
686             track->v_dwidth = num;
687             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |   + Display width: %u\n",
688                    track->v_dwidth);
689             break;
690         }
691 
692         case MATROSKA_ID_VIDEODISPLAYHEIGHT:
693         {
694             uint64_t num = ebml_read_uint(s, &l);
695             if (num == EBML_UINT_INVALID)
696                 return 0;
697             track->v_dheight = num;
698             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |   + Display height: %u\n",
699                    track->v_dheight);
700             break;
701         }
702 
703         case MATROSKA_ID_VIDEOPIXELWIDTH:
704         {
705             uint64_t num = ebml_read_uint(s, &l);
706             if (num == EBML_UINT_INVALID)
707                 return 0;
708             track->v_width = num;
709             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |   + Pixel width: %u\n",
710                    track->v_width);
711             break;
712         }
713 
714         case MATROSKA_ID_VIDEOPIXELHEIGHT:
715         {
716             uint64_t num = ebml_read_uint(s, &l);
717             if (num == EBML_UINT_INVALID)
718                 return 0;
719             track->v_height = num;
720             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |   + Pixel height: %u\n",
721                    track->v_height);
722             break;
723         }
724 
725         default:
726             ebml_read_skip(s, &l);
727             break;
728         }
729         length -= l + il;
730     }
731     return len;
732 }
733 
734 /**
735  * \brief free any data associated with given track
736  * \param track track of which to free data
737  */
demux_mkv_free_trackentry(mkv_track_t * track)738 static void demux_mkv_free_trackentry(mkv_track_t *track)
739 {
740     free(track->name);
741     free(track->codec_id);
742     free(track->language);
743     free(track->private_data);
744     free(track->audio_buf);
745     free(track->audio_timestamp);
746     demux_mkv_free_encodings(track->encodings, track->num_encodings);
747     free(track);
748 }
749 
demux_mkv_read_trackentry(demuxer_t * demuxer)750 static int demux_mkv_read_trackentry(demuxer_t *demuxer)
751 {
752     mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
753     stream_t *s = demuxer->stream;
754     mkv_track_t *track;
755     uint64_t len, length, l;
756     int il;
757 
758     track = calloc(1, sizeof(*track));
759     /* set default values */
760     track->default_track = 1;
761     track->name = 0;
762     track->language = strdup("eng");
763 
764     len = length = ebml_read_length(s, &il);
765     len += il;
766     while (length > 0) {
767         switch (ebml_read_id(s, &il)) {
768         case MATROSKA_ID_TRACKNUMBER:
769         {
770             uint64_t num = ebml_read_uint(s, &l);
771             if (num == EBML_UINT_INVALID)
772                 goto err_out;
773             track->tnum = num;
774             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |  + Track number: %u\n",
775                    track->tnum);
776             break;
777         }
778 
779         case MATROSKA_ID_TRACKNAME:
780             track->name = ebml_read_utf8(s, &l);
781             if (track->name == NULL)
782                 goto err_out;
783             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |  + Name: %s\n",
784                    track->name);
785             break;
786 
787         case MATROSKA_ID_TRACKTYPE:
788         {
789             uint64_t num = ebml_read_uint(s, &l);
790             if (num == EBML_UINT_INVALID)
791                 goto err_out;
792             track->type = num;
793             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |  + Track type: ");
794             switch (track->type) {
795             case MATROSKA_TRACK_AUDIO:
796                 mp_msg(MSGT_DEMUX, MSGL_V, "Audio\n");
797                 break;
798             case MATROSKA_TRACK_VIDEO:
799                 mp_msg(MSGT_DEMUX, MSGL_V, "Video\n");
800                 break;
801             case MATROSKA_TRACK_SUBTITLE:
802                 mp_msg(MSGT_DEMUX, MSGL_V, "Subtitle\n");
803                 break;
804             default:
805                 mp_msg(MSGT_DEMUX, MSGL_V, "unknown\n");
806                 break;
807             }
808             break;
809         }
810 
811         case MATROSKA_ID_TRACKAUDIO:
812             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |  + Audio track\n");
813             l = demux_mkv_read_trackaudio(demuxer, track);
814             if (l == 0)
815                 goto err_out;
816             break;
817 
818         case MATROSKA_ID_TRACKVIDEO:
819             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |  + Video track\n");
820             l = demux_mkv_read_trackvideo(demuxer, track);
821             if (l == 0)
822                 goto err_out;
823             break;
824 
825         case MATROSKA_ID_CODECID:
826             track->codec_id = ebml_read_ascii(s, &l);
827             if (track->codec_id == NULL)
828                 goto err_out;
829             if (!strcmp(track->codec_id, MKV_V_MSCOMP)
830                 || !strcmp(track->codec_id, MKV_A_ACM))
831                 track->ms_compat = 1;
832             else if (!strcmp(track->codec_id, MKV_S_VOBSUB))
833                 track->subtitle_type = MATROSKA_SUBTYPE_VOBSUB;
834             else if (!strcmp(track->codec_id, MKV_S_TEXTSSA)
835                      || !strcmp(track->codec_id, MKV_S_TEXTASS)
836                      || !strcmp(track->codec_id, MKV_S_SSA)
837                      || !strcmp(track->codec_id, MKV_S_ASS)) {
838                 track->subtitle_type = MATROSKA_SUBTYPE_SSA;
839             } else if (!strcmp(track->codec_id, MKV_S_TEXTASCII))
840                 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
841             if (!strcmp(track->codec_id, MKV_S_TEXTUTF8)) {
842                 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
843             }
844             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |  + Codec ID: %s\n",
845                    track->codec_id);
846             break;
847 
848         case MATROSKA_ID_CODECPRIVATE:
849         {
850             int x;
851             uint64_t num = ebml_read_length(s, &x);
852             // audit: cheap guard against overflows later..
853             if (num > SIZE_MAX - 1000)
854                 goto err_out;
855             l = x + num;
856             track->private_data = malloc(num + AV_LZO_INPUT_PADDING);
857             if (stream_read(s, track->private_data, num) != (int) num)
858                 goto err_out;
859             track->private_size = num;
860             mp_msg(MSGT_DEMUX, MSGL_V,
861                    "[mkv] |  + CodecPrivate, length " "%zu\n",
862                    track->private_size);
863             break;
864         }
865 
866         case MATROSKA_ID_TRACKLANGUAGE:
867             free(track->language);
868             track->language = ebml_read_utf8(s, &l);
869             if (track->language == NULL)
870                 goto err_out;
871             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |  + Language: %s\n",
872                    track->language);
873             break;
874 
875         case MATROSKA_ID_TRACKFLAGDEFAULT:
876         {
877             uint64_t num = ebml_read_uint(s, &l);
878             if (num == EBML_UINT_INVALID)
879                 goto err_out;
880             track->default_track = num;
881             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |  + Default flag: %u\n",
882                    track->default_track);
883             break;
884         }
885 
886         case MATROSKA_ID_TRACKDEFAULTDURATION:
887         {
888             uint64_t num = ebml_read_uint(s, &l);
889             if (num == EBML_UINT_INVALID)
890                 goto err_out;
891             if (num == 0)
892                 mp_msg(MSGT_DEMUX, MSGL_V,
893                        "[mkv] |  + Default duration: 0");
894             else {
895                 track->v_frate = 1000000000.0 / num;
896                 track->default_duration = num / 1000000000.0;
897                 mp_msg(MSGT_DEMUX, MSGL_V,
898                        "[mkv] |  + Default duration: "
899                        "%.3fms ( = %.3f fps)\n", num / 1000000.0,
900                        track->v_frate);
901             }
902             break;
903         }
904 
905         case MATROSKA_ID_TRACKENCODINGS:
906             l = demux_mkv_read_trackencodings(demuxer, track);
907             if (l == 0)
908                 goto err_out;
909             break;
910 
911         default:
912             ebml_read_skip(s, &l);
913             break;
914         }
915         length -= l + il;
916     }
917 
918     mkv_d->tracks[mkv_d->num_tracks++] = track;
919     return len;
920 
921 err_out:
922     demux_mkv_free_trackentry(track);
923     return 0;
924 }
925 
demux_mkv_read_tracks(demuxer_t * demuxer)926 static int demux_mkv_read_tracks(demuxer_t *demuxer)
927 {
928     mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
929     stream_t *s = demuxer->stream;
930     uint64_t length, l;
931     int il;
932 
933     mkv_d->tracks = malloc(sizeof(*mkv_d->tracks));
934     mkv_d->num_tracks = 0;
935 
936     length = ebml_read_length(s, NULL);
937     while (length > 0) {
938         switch (ebml_read_id(s, &il)) {
939         case MATROSKA_ID_TRACKENTRY:
940             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + a track...\n");
941             mkv_d->tracks = realloc(mkv_d->tracks, (mkv_d->num_tracks + 1)
942                                     * sizeof(*mkv_d->tracks));
943             l = demux_mkv_read_trackentry(demuxer);
944             if (l == 0)
945                 return 1;
946             break;
947 
948         default:
949             ebml_read_skip(s, &l);
950             break;
951         }
952         length -= l + il;
953     }
954     return 0;
955 }
956 
demux_mkv_read_cues(demuxer_t * demuxer)957 static int demux_mkv_read_cues(demuxer_t *demuxer)
958 {
959     mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
960     stream_t *s = demuxer->stream;
961     uint64_t length, l, time, track, pos;
962     off_t off;
963     int i, il;
964 
965     if (index_mode == 0) {
966         ebml_read_skip(s, NULL);
967         return 0;
968     }
969     off = stream_tell(s);
970     for (i = 0; i < mkv_d->parsed_cues_num; i++)
971         if (mkv_d->parsed_cues[i] == off) {
972             ebml_read_skip(s, NULL);
973             return 0;
974         }
975     mkv_d->parsed_cues = realloc(mkv_d->parsed_cues,
976                                  (mkv_d->parsed_cues_num + 1) * sizeof(off_t));
977     mkv_d->parsed_cues[mkv_d->parsed_cues_num++] = off;
978 
979     mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing cues ] -----------\n");
980     length = ebml_read_length(s, NULL);
981 
982     while (length > 0) {
983         time = track = pos = EBML_UINT_INVALID;
984 
985         switch (ebml_read_id(s, &il)) {
986         case MATROSKA_ID_POINTENTRY:
987         {
988             uint64_t len;
989 
990             len = ebml_read_length(s, &i);
991             l = len + i;
992 
993             while (len > 0) {
994                 uint64_t l;
995                 int il;
996 
997                 switch (ebml_read_id(s, &il)) {
998                 case MATROSKA_ID_CUETIME:
999                     time = ebml_read_uint(s, &l);
1000                     break;
1001 
1002                 case MATROSKA_ID_CUETRACKPOSITION:
1003                 {
1004                     uint64_t le;
1005 
1006                     le = ebml_read_length(s, &i);
1007                     l = le + i;
1008 
1009                     while (le > 0) {
1010                         uint64_t l;
1011                         int il;
1012 
1013                         switch (ebml_read_id(s, &il)) {
1014                         case MATROSKA_ID_CUETRACK:
1015                             track = ebml_read_uint(s, &l);
1016                             break;
1017 
1018                         case MATROSKA_ID_CUECLUSTERPOSITION:
1019                             pos = ebml_read_uint(s, &l);
1020                             break;
1021 
1022                         default:
1023                             ebml_read_skip(s, &l);
1024                             break;
1025                         }
1026                         le -= l + il;
1027                     }
1028                     break;
1029                 }
1030 
1031                 default:
1032                     ebml_read_skip(s, &l);
1033                     break;
1034                 }
1035                 len -= l + il;
1036             }
1037             break;
1038         }
1039 
1040         default:
1041             ebml_read_skip(s, &l);
1042             break;
1043         }
1044 
1045         length -= l + il;
1046 
1047         if (time != EBML_UINT_INVALID && track != EBML_UINT_INVALID
1048             && pos != EBML_UINT_INVALID) {
1049             grow_array(&mkv_d->indexes, mkv_d->num_indexes,
1050                        sizeof(mkv_index_t));
1051             if (!mkv_d->indexes) {
1052                 mkv_d->num_indexes = 0;
1053                 break;
1054             }
1055             mkv_d->indexes[mkv_d->num_indexes].tnum = track;
1056             mkv_d->indexes[mkv_d->num_indexes].timecode = time;
1057             mkv_d->indexes[mkv_d->num_indexes].filepos = mkv_d->segment_start
1058                                                          + pos;
1059             mp_msg(MSGT_DEMUX, MSGL_DBG2,
1060                    "[mkv] |+ found cue point " "for track %" PRIu64
1061                    ": timecode %" PRIu64 ", filepos: %" PRIu64 "\n", track,
1062                    time, mkv_d->segment_start + pos);
1063             mkv_d->num_indexes++;
1064         }
1065     }
1066 
1067     mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing cues ] -----------\n");
1068     return 0;
1069 }
1070 
demux_mkv_read_chapters(demuxer_t * demuxer)1071 static int demux_mkv_read_chapters(demuxer_t *demuxer)
1072 {
1073     stream_t *s = demuxer->stream;
1074     uint64_t length, l;
1075     int il;
1076 
1077     if (demuxer->chapters) {
1078         ebml_read_skip(s, NULL);
1079         return 0;
1080     }
1081 
1082     mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing chapters ] ---------\n");
1083     length = ebml_read_length(s, NULL);
1084 
1085     while (length > 0) {
1086         switch (ebml_read_id(s, &il)) {
1087         case MATROSKA_ID_EDITIONENTRY:
1088         {
1089             uint64_t len;
1090             int i;
1091 
1092             len = ebml_read_length(s, &i);
1093             l = len + i;
1094 
1095             while (len > 0) {
1096                 uint64_t l;
1097                 int il;
1098 
1099                 switch (ebml_read_id(s, &il)) {
1100                 case MATROSKA_ID_CHAPTERATOM:
1101                 {
1102                     uint64_t len, start = 0, end = 0;
1103                     char *name = 0;
1104                     int i;
1105                     int cid;
1106 
1107                     len = ebml_read_length(s, &i);
1108                     l = len + i;
1109 
1110                     while (len > 0) {
1111                         uint64_t l;
1112                         int il;
1113 
1114                         switch (ebml_read_id(s, &il)) {
1115                         case MATROSKA_ID_CHAPTERTIMESTART:
1116                             start = ebml_read_uint(s, &l) / 1000000;
1117                             break;
1118 
1119                         case MATROSKA_ID_CHAPTERTIMEEND:
1120                             end = ebml_read_uint(s, &l) / 1000000;
1121                             break;
1122 
1123                         case MATROSKA_ID_CHAPTERDISPLAY:
1124                         {
1125                             uint64_t len;
1126                             int i;
1127 
1128                             len = ebml_read_length(s, &i);
1129                             l = len + i;
1130                             while (len > 0) {
1131                                 uint64_t l;
1132                                 int il;
1133 
1134                                 switch (ebml_read_id(s, &il)) {
1135                                 case MATROSKA_ID_CHAPSTRING:
1136                                     free(name);
1137                                     name = ebml_read_utf8(s, &l);
1138                                     break;
1139                                 default:
1140                                     ebml_read_skip(s, &l);
1141                                     break;
1142                                 }
1143                                 len -= l + il;
1144                             }
1145                         }
1146                         break;
1147 
1148                         default:
1149                             ebml_read_skip(s, &l);
1150                             break;
1151                         }
1152                         len -= l + il;
1153                     }
1154 
1155                     if (!name)
1156                         name = strdup("(unnamed)");
1157 
1158                     cid = demuxer_add_chapter(demuxer, name, start, end);
1159 
1160                     mp_msg(MSGT_DEMUX, MSGL_V,
1161                            "[mkv] Chapter %u from %02d:%02d:%02d."
1162                            "%03d to %02d:%02d:%02d.%03d, %s\n", cid,
1163                            (int) (start / 60 / 60 / 1000),
1164                            (int) ((start / 60 / 1000) % 60),
1165                            (int) ((start / 1000) % 60),
1166                            (int) (start % 1000),
1167                            (int) (end / 60 / 60 / 1000),
1168                            (int) ((end / 60 / 1000) % 60),
1169                            (int) ((end / 1000) % 60),
1170                            (int) (end % 1000), name);
1171 
1172                     free(name);
1173                     break;
1174                 }
1175 
1176                 default:
1177                     ebml_read_skip(s, &l);
1178                     break;
1179                 }
1180                 len -= l + il;
1181             }
1182             break;
1183         }
1184 
1185         default:
1186             ebml_read_skip(s, &l);
1187             break;
1188         }
1189 
1190         length -= l + il;
1191     }
1192 
1193     mp_msg(MSGT_DEMUX, MSGL_V,
1194            "[mkv] \\---- [ parsing chapters ] ---------\n");
1195     return 0;
1196 }
1197 
demux_mkv_read_tags(demuxer_t * demuxer)1198 static int demux_mkv_read_tags(demuxer_t *demuxer)
1199 {
1200     ebml_read_skip(demuxer->stream, NULL);
1201     return 0;
1202 }
1203 
demux_mkv_read_attachments(demuxer_t * demuxer)1204 static int demux_mkv_read_attachments(demuxer_t *demuxer)
1205 {
1206     stream_t *s = demuxer->stream;
1207     uint64_t length, l;
1208     int il;
1209 
1210     mp_msg(MSGT_DEMUX, MSGL_V,
1211            "[mkv] /---- [ parsing attachments ] ---------\n");
1212     length = ebml_read_length(s, NULL);
1213 
1214     while (length > 0) {
1215         switch (ebml_read_id(s, &il)) {
1216         case MATROSKA_ID_ATTACHEDFILE:
1217         {
1218             uint64_t len;
1219             int i;
1220             char *name = NULL;
1221             char *mime = NULL;
1222             char *data = NULL;
1223             int data_size = 0;
1224 
1225             len = ebml_read_length(s, &i);
1226             l = len + i;
1227 
1228             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + an attachment...\n");
1229 
1230             while (len > 0) {
1231                 uint64_t l;
1232                 int il;
1233 
1234                 switch (ebml_read_id(s, &il)) {
1235                 case MATROSKA_ID_FILENAME:
1236                     free(name);
1237                     name = ebml_read_utf8(s, &l);
1238                     if (name == NULL) {
1239                         free(mime);
1240                         free(data);
1241                         return 0;
1242                     }
1243                     mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |  + FileName: %s\n",
1244                            name);
1245                     break;
1246 
1247                 case MATROSKA_ID_FILEMIMETYPE:
1248                     free(mime);
1249                     mime = ebml_read_ascii(s, &l);
1250                     if (mime == NULL) {
1251                         free(name);
1252                         free(data);
1253                         return 0;
1254                     }
1255                     mp_msg(MSGT_DEMUX, MSGL_V,
1256                            "[mkv] |  + FileMimeType: %s\n", mime);
1257                     break;
1258 
1259                 case MATROSKA_ID_FILEDATA:
1260                 {
1261                     int x;
1262                     uint64_t num = ebml_read_length(s, &x);
1263                     l = x + num;
1264                     free(data);
1265                     if (num > SIZE_MAX) {
1266                         free(name);
1267                         free(mime);
1268                         return 0;
1269                     }
1270                     data = malloc(num);
1271                     if (!data || stream_read(s, data, num) != (int) num) {
1272                         free(name);
1273                         free(mime);
1274                         free(data);
1275                         return 0;
1276                     }
1277                     data_size = num;
1278                     mp_msg(MSGT_DEMUX, MSGL_V,
1279                            "[mkv] |  + FileData, length " "%u\n",
1280                            data_size);
1281                     break;
1282                 }
1283 
1284                 default:
1285                     ebml_read_skip(s, &l);
1286                     break;
1287                 }
1288                 len -= l + il;
1289             }
1290 
1291             demuxer_add_attachment(demuxer, name, mime ? mime : "application/octet-stream", data, data_size);
1292             mp_msg(MSGT_DEMUX, MSGL_V,
1293                    "[mkv] Attachment: %s, %s, %u bytes\n", name, mime,
1294                    data_size);
1295             free(name);
1296             free(mime);
1297             free(data);
1298             break;
1299         }
1300 
1301         default:
1302             ebml_read_skip(s, &l);
1303             break;
1304         }
1305         length -= l + il;
1306     }
1307 
1308     mp_msg(MSGT_DEMUX, MSGL_V,
1309            "[mkv] \\---- [ parsing attachments ] ---------\n");
1310     return 0;
1311 }
1312 
demux_mkv_read_seekhead(demuxer_t * demuxer)1313 static int demux_mkv_read_seekhead(demuxer_t *demuxer)
1314 {
1315     mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1316     stream_t *s = demuxer->stream;
1317     uint64_t length, l, seek_pos, saved_pos, num;
1318     uint32_t seek_id;
1319     int i, il, res = 0;
1320     off_t off;
1321 
1322     off = stream_tell(s);
1323     for (i = 0; i < mkv_d->parsed_seekhead_num; i++)
1324         if (mkv_d->parsed_seekhead[i] == off) {
1325             ebml_read_skip(s, NULL);
1326             return 0;
1327         }
1328     if (mkv_d->parsed_seekhead_num >= INT_MAX ||
1329         mkv_d->parsed_seekhead_num > SIZE_MAX/sizeof(off_t))
1330         return 0;
1331     mkv_d->parsed_seekhead = realloc(mkv_d->parsed_seekhead,
1332                                      (mkv_d->parsed_seekhead_num + 1)
1333                                      * sizeof(off_t));
1334     mkv_d->parsed_seekhead[mkv_d->parsed_seekhead_num++] = off;
1335 
1336     mp_msg(MSGT_DEMUX, MSGL_V,
1337            "[mkv] /---- [ parsing seek head ] ---------\n");
1338     length = ebml_read_length(s, NULL);
1339     /* off now holds the position of the next element after the seek head. */
1340     off = stream_tell(s) + length;
1341     while (length > 0 && !res) {
1342 
1343         seek_id = 0;
1344         seek_pos = EBML_UINT_INVALID;
1345 
1346         switch (ebml_read_id(s, &il)) {
1347         case MATROSKA_ID_SEEKENTRY:
1348         {
1349             uint64_t len;
1350 
1351             len = ebml_read_length(s, &i);
1352             l = len + i;
1353 
1354             while (len > 0) {
1355                 uint64_t l;
1356                 int il;
1357 
1358                 switch (ebml_read_id(s, &il)) {
1359                 case MATROSKA_ID_SEEKID:
1360                     num = ebml_read_uint(s, &l);
1361                     if (num != EBML_UINT_INVALID)
1362                         seek_id = num;
1363                     break;
1364 
1365                 case MATROSKA_ID_SEEKPOSITION:
1366                     seek_pos = ebml_read_uint(s, &l);
1367                     break;
1368 
1369                 default:
1370                     ebml_read_skip(s, &l);
1371                     break;
1372                 }
1373                 len -= l + il;
1374             }
1375 
1376             break;
1377         }
1378 
1379         default:
1380             ebml_read_skip(s, &l);
1381             break;
1382         }
1383         length -= l + il;
1384 
1385         if (seek_id == 0 || seek_id == MATROSKA_ID_CLUSTER
1386             || seek_pos == EBML_UINT_INVALID
1387             || ((mkv_d->segment_start + seek_pos) >=
1388                 (uint64_t) demuxer->movi_end))
1389             continue;
1390 
1391         saved_pos = stream_tell(s);
1392         if (!stream_seek(s, mkv_d->segment_start + seek_pos))
1393             res = 1;
1394         else {
1395             if (ebml_read_id(s, &il) != seek_id)
1396                 res = 1;
1397             else
1398                 switch (seek_id) {
1399                 case MATROSKA_ID_CUES:
1400                     if (demux_mkv_read_cues(demuxer))
1401                         res = 1;
1402                     break;
1403 
1404                 case MATROSKA_ID_TAGS:
1405                     if (demux_mkv_read_tags(demuxer))
1406                         res = 1;
1407                     break;
1408 
1409                 case MATROSKA_ID_SEEKHEAD:
1410                     if (demux_mkv_read_seekhead(demuxer))
1411                         res = 1;
1412                     break;
1413 
1414                 case MATROSKA_ID_CHAPTERS:
1415                     if (demux_mkv_read_chapters(demuxer))
1416                         res = 1;
1417                     break;
1418                 }
1419         }
1420 
1421         stream_seek(s, saved_pos);
1422     }
1423     if (res) {
1424         /* If there was an error then try to skip this seek head. */
1425         if (stream_seek(s, off))
1426             res = 0;
1427     } else if (length > 0)
1428         stream_seek(s, stream_tell(s) + length);
1429     mp_msg(MSGT_DEMUX, MSGL_V,
1430            "[mkv] \\---- [ parsing seek head ] ---------\n");
1431     return res;
1432 }
1433 
1434 static int demux_mkv_open_video(demuxer_t *demuxer, mkv_track_t *track,
1435                                 int vid);
1436 static int demux_mkv_open_audio(demuxer_t *demuxer, mkv_track_t *track,
1437                                 int aid);
1438 static int demux_mkv_open_sub(demuxer_t *demuxer, mkv_track_t *track,
1439                               int sid);
1440 
display_create_tracks(demuxer_t * demuxer)1441 static void display_create_tracks(demuxer_t *demuxer)
1442 {
1443     mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1444     int i, vid = 0, aid = 0, sid = 0;
1445 
1446     for (i = 0; i < mkv_d->num_tracks; i++) {
1447         char *type = "unknown", str[32];
1448         *str = '\0';
1449         switch (mkv_d->tracks[i]->type) {
1450         case MATROSKA_TRACK_VIDEO:
1451             type = "video";
1452             demux_mkv_open_video(demuxer, mkv_d->tracks[i], vid);
1453             if (mkv_d->tracks[i]->name)
1454                 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VID_%d_NAME=%s\n", vid,
1455                        mkv_d->tracks[i]->name);
1456             sprintf(str, "-vid %u", vid++);
1457             break;
1458         case MATROSKA_TRACK_AUDIO:
1459             type = "audio";
1460             demux_mkv_open_audio(demuxer, mkv_d->tracks[i], aid);
1461             if (mkv_d->tracks[i]->name)
1462                 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_NAME=%s\n", aid,
1463                        mkv_d->tracks[i]->name);
1464             sprintf(str, "-aid %u, -alang %.5s", aid++,
1465                     mkv_d->tracks[i]->language);
1466             break;
1467         case MATROSKA_TRACK_SUBTITLE:
1468             type = "subtitles";
1469             demux_mkv_open_sub(demuxer, mkv_d->tracks[i], sid);
1470             if (mkv_d->tracks[i]->name)
1471                 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_NAME=%s\n", sid,
1472                        mkv_d->tracks[i]->name);
1473             mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_LANG=%s\n", sid,
1474                    mkv_d->tracks[i]->language);
1475             sprintf(str, "-sid %u, -slang %.5s", sid++,
1476                     mkv_d->tracks[i]->language);
1477             break;
1478         }
1479         if (mkv_d->tracks[i]->name)
1480             mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_TrackIDName,
1481                    mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id,
1482                    mkv_d->tracks[i]->name, str);
1483         else
1484             mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_TrackID,
1485                    mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id,
1486                    str);
1487     }
1488 }
1489 
1490 typedef struct {
1491     char *id;
1492     int fourcc;
1493     int extradata;
1494 } videocodec_info_t;
1495 
1496 static const videocodec_info_t vinfo[] = {
1497     {MKV_V_HEVC,      mmioFOURCC('h', 'e', 'v', '1'), 1},
1498     {MKV_V_MPEG1,     mmioFOURCC('m', 'p', 'g', '1'), 0},
1499     {MKV_V_MPEG2,     mmioFOURCC('m', 'p', 'g', '2'), 0},
1500     {MKV_V_MPEG4_SP,  mmioFOURCC('m', 'p', '4', 'v'), 1},
1501     {MKV_V_MPEG4_ASP, mmioFOURCC('m', 'p', '4', 'v'), 1},
1502     {MKV_V_MPEG4_AP,  mmioFOURCC('m', 'p', '4', 'v'), 1},
1503     {MKV_V_MPEG4_AVC, mmioFOURCC('a', 'v', 'c', '1'), 1},
1504     {MKV_V_THEORA,    mmioFOURCC('t', 'h', 'e', 'o'), 1},
1505     {MKV_V_VP8,       mmioFOURCC('V', 'P', '8', '0'), 0},
1506     {MKV_V_VP9,       mmioFOURCC('V', 'P', '9', '0'), 0},
1507     {NULL, 0, 0}
1508 };
1509 
demux_mkv_open_video(demuxer_t * demuxer,mkv_track_t * track,int vid)1510 static int demux_mkv_open_video(demuxer_t *demuxer, mkv_track_t *track,
1511                                 int vid)
1512 {
1513     BITMAPINFOHEADER *bih;
1514     void *ImageDesc = NULL;
1515     sh_video_t *sh_v;
1516 
1517     if (track->ms_compat) {     /* MS compatibility mode */
1518         BITMAPINFOHEADER *src;
1519 
1520         if (track->private_data == NULL
1521             || track->private_size >= INT_MAX - 1000
1522             || track->private_size < sizeof(*bih))
1523             return 1;
1524 
1525         src = (BITMAPINFOHEADER *) track->private_data;
1526         bih = calloc(1, track->private_size);
1527         bih->biSize = le2me_32(src->biSize);
1528         bih->biWidth = le2me_32(src->biWidth);
1529         bih->biHeight = le2me_32(src->biHeight);
1530         bih->biPlanes = le2me_16(src->biPlanes);
1531         bih->biBitCount = le2me_16(src->biBitCount);
1532         bih->biCompression = le2me_32(src->biCompression);
1533         bih->biSizeImage = le2me_32(src->biSizeImage);
1534         bih->biXPelsPerMeter = le2me_32(src->biXPelsPerMeter);
1535         bih->biYPelsPerMeter = le2me_32(src->biYPelsPerMeter);
1536         bih->biClrUsed = le2me_32(src->biClrUsed);
1537         bih->biClrImportant = le2me_32(src->biClrImportant);
1538         memcpy(bih + 1,
1539                src + 1,
1540                track->private_size - sizeof(*bih));
1541 
1542         if (track->v_width == 0)
1543             track->v_width = bih->biWidth;
1544         if (track->v_height == 0)
1545             track->v_height = bih->biHeight;
1546     } else {
1547         bih = calloc(1, sizeof(*bih));
1548         bih->biSize = sizeof(*bih);
1549         bih->biWidth = track->v_width;
1550         bih->biHeight = track->v_height;
1551         bih->biBitCount = 24;
1552         bih->biSizeImage = bih->biWidth * bih->biHeight * bih->biBitCount / 8;
1553 
1554         if (track->private_size >= RVPROPERTIES_SIZE
1555             && (!strcmp(track->codec_id, MKV_V_REALV10)
1556                 || !strcmp(track->codec_id, MKV_V_REALV20)
1557                 || !strcmp(track->codec_id, MKV_V_REALV30)
1558                 || !strcmp(track->codec_id, MKV_V_REALV40))) {
1559             unsigned char *dst, *src;
1560             uint32_t type2;
1561             size_t cnt;
1562 
1563             src = (uint8_t *) track->private_data + RVPROPERTIES_SIZE;
1564 
1565             cnt = track->private_size - RVPROPERTIES_SIZE;
1566             if (cnt > INT_MAX - sizeof(*bih) - 8) {
1567                 mp_msg(MSGT_DEMUX, MSGL_ERR, "[mkv] Integer overflow!\n");
1568                 free(bih);
1569                 return 1;
1570             }
1571             bih = realloc(bih, sizeof(*bih) + 8 + cnt);
1572             bih->biSize = 48 + cnt;
1573             bih->biPlanes = 1;
1574             type2 = AV_RB32(src - 4);
1575             if (type2 == 0x10003000 || type2 == 0x10003001)
1576                 bih->biCompression = mmioFOURCC('R', 'V', '1', '3');
1577             else
1578                 bih->biCompression =
1579                     mmioFOURCC('R', 'V', track->codec_id[9], '0');
1580             dst = (unsigned char *) (bih + 1);
1581             // copy type1 and type2 info from rv properties
1582             memcpy(dst, src - 8, 8);
1583             stream_read(demuxer->stream, dst + 8, cnt);
1584             track->realmedia = 1;
1585 
1586 #ifdef CONFIG_QTX_CODECS
1587         } else if (track->private_size >= sizeof(ImageDescription)
1588                    && !strcmp(track->codec_id, MKV_V_QUICKTIME)) {
1589             ImageDescriptionPtr idesc;
1590 
1591             idesc = (ImageDescriptionPtr) track->private_data;
1592             idesc->idSize = be2me_32(idesc->idSize);
1593             idesc->cType = be2me_32(idesc->cType);
1594             idesc->version = be2me_16(idesc->version);
1595             idesc->revisionLevel = be2me_16(idesc->revisionLevel);
1596             idesc->vendor = be2me_32(idesc->vendor);
1597             idesc->temporalQuality = be2me_32(idesc->temporalQuality);
1598             idesc->spatialQuality = be2me_32(idesc->spatialQuality);
1599             idesc->width = be2me_16(idesc->width);
1600             idesc->height = be2me_16(idesc->height);
1601             idesc->hRes = be2me_32(idesc->hRes);
1602             idesc->vRes = be2me_32(idesc->vRes);
1603             idesc->dataSize = be2me_32(idesc->dataSize);
1604             idesc->frameCount = be2me_16(idesc->frameCount);
1605             idesc->depth = be2me_16(idesc->depth);
1606             idesc->clutID = be2me_16(idesc->clutID);
1607             bih->biPlanes = 1;
1608             bih->biCompression = idesc->cType;
1609             ImageDesc = idesc;
1610 #endif                          /* CONFIG_QTX_CODECS */
1611 
1612         } else {
1613             const videocodec_info_t *vi = vinfo;
1614             while (vi->id && strcmp(vi->id, track->codec_id))
1615                 vi++;
1616             bih->biCompression = vi->fourcc;
1617             if (vi->extradata && track->private_data
1618                 && (track->private_size > 0)) {
1619                 bih->biSize += track->private_size;
1620                 bih = realloc(bih, bih->biSize);
1621                 memcpy(bih + 1, track->private_data, track->private_size);
1622             }
1623             track->reorder_timecodes = user_correct_pts == 0;
1624             if (!vi->id) {
1625                 mp_msg(MSGT_DEMUX, MSGL_WARN, MSGTR_MPDEMUX_MKV_UnknownCodecID,
1626                        track->codec_id, track->tnum);
1627                 free(bih);
1628                 return 1;
1629             }
1630         }
1631     }
1632 
1633     sh_v = new_sh_video_vid(demuxer, track->tnum, vid);
1634     sh_v->bih = bih;
1635     sh_v->format = sh_v->bih->biCompression;
1636     if (track->v_frate == 0.0)
1637         track->v_frate = 25.0;
1638     sh_v->fps = track->v_frate;
1639     sh_v->frametime = 1 / track->v_frate;
1640     sh_v->original_aspect = 0;
1641     if (!track->realmedia) {
1642         sh_v->disp_w = track->v_width;
1643         sh_v->disp_h = track->v_height;
1644         if (track->v_dheight)
1645             sh_v->original_aspect = (float) track->v_dwidth / (float) track->v_dheight;
1646     } else {
1647         // vd_realvid.c will set aspect to disp_w/disp_h and rederive
1648         // disp_w and disp_h from the RealVideo stream contents returned
1649         // by the Real DLLs. If DisplayWidth/DisplayHeight was not set in
1650         // the Matroska file then it has already been set to PixelWidth/Height
1651         // by check_track_information.
1652         sh_v->disp_w = track->v_dwidth;
1653         sh_v->disp_h = track->v_dheight;
1654     }
1655     sh_v->ImageDesc = ImageDesc;
1656     mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Aspect: %f\n", sh_v->aspect);
1657 
1658     return 0;
1659 }
1660 
demux_mkv_open_audio(demuxer_t * demuxer,mkv_track_t * track,int aid)1661 static int demux_mkv_open_audio(demuxer_t *demuxer, mkv_track_t *track,
1662                                 int aid)
1663 {
1664     mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1665     sh_audio_t *sh_a = new_sh_audio_aid(demuxer, track->tnum, aid,
1666                                         track->language);
1667     demux_packet_t *dp;
1668     if (!sh_a)
1669         return 1;
1670     mkv_d->audio_tracks[mkv_d->last_aid] = track->tnum;
1671 
1672     sh_a->default_track = track->default_track;
1673     sh_a->wf = malloc(sizeof(*sh_a->wf));
1674     if (track->ms_compat && (track->private_size >= sizeof(*sh_a->wf))) {
1675         WAVEFORMATEX *wf = (WAVEFORMATEX *) track->private_data;
1676         if (track->private_size > USHRT_MAX + sizeof(WAVEFORMATEX)) {
1677             mp_msg(MSGT_DEMUX, MSGL_ERR, "[mkv] Integer overflow!\n");
1678             goto err_out;
1679         }
1680         sh_a->wf = realloc(sh_a->wf, track->private_size);
1681         sh_a->wf->wFormatTag = le2me_16(wf->wFormatTag);
1682         sh_a->wf->nChannels = le2me_16(wf->nChannels);
1683         sh_a->wf->nSamplesPerSec = le2me_32(wf->nSamplesPerSec);
1684         sh_a->wf->nAvgBytesPerSec = le2me_32(wf->nAvgBytesPerSec);
1685         sh_a->wf->nBlockAlign = le2me_16(wf->nBlockAlign);
1686         sh_a->wf->wBitsPerSample = le2me_16(wf->wBitsPerSample);
1687         sh_a->wf->cbSize = track->private_size - sizeof(*sh_a->wf);
1688         memcpy(sh_a->wf + 1, wf + 1,
1689                track->private_size - sizeof(*sh_a->wf));
1690         if (track->a_sfreq == 0.0)
1691             track->a_sfreq = sh_a->wf->nSamplesPerSec;
1692         if (track->a_channels == 0)
1693             track->a_channels = sh_a->wf->nChannels;
1694         if (track->a_bps == 0)
1695             track->a_bps = sh_a->wf->wBitsPerSample;
1696         track->a_formattag = sh_a->wf->wFormatTag;
1697     } else {
1698         memset(sh_a->wf, 0, sizeof(*sh_a->wf));
1699         if (!strcmp(track->codec_id, MKV_A_MP3)
1700             || !strcmp(track->codec_id, MKV_A_MP2))
1701             track->a_formattag = 0x0055;
1702         else if (!strncmp(track->codec_id, MKV_A_AC3, strlen(MKV_A_AC3)))
1703             track->a_formattag = 0x2000;
1704         else if (!strcmp(track->codec_id, MKV_A_DTS))
1705             track->a_formattag = 0x2001;
1706         else if (!strcmp(track->codec_id, MKV_A_EAC3))
1707             track->a_formattag = mmioFOURCC('E', 'A', 'C', '3');
1708         else if (!strcmp(track->codec_id, MKV_A_PCM)
1709                  || !strcmp(track->codec_id, MKV_A_PCM_BE))
1710             track->a_formattag = 0x0001;
1711         else if (!strcmp(track->codec_id, MKV_A_AAC_2MAIN)
1712                  || !strncmp(track->codec_id, MKV_A_AAC_2LC,
1713                              strlen(MKV_A_AAC_2LC))
1714                  || !strcmp(track->codec_id, MKV_A_AAC_2SSR)
1715                  || !strcmp(track->codec_id, MKV_A_AAC_4MAIN)
1716                  || !strncmp(track->codec_id, MKV_A_AAC_4LC,
1717                              strlen(MKV_A_AAC_4LC))
1718                  || !strcmp(track->codec_id, MKV_A_AAC_4SSR)
1719                  || !strcmp(track->codec_id, MKV_A_AAC_4LTP)
1720                  || !strcmp(track->codec_id, MKV_A_AAC))
1721             track->a_formattag = mmioFOURCC('M', 'P', '4', 'A');
1722         else if (!strcmp(track->codec_id, MKV_A_VORBIS)) {
1723             if (track->private_data == NULL)
1724                 goto err_out;
1725             track->a_formattag = mmioFOURCC('v', 'r', 'b', 's');
1726         } else if (!strcmp(track->codec_id, MKV_A_QDMC))
1727             track->a_formattag = mmioFOURCC('Q', 'D', 'M', 'C');
1728         else if (!strcmp(track->codec_id, MKV_A_QDMC2))
1729             track->a_formattag = mmioFOURCC('Q', 'D', 'M', '2');
1730         else if (!strcmp(track->codec_id, MKV_A_WAVPACK))
1731             track->a_formattag = mmioFOURCC('W', 'V', 'P', 'K');
1732         else if (!strcmp(track->codec_id, MKV_A_TRUEHD))
1733             track->a_formattag = mmioFOURCC('T', 'R', 'H', 'D');
1734         else if (!strcmp(track->codec_id, MKV_A_FLAC)) {
1735             if (track->private_data == NULL || track->private_size == 0) {
1736                 mp_msg(MSGT_DEMUX, MSGL_WARN,
1737                        MSGTR_MPDEMUX_MKV_FlacTrackDoesNotContainValidHeaders);
1738                 goto err_out;
1739             }
1740             track->a_formattag = mmioFOURCC('f', 'L', 'a', 'C');
1741         } else if (track->private_size >= RAPROPERTIES4_SIZE) {
1742             if (!strcmp(track->codec_id, MKV_A_REAL28))
1743                 track->a_formattag = mmioFOURCC('2', '8', '_', '8');
1744             else if (!strcmp(track->codec_id, MKV_A_REALATRC))
1745                 track->a_formattag = mmioFOURCC('a', 't', 'r', 'c');
1746             else if (!strcmp(track->codec_id, MKV_A_REALCOOK))
1747                 track->a_formattag = mmioFOURCC('c', 'o', 'o', 'k');
1748             else if (!strcmp(track->codec_id, MKV_A_REALDNET))
1749                 track->a_formattag = mmioFOURCC('d', 'n', 'e', 't');
1750             else if (!strcmp(track->codec_id, MKV_A_REALSIPR))
1751                 track->a_formattag = mmioFOURCC('s', 'i', 'p', 'r');
1752         } else {
1753             mp_msg(MSGT_DEMUX, MSGL_WARN, MSGTR_MPDEMUX_MKV_UnknownAudioCodec,
1754                    track->codec_id, track->tnum);
1755             goto err_out;
1756         }
1757     }
1758 
1759     sh_a->format = track->a_formattag;
1760     sh_a->wf->wFormatTag = track->a_formattag;
1761     sh_a->channels = track->a_channels;
1762     sh_a->wf->nChannels = track->a_channels;
1763     sh_a->samplerate = (uint32_t) track->a_sfreq;
1764     sh_a->wf->nSamplesPerSec = (uint32_t) track->a_sfreq;
1765     if (track->a_bps == 0) {
1766         sh_a->samplesize = 2;
1767         sh_a->wf->wBitsPerSample = 16;
1768     } else {
1769         sh_a->samplesize = track->a_bps / 8;
1770         sh_a->wf->wBitsPerSample = track->a_bps;
1771     }
1772     if (track->a_formattag == 0x0055) { /* MP3 || MP2 */
1773         sh_a->wf->nAvgBytesPerSec = 16000;
1774         sh_a->wf->nBlockAlign = 1152;
1775     } else if ((track->a_formattag == 0x2000) ||        /* AC3 */
1776                (track->a_formattag == mmioFOURCC('E', 'A', 'C', '3')) ||
1777                (track->a_formattag == 0x2001)) {        /* DTS */
1778         free(sh_a->wf);
1779         sh_a->wf = NULL;
1780     } else if (track->a_formattag == 0x0001) {  /* PCM || PCM_BE */
1781         sh_a->wf->nAvgBytesPerSec = sh_a->channels * sh_a->samplerate * 2;
1782         sh_a->wf->nBlockAlign = sh_a->wf->nAvgBytesPerSec;
1783         if (!strcmp(track->codec_id, MKV_A_PCM_BE))
1784             sh_a->format = mmioFOURCC('t', 'w', 'o', 's');
1785     } else if (!strcmp(track->codec_id, MKV_A_QDMC)
1786                || !strcmp(track->codec_id, MKV_A_QDMC2)) {
1787         sh_a->wf->nAvgBytesPerSec = 16000;
1788         sh_a->wf->nBlockAlign = 1486;
1789         track->fix_i_bps = 1;
1790         track->qt_last_a_pts = 0.0;
1791         if (track->private_data != NULL) {
1792             if (track->private_size > INT_MAX) {
1793                 mp_msg(MSGT_DEMUX, MSGL_ERR, "[mkv] Integer overflow!\n");
1794                 goto err_out;
1795             }
1796             sh_a->codecdata = malloc(track->private_size);
1797             memcpy(sh_a->codecdata, track->private_data, track->private_size);
1798             sh_a->codecdata_len = track->private_size;
1799         }
1800     } else if (track->a_formattag == mmioFOURCC('M', 'P', '4', 'A')) {
1801         int profile, srate_idx;
1802 
1803         sh_a->wf->nAvgBytesPerSec = 16000;
1804         sh_a->wf->nBlockAlign = 1024;
1805 
1806         if (!strcmp(track->codec_id, MKV_A_AAC)
1807             && (NULL != track->private_data)) {
1808             if (track->private_size > INT_MAX) {
1809                 mp_msg(MSGT_DEMUX, MSGL_ERR, "[mkv] Integer overflow!\n");
1810                 goto err_out;
1811             }
1812             sh_a->codecdata = malloc(track->private_size);
1813             memcpy(sh_a->codecdata, track->private_data, track->private_size);
1814             sh_a->codecdata_len = track->private_size;
1815             return 0;
1816         }
1817 
1818         /* Recreate the 'private data' */
1819         /* which faad2 uses in its initialization */
1820         srate_idx = aac_get_sample_rate_index(sh_a->samplerate);
1821         if (!strncmp(&track->codec_id[12], "MAIN", 4))
1822             profile = 0;
1823         else if (!strncmp(&track->codec_id[12], "LC", 2))
1824             profile = 1;
1825         else if (!strncmp(&track->codec_id[12], "SSR", 3))
1826             profile = 2;
1827         else
1828             profile = 3;
1829         sh_a->codecdata = malloc(5);
1830         sh_a->codecdata[0] = ((profile + 1) << 3) | ((srate_idx & 0xE) >> 1);
1831         sh_a->codecdata[1] =
1832             ((srate_idx & 0x1) << 7) | (track->a_channels << 3);
1833 
1834         if (strstr(track->codec_id, "SBR") != NULL) {
1835             /* HE-AAC (aka SBR AAC) */
1836             sh_a->codecdata_len = 5;
1837 
1838             sh_a->samplerate *= 2;
1839             sh_a->wf->nSamplesPerSec *= 2;
1840             srate_idx = aac_get_sample_rate_index(sh_a->samplerate);
1841             sh_a->codecdata[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
1842             sh_a->codecdata[3] = ((AAC_SYNC_EXTENSION_TYPE & 0x07) << 5) | 5;
1843             sh_a->codecdata[4] = (1 << 7) | (srate_idx << 3);
1844             track->default_duration = 1024.0 / (sh_a->samplerate / 2);
1845         } else {
1846             sh_a->codecdata_len = 2;
1847             track->default_duration = 1024.0 / (float) sh_a->samplerate;
1848         }
1849     } else if (track->a_formattag == mmioFOURCC('v', 'r', 'b', 's')) {  /* VORBIS */
1850         if (track->private_size > USHRT_MAX) {
1851             mp_msg(MSGT_DEMUX, MSGL_ERR, "[mkv] Integer overflow!\n");
1852             goto err_out;
1853         }
1854         sh_a->wf->cbSize = track->private_size;
1855         sh_a->wf = realloc(sh_a->wf, sizeof(*sh_a->wf) + sh_a->wf->cbSize);
1856         memcpy((unsigned char *) (sh_a->wf + 1), track->private_data,
1857                sh_a->wf->cbSize);
1858     } else if (track->private_size >= RAPROPERTIES4_SIZE
1859                && !strncmp(track->codec_id, MKV_A_REALATRC, 7)) {
1860         /* Common initialization for all RealAudio codecs */
1861         unsigned char *src = track->private_data;
1862         unsigned char *src_end = src + track->private_size;
1863         unsigned codecdata_length, version;
1864         int flavor;
1865 
1866         sh_a->wf->nAvgBytesPerSec = 0;  /* FIXME !? */
1867 
1868         version = AV_RB16(src + 4);
1869         flavor = AV_RB16(src + 22);
1870         track->coded_framesize = AV_RB32(src + 24);
1871         track->sub_packet_h = AV_RB16(src + 40);
1872         sh_a->wf->nBlockAlign = track->audiopk_size = AV_RB16(src + 42);
1873         track->sub_packet_size = AV_RB16(src + 44);
1874         if (version == 4) {
1875             src += RAPROPERTIES4_SIZE;
1876             if (src[0] + 1 > src_end - src) goto err_out;
1877             src += src[0] + 1;
1878             if (src[0] + 1 > src_end - src) goto err_out;
1879             src += src[0] + 1;
1880         } else {
1881             if (RAPROPERTIES5_SIZE > src_end - src) goto err_out;
1882             src += RAPROPERTIES5_SIZE;
1883         }
1884 
1885         if (4 > src_end - src) goto err_out;
1886         src += 3;
1887         if (version == 5)
1888             src++;
1889         if (4 > src_end - src) goto err_out;
1890         codecdata_length = AV_RB32(src);
1891         src += 4;
1892         codecdata_length = FFMIN(codecdata_length, src_end - src);
1893         sh_a->wf->cbSize = codecdata_length;
1894         sh_a->wf = realloc(sh_a->wf, sizeof(*sh_a->wf) + sh_a->wf->cbSize);
1895         memcpy(((char *) (sh_a->wf + 1)), src, codecdata_length);
1896 
1897         switch (track->a_formattag) {
1898         case mmioFOURCC('a', 't', 'r', 'c'):
1899             if (flavor < FF_ARRAY_ELEMS(atrc_fl2bps))
1900                 sh_a->wf->nAvgBytesPerSec = atrc_fl2bps[flavor];
1901             sh_a->wf->nBlockAlign = track->sub_packet_size;
1902             track->audio_buf =
1903                 calloc(track->sub_packet_h, track->audiopk_size);
1904             track->audio_timestamp =
1905                 calloc(track->sub_packet_h, sizeof(float));
1906             break;
1907         case mmioFOURCC('c', 'o', 'o', 'k'):
1908             if (flavor < FF_ARRAY_ELEMS(cook_fl2bps))
1909                 sh_a->wf->nAvgBytesPerSec = cook_fl2bps[flavor];
1910             sh_a->wf->nBlockAlign = track->sub_packet_size;
1911             track->audio_buf =
1912                 calloc(track->sub_packet_h, track->audiopk_size);
1913             track->audio_timestamp =
1914                 calloc(track->sub_packet_h, sizeof(float));
1915             break;
1916         case mmioFOURCC('s', 'i', 'p', 'r'):
1917             if (flavor < FF_ARRAY_ELEMS(sipr_fl2bps))
1918                 sh_a->wf->nAvgBytesPerSec = sipr_fl2bps[flavor];
1919             sh_a->wf->nBlockAlign = track->coded_framesize;
1920             track->audio_buf =
1921                 calloc(track->sub_packet_h, track->audiopk_size);
1922             track->audio_timestamp =
1923                 calloc(track->sub_packet_h, sizeof(float));
1924             break;
1925         case mmioFOURCC('2', '8', '_', '8'):
1926             sh_a->wf->nAvgBytesPerSec = 3600;
1927             sh_a->wf->nBlockAlign = track->coded_framesize;
1928             track->audio_buf =
1929                 calloc(track->sub_packet_h, track->audiopk_size);
1930             track->audio_timestamp =
1931                 calloc(track->sub_packet_h, sizeof(float));
1932             break;
1933         }
1934 
1935         track->realmedia = 1;
1936     } else if (!strcmp(track->codec_id, MKV_A_FLAC)
1937                || (track->a_formattag == 0xf1ac)) {
1938         unsigned char *ptr;
1939         size_t size;
1940         free(sh_a->wf);
1941         sh_a->wf = NULL;
1942 
1943         if (track->a_formattag == mmioFOURCC('f', 'L', 'a', 'C')) {
1944             ptr = track->private_data;
1945             size = track->private_size;
1946         } else {
1947             sh_a->format = mmioFOURCC('f', 'L', 'a', 'C');
1948             ptr  = (unsigned char *) track->private_data + sizeof(*sh_a->wf);
1949             size = track->private_size - sizeof(*sh_a->wf);
1950         }
1951         if (size < 4 || ptr[0] != 'f' || ptr[1] != 'L' || ptr[2] != 'a'
1952             || ptr[3] != 'C') {
1953             dp = new_demux_packet(4);
1954             memcpy(dp->buffer, "fLaC", 4);
1955         } else {
1956             dp = new_demux_packet(size);
1957             memcpy(dp->buffer, ptr, size);
1958         }
1959         dp->pts = 0;
1960         dp->flags = 0;
1961         ds_add_packet(demuxer->audio, dp);
1962     } else if (track->a_formattag == mmioFOURCC('W', 'V', 'P', 'K') ||
1963                track->a_formattag == mmioFOURCC('T', 'R', 'H', 'D')) {
1964         /* do nothing, still works */
1965     } else if (!track->ms_compat
1966                || (track->private_size < sizeof(*sh_a->wf))) {
1967         goto err_out;
1968     }
1969 
1970     return 0;
1971 
1972 err_out:
1973     free_sh_audio(demuxer, track->tnum);
1974     return 1;
1975 }
1976 
demux_mkv_open_sub(demuxer_t * demuxer,mkv_track_t * track,int sid)1977 static int demux_mkv_open_sub(demuxer_t *demuxer, mkv_track_t *track,
1978                               int sid)
1979 {
1980     if (track->subtitle_type != MATROSKA_SUBTYPE_UNKNOWN) {
1981         size_t size;
1982         int m;
1983         uint8_t *buffer;
1984         sh_sub_t *sh = new_sh_sub_sid(demuxer, track->tnum, sid, track->language);
1985         track->sh_sub = sh;
1986         sh->type = 't';
1987         if (track->subtitle_type == MATROSKA_SUBTYPE_VOBSUB)
1988             sh->type = 'v';
1989         if (track->subtitle_type == MATROSKA_SUBTYPE_SSA)
1990             sh->type = 'a';
1991         size = track->private_size;
1992         m = demux_mkv_decode(track, track->private_data, &buffer, &size, 2);
1993         if (buffer && m) {
1994             free(track->private_data);
1995             track->private_data = buffer;
1996             track->private_size = size;
1997         }
1998         if (track->private_size > INT_MAX) {
1999             mp_msg(MSGT_DEMUX, MSGL_ERR, "[mkv] Integer overflow!\n");
2000             return 1;
2001         }
2002         sh->extradata = malloc(track->private_size);
2003         memcpy(sh->extradata, track->private_data, track->private_size);
2004         sh->extradata_len = track->private_size;
2005         sh->default_track = track->default_track;
2006     } else {
2007         mp_msg(MSGT_DEMUX, MSGL_ERR,
2008                MSGTR_MPDEMUX_MKV_SubtitleTypeNotSupported, track->codec_id);
2009         return 1;
2010     }
2011 
2012     return 0;
2013 }
2014 
demux_mkv_open(demuxer_t * demuxer)2015 static int demux_mkv_open(demuxer_t *demuxer)
2016 {
2017     stream_t *s = demuxer->stream;
2018     mkv_demuxer_t *mkv_d;
2019     mkv_track_t *track;
2020     int i, version, cont = 0;
2021     char *str;
2022 
2023     stream_seek(s, s->start_pos);
2024     str = ebml_read_header(s, &version);
2025     if (str == NULL || (strcmp(str, "matroska") && strcmp(str, "webm")) || version > 2) {
2026         mp_msg(MSGT_DEMUX, MSGL_DBG2, "[mkv] no head found\n");
2027         return 0;
2028     }
2029     free(str);
2030 
2031     mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Found the head...\n");
2032 
2033     if (ebml_read_id(s, NULL) != MATROSKA_ID_SEGMENT) {
2034         mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] but no segment :(\n");
2035         return 0;
2036     }
2037     ebml_read_length(s, NULL);  /* return bytes number until EOF */
2038 
2039     mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] + a segment...\n");
2040 
2041     mkv_d = calloc(1, sizeof(mkv_demuxer_t));
2042     demuxer->priv = mkv_d;
2043     mkv_d->tc_scale = 1000000;
2044     mkv_d->segment_start = stream_tell(s);
2045     mkv_d->parsed_cues = malloc(sizeof(off_t));
2046     mkv_d->parsed_seekhead = malloc(sizeof(off_t));
2047 
2048     while (!cont) {
2049         switch (ebml_read_id(s, NULL)) {
2050         case MATROSKA_ID_INFO:
2051             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |+ segment information...\n");
2052             cont = demux_mkv_read_info(demuxer);
2053             break;
2054 
2055         case MATROSKA_ID_TRACKS:
2056             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |+ segment tracks...\n");
2057             cont = demux_mkv_read_tracks(demuxer);
2058             break;
2059 
2060         case MATROSKA_ID_CUES:
2061             cont = demux_mkv_read_cues(demuxer);
2062             break;
2063 
2064         case MATROSKA_ID_TAGS:
2065             cont = demux_mkv_read_tags(demuxer);
2066             break;
2067 
2068         case MATROSKA_ID_SEEKHEAD:
2069             cont = demux_mkv_read_seekhead(demuxer);
2070             break;
2071 
2072         case MATROSKA_ID_CHAPTERS:
2073             cont = demux_mkv_read_chapters(demuxer);
2074             break;
2075 
2076         case MATROSKA_ID_ATTACHMENTS:
2077             cont = demux_mkv_read_attachments(demuxer);
2078             break;
2079 
2080         case MATROSKA_ID_CLUSTER:
2081         {
2082             int p, l;
2083             mp_msg(MSGT_DEMUX, MSGL_V,
2084                    "[mkv] |+ found cluster, headers are "
2085                    "parsed completely :)\n");
2086             /* get the first cluster timecode */
2087             p = stream_tell(s);
2088             l = ebml_read_length(s, NULL);
2089             while (ebml_read_id(s, NULL) != MATROSKA_ID_CLUSTERTIMECODE) {
2090                 ebml_read_skip(s, NULL);
2091                 if (stream_tell(s) >= p + l)
2092                     break;
2093             }
2094             if (stream_tell(s) < p + l) {
2095                 uint64_t num = ebml_read_uint(s, NULL);
2096                 if (num == EBML_UINT_INVALID)
2097                     return 0;
2098                 mkv_d->first_tc = num * mkv_d->tc_scale / 1000000.0;
2099                 mkv_d->has_first_tc = 1;
2100             }
2101             stream_seek(s, p - 4);
2102             cont = 1;
2103             break;
2104         }
2105 
2106         default:
2107             cont = 1;
2108             /* Fallthrough to skip data */
2109         case EBML_ID_VOID:
2110             ebml_read_skip(s, NULL);
2111             break;
2112         }
2113     }
2114 
2115     display_create_tracks(demuxer);
2116 
2117     /* select video track */
2118     track = NULL;
2119     if (demuxer->video->id == -1) {     /* automatically select a video track */
2120         /* search for a video track that has the 'default' flag set */
2121         for (i = 0; i < mkv_d->num_tracks; i++)
2122             if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO
2123                 && mkv_d->tracks[i]->default_track) {
2124                 track = mkv_d->tracks[i];
2125                 break;
2126             }
2127 
2128         if (track == NULL)
2129             /* no track has the 'default' flag set */
2130             /* let's take the first video track */
2131             for (i = 0; i < mkv_d->num_tracks; i++)
2132                 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO) {
2133                     track = mkv_d->tracks[i];
2134                     break;
2135                 }
2136     } else if (demuxer->video->id != -2)        /* -2 = no video at all */
2137         track = demux_mkv_find_track_by_num(mkv_d, demuxer->video->id,
2138                                             MATROSKA_TRACK_VIDEO);
2139 
2140     if (track && demuxer->v_streams[track->tnum]) {
2141         mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_WillPlayVideoTrack,
2142                track->tnum);
2143         demuxer->video->id = track->tnum;
2144         demuxer->video->sh = demuxer->v_streams[track->tnum];
2145     } else {
2146         mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_NoVideoTrackFound);
2147         demuxer->video->id = -2;
2148     }
2149 
2150     /* select audio track */
2151     track = NULL;
2152     if (track == NULL)
2153         /* search for an audio track that has the 'default' flag set */
2154         for (i = 0; i < mkv_d->num_tracks; i++)
2155             if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO
2156                 && mkv_d->tracks[i]->default_track) {
2157                 track = mkv_d->tracks[i];
2158                 break;
2159             }
2160 
2161     if (track == NULL)
2162         /* no track has the 'default' flag set */
2163         /* let's take the first audio track */
2164         for (i = 0; i < mkv_d->num_tracks; i++)
2165             if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO) {
2166                 track = mkv_d->tracks[i];
2167                 break;
2168             }
2169 
2170     if (track && demuxer->a_streams[track->tnum]) {
2171         demuxer->audio->id = track->tnum;
2172         demuxer->audio->sh = demuxer->a_streams[track->tnum];
2173     } else {
2174         mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_NoAudioTrackFound);
2175         demuxer->audio->id = -2;
2176     }
2177 
2178 
2179     if (demuxer->audio->id != -2)
2180         for (i = 0; i < mkv_d->num_tracks; i++) {
2181             if (mkv_d->tracks[i]->type != MATROSKA_TRACK_AUDIO)
2182                 continue;
2183             if (demuxer->a_streams[track->tnum]) {
2184                 mkv_d->last_aid++;
2185                 if (mkv_d->last_aid == MAX_A_STREAMS)
2186                     break;
2187             }
2188         }
2189 
2190     if (demuxer->chapters) {
2191         for (i = 0; i < (int) demuxer->num_chapters; i++) {
2192             demuxer->chapters[i].start -= mkv_d->first_tc;
2193             demuxer->chapters[i].end -= mkv_d->first_tc;
2194         }
2195         if (dvd_last_chapter > 0 && dvd_last_chapter <= demuxer->num_chapters) {
2196             if (demuxer->chapters[dvd_last_chapter - 1].end != 0)
2197                 mkv_d->stop_timecode =
2198                     demuxer->chapters[dvd_last_chapter - 1].end;
2199             else if (dvd_last_chapter + 1 <= demuxer->num_chapters)
2200                 mkv_d->stop_timecode =
2201                     demuxer->chapters[dvd_last_chapter].start;
2202         }
2203     }
2204 
2205     if (s->end_pos == 0 || (mkv_d->indexes == NULL && index_mode < 0))
2206         demuxer->seekable = 0;
2207     else {
2208         demuxer->movi_start = s->start_pos;
2209         demuxer->movi_end = s->end_pos;
2210         demuxer->seekable = 1;
2211     }
2212 
2213     return DEMUXER_TYPE_MATROSKA;
2214 }
2215 
demux_close_mkv(demuxer_t * demuxer)2216 static void demux_close_mkv(demuxer_t *demuxer)
2217 {
2218     mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2219 
2220     if (mkv_d) {
2221         int i;
2222         free_cached_dps(demuxer);
2223         if (mkv_d->tracks) {
2224             for (i = 0; i < mkv_d->num_tracks; i++)
2225                 demux_mkv_free_trackentry(mkv_d->tracks[i]);
2226             free(mkv_d->tracks);
2227         }
2228         free(mkv_d->indexes);
2229         free(mkv_d->cluster_positions);
2230         free(mkv_d->parsed_cues);
2231         free(mkv_d->parsed_seekhead);
2232         free(mkv_d);
2233     }
2234 }
2235 
demux_mkv_read_block_lacing(uint8_t * buffer,uint64_t * size,uint8_t * laces,uint32_t ** all_lace_sizes)2236 static int demux_mkv_read_block_lacing(uint8_t *buffer, uint64_t *size,
2237                                        uint8_t *laces,
2238                                        uint32_t **all_lace_sizes)
2239 {
2240     uint32_t total = 0, *lace_size;
2241     uint8_t flags;
2242     int i;
2243 
2244     *all_lace_sizes = NULL;
2245     lace_size = NULL;
2246     /* lacing flags */
2247     if (!*size) goto err_out;
2248     flags = *buffer++;
2249     (*size)--;
2250 
2251     switch ((flags & 0x06) >> 1) {
2252     case 0:                    /* no lacing */
2253         *laces = 1;
2254         lace_size = calloc(*laces, sizeof(uint32_t));
2255         lace_size[0] = *size;
2256         break;
2257 
2258     case 1:                    /* xiph lacing */
2259     case 2:                    /* fixed-size lacing */
2260     case 3:                    /* EBML lacing */
2261         if (!*size) goto err_out;
2262         *laces = *buffer++;
2263         (*size)--;
2264         (*laces)++;
2265         lace_size = calloc(*laces, sizeof(uint32_t));
2266 
2267         switch ((flags & 0x06) >> 1) {
2268         case 1:                /* xiph lacing */
2269             for (i = 0; i < *laces - 1; i++) {
2270                 lace_size[i] = 0;
2271                 do {
2272                     lace_size[i] += *buffer;
2273                     if (!*size) goto err_out;
2274                     (*size)--;
2275                 } while (*buffer++ == 0xFF);
2276                 total += lace_size[i];
2277             }
2278             if (*size < total) goto err_out;
2279             lace_size[i] = *size - total;
2280             break;
2281 
2282         case 2:                /* fixed-size lacing */
2283             for (i = 0; i < *laces; i++)
2284                 lace_size[i] = *size / *laces;
2285             break;
2286 
2287         case 3:                /* EBML lacing */
2288         {
2289             int l;
2290             uint64_t num = ebml_read_vlen_uint(buffer, &l);
2291             if (num == EBML_UINT_INVALID || *size < l) goto err_out;
2292             buffer += l;
2293             *size -= l;
2294 
2295             total = lace_size[0] = num;
2296             for (i = 1; i < *laces - 1; i++) {
2297                 int64_t snum;
2298                 snum = ebml_read_vlen_int(buffer, &l);
2299                 if (snum == EBML_INT_INVALID || *size < l) goto err_out;
2300                 buffer += l;
2301                 *size -= l;
2302                 lace_size[i] = lace_size[i - 1] + snum;
2303                 total += lace_size[i];
2304             }
2305             if (*size < total) goto err_out;
2306             lace_size[i] = *size - total;
2307             break;
2308         }
2309         }
2310         break;
2311     }
2312     *all_lace_sizes = lace_size;
2313     return 0;
2314 
2315 err_out:
2316     free(lace_size);
2317     return 1;
2318 }
2319 
handle_subtitles(demuxer_t * demuxer,mkv_track_t * track,char * block,int64_t size,uint64_t block_duration,uint64_t timecode)2320 static void handle_subtitles(demuxer_t *demuxer, mkv_track_t *track,
2321                              char *block, int64_t size,
2322                              uint64_t block_duration, uint64_t timecode)
2323 {
2324     demux_packet_t *dp;
2325 
2326     if (block_duration == 0) {
2327         mp_msg(MSGT_DEMUX, MSGL_WARN,
2328                MSGTR_MPDEMUX_MKV_NoBlockDurationForSubtitleTrackFound);
2329         return;
2330     }
2331 
2332     sub_utf8 = 1;
2333     dp = new_demux_packet(size);
2334     memcpy(dp->buffer, block, size);
2335     dp->pts = timecode / 1000.0f;
2336     dp->endpts = (timecode + block_duration) / 1000.0f;
2337     ds_add_packet(demuxer->sub, dp);
2338 }
2339 
handle_realvideo(demuxer_t * demuxer,mkv_track_t * track,uint8_t * buffer,uint32_t size,int block_bref)2340 static void handle_realvideo(demuxer_t *demuxer, mkv_track_t *track,
2341                              uint8_t *buffer, uint32_t size, int block_bref)
2342 {
2343     mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2344     demux_packet_t *dp;
2345     uint32_t timestamp = mkv_d->last_pts * 1000;
2346 
2347     dp = new_demux_packet(size);
2348     memcpy(dp->buffer, buffer, size);
2349 
2350     if (mkv_d->v_skip_to_keyframe) {
2351         dp->pts = mkv_d->last_pts;
2352         track->rv_kf_base = 0;
2353         track->rv_kf_pts = timestamp;
2354     } else
2355         dp->pts =
2356             real_fix_timestamp(dp->buffer, timestamp,
2357                                ((sh_video_t *) demuxer->video->sh)->bih->
2358                                biCompression, &track->rv_kf_base,
2359                                &track->rv_kf_pts, NULL);
2360     dp->pos = demuxer->filepos;
2361     dp->flags = block_bref ? 0 : 0x10;
2362 
2363     ds_add_packet(demuxer->video, dp);
2364 }
2365 
handle_realaudio(demuxer_t * demuxer,mkv_track_t * track,uint8_t * buffer,uint32_t size,int block_bref)2366 static void handle_realaudio(demuxer_t *demuxer, mkv_track_t *track,
2367                              uint8_t *buffer, uint32_t size, int block_bref)
2368 {
2369     mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2370     int sps = track->sub_packet_size;
2371     int sph = track->sub_packet_h;
2372     int cfs = track->coded_framesize;
2373     int w = track->audiopk_size;
2374     int spc = track->sub_packet_cnt;
2375     demux_packet_t *dp;
2376     int x;
2377 
2378     if ((track->a_formattag == mmioFOURCC('2', '8', '_', '8'))
2379         || (track->a_formattag == mmioFOURCC('c', 'o', 'o', 'k'))
2380         || (track->a_formattag == mmioFOURCC('a', 't', 'r', 'c'))
2381         || (track->a_formattag == mmioFOURCC('s', 'i', 'p', 'r'))) {
2382 //      if(!block_bref)
2383 //        spc = track->sub_packet_cnt = 0;
2384         switch (track->a_formattag) {
2385         case mmioFOURCC('2', '8', '_', '8'):
2386             for (x = 0; x < sph / 2; x++)
2387                 memcpy(track->audio_buf + x * 2 * w + spc * cfs,
2388                        buffer + cfs * x, cfs);
2389             break;
2390         case mmioFOURCC('c', 'o', 'o', 'k'):
2391         case mmioFOURCC('a', 't', 'r', 'c'):
2392             for (x = 0; x < w / sps; x++)
2393                 memcpy(track->audio_buf +
2394                        sps * (sph * x + ((sph + 1) / 2) * (spc & 1) +
2395                               (spc >> 1)), buffer + sps * x, sps);
2396             break;
2397         case mmioFOURCC('s', 'i', 'p', 'r'):
2398             memcpy(track->audio_buf + spc * w, buffer, w);
2399             if (spc == sph - 1) {
2400                 int n;
2401                 int bs = sph * w * 2 / 96;      // nibbles per subpacket
2402                 // Perform reordering
2403                 for (n = 0; n < 38; n++) {
2404                     int j;
2405                     int i = bs * sipr_swaps[n][0];
2406                     int o = bs * sipr_swaps[n][1];
2407                     // swap nibbles of block 'i' with 'o'      TODO: optimize
2408                     for (j = 0; j < bs; j++) {
2409                         int x = (i & 1) ?
2410                             (track->audio_buf[i >> 1] >> 4) :
2411                             (track->audio_buf[i >> 1] & 0x0F);
2412                         int y = (o & 1) ?
2413                             (track->audio_buf[o >> 1] >> 4) :
2414                             (track->audio_buf[o >> 1] & 0x0F);
2415                         if (o & 1)
2416                             track->audio_buf[o >> 1] =
2417                                 (track->audio_buf[o >> 1] & 0x0F) | (x << 4);
2418                         else
2419                             track->audio_buf[o >> 1] =
2420                                 (track->audio_buf[o >> 1] & 0xF0) | x;
2421                         if (i & 1)
2422                             track->audio_buf[i >> 1] =
2423                                 (track->audio_buf[i >> 1] & 0x0F) | (y << 4);
2424                         else
2425                             track->audio_buf[i >> 1] =
2426                                 (track->audio_buf[i >> 1] & 0xF0) | y;
2427                         ++i;
2428                         ++o;
2429                     }
2430                 }
2431             }
2432             break;
2433         }
2434         track->audio_timestamp[track->sub_packet_cnt] =
2435             (track->ra_pts == mkv_d->last_pts) ? 0 : (mkv_d->last_pts);
2436         track->ra_pts = mkv_d->last_pts;
2437         if (track->sub_packet_cnt == 0)
2438             track->audio_filepos = demuxer->filepos;
2439         if (++(track->sub_packet_cnt) == sph) {
2440             int apk_usize =
2441                 ((sh_audio_t *) demuxer->audio->sh)->wf->nBlockAlign;
2442             track->sub_packet_cnt = 0;
2443             // Release all the audio packets
2444             for (x = 0; x < sph * w / apk_usize; x++) {
2445                 dp = new_demux_packet(apk_usize);
2446                 memcpy(dp->buffer, track->audio_buf + x * apk_usize,
2447                        apk_usize);
2448                 /* Put timestamp only on packets that correspond to original
2449                  * audio packets in file */
2450                 dp->pts = (x * apk_usize % w) ? 0 :
2451                     track->audio_timestamp[x * apk_usize / w];
2452                 dp->pos = track->audio_filepos; // all equal
2453                 dp->flags = x ? 0 : 0x10;       // Mark first packet as keyframe
2454                 ds_add_packet(demuxer->audio, dp);
2455             }
2456         }
2457     } else {                    // Not a codec that require reordering
2458         dp = new_demux_packet(size);
2459         memcpy(dp->buffer, buffer, size);
2460         if (track->ra_pts == mkv_d->last_pts && !mkv_d->a_skip_to_keyframe)
2461             dp->pts = 0;
2462         else
2463             dp->pts = mkv_d->last_pts;
2464         track->ra_pts = mkv_d->last_pts;
2465 
2466         dp->pos = demuxer->filepos;
2467         dp->flags = block_bref ? 0 : 0x10;
2468         ds_add_packet(demuxer->audio, dp);
2469     }
2470 }
2471 
2472 /** Reorder timecodes and add cached demux packets to the queues.
2473  *
2474  * Timecode reordering is needed if a video track contains B frames that
2475  * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
2476  * MPlayer doesn't like timestamps in display order. This function adjusts
2477  * the timestamp of cached frames (which are exactly one I/P frame followed
2478  * by one or more B frames) so that they are in coding order again.
2479  *
2480  * Example: The track with 25 FPS contains four frames with the timecodes
2481  * I at 0ms, P at 120ms, B at 40ms and B at 80ms. As soon as the next I
2482  * or P frame arrives these timecodes can be changed to I at 0ms, P at 40ms,
2483  * B at 80ms and B at 120ms.
2484  *
2485  * This works for simple H.264 B-frame pyramids, but not for arbitrary orders.
2486  *
2487  * \param demuxer The Matroska demuxer struct for this instance.
2488  * \param track The track structure whose cache should be handled.
2489  */
flush_cached_dps(demuxer_t * demuxer,mkv_track_t * track)2490 static void flush_cached_dps(demuxer_t *demuxer, mkv_track_t *track)
2491 {
2492     int i, ok;
2493 
2494     if (track->num_cached_dps == 0)
2495         return;
2496 
2497     do {
2498         ok = 1;
2499         for (i = 1; i < track->num_cached_dps; i++)
2500             if (track->cached_dps[i - 1]->pts > track->cached_dps[i]->pts) {
2501                 float tmp_pts = track->cached_dps[i - 1]->pts;
2502                 track->cached_dps[i - 1]->pts = track->cached_dps[i]->pts;
2503                 track->cached_dps[i]->pts = tmp_pts;
2504                 ok = 0;
2505             }
2506     } while (!ok);
2507 
2508     for (i = 0; i < track->num_cached_dps; i++)
2509         ds_add_packet(demuxer->video, track->cached_dps[i]);
2510     track->num_cached_dps = 0;
2511 }
2512 
2513 /** Cache video frames if timecodes have to be reordered.
2514  *
2515  * Timecode reordering is needed if a video track contains B frames that
2516  * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
2517  * This function takes in a Matroska block read from the file, allocates a
2518  * demux packet for it, fills in its values, allocates space for storing
2519  * pointers to the cached demux packets and adds the packet to it. If
2520  * the packet contains an I or a P frame then ::flush_cached_dps is called
2521  * in order to send the old cached frames downstream.
2522  *
2523  * \param demuxer The Matroska demuxer struct for this instance.
2524  * \param track The packet is meant for this track.
2525  * \param buffer The actual frame contents.
2526  * \param size The frame size in bytes.
2527  * \param block_bref A relative timecode (backward reference). If it is \c 0
2528  *   then the frame is an I frame.
2529  * \param block_fref A relative timecode (forward reference). If it is \c 0
2530  *   then the frame is either an I frame or a P frame depending on the value
2531  *   of \a block_bref. Otherwise it's a B frame.
2532  */
handle_video_bframes(demuxer_t * demuxer,mkv_track_t * track,uint8_t * buffer,uint32_t size,int block_bref,int block_fref)2533 static void handle_video_bframes(demuxer_t *demuxer, mkv_track_t *track,
2534                                  uint8_t *buffer, uint32_t size,
2535                                  int block_bref, int block_fref)
2536 {
2537     mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2538     demux_packet_t *dp;
2539 
2540     dp = new_demux_packet(size);
2541     memcpy(dp->buffer, buffer, size);
2542     dp->pos = demuxer->filepos;
2543     dp->pts = mkv_d->last_pts;
2544     if ((track->num_cached_dps > 0) && (dp->pts < track->max_pts))
2545         block_fref = 1;
2546     if (block_fref == 0)        /* I or P frame */
2547         flush_cached_dps(demuxer, track);
2548     if (block_bref != 0)        /* I frame, don't cache it */
2549         dp->flags = 0x10;
2550     if ((track->num_cached_dps + 1) > track->num_allocated_dps) {
2551         track->cached_dps = (demux_packet_t **)
2552             realloc(track->cached_dps,
2553                     (track->num_cached_dps + 10) * sizeof(demux_packet_t *));
2554         track->num_allocated_dps += 10;
2555     }
2556     track->cached_dps[track->num_cached_dps] = dp;
2557     track->num_cached_dps++;
2558     if (dp->pts > track->max_pts)
2559         track->max_pts = dp->pts;
2560 }
2561 
handle_block(demuxer_t * demuxer,uint8_t * block,uint64_t length,uint64_t block_duration,int64_t block_bref,int64_t block_fref,uint8_t simpleblock)2562 static int handle_block(demuxer_t *demuxer, uint8_t *block, uint64_t length,
2563                         uint64_t block_duration, int64_t block_bref,
2564                         int64_t block_fref, uint8_t simpleblock)
2565 {
2566     mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2567     mkv_track_t *track = NULL;
2568     demux_stream_t *ds = NULL;
2569     uint64_t old_length;
2570     int64_t tc;
2571     uint32_t *lace_size;
2572     uint8_t laces, flags;
2573     int i, num, tmp, use_this_block = 1;
2574     float current_pts;
2575     int16_t time;
2576 
2577     /* first byte(s): track num */
2578     num = ebml_read_vlen_uint(block, &tmp);
2579     block += tmp;
2580     /* time (relative to cluster time) */
2581     time = block[0] << 8 | block[1];
2582     block += 2;
2583     length -= tmp + 2;
2584     old_length = length;
2585     flags = block[0];
2586     if (demux_mkv_read_block_lacing(block, &length, &laces, &lace_size))
2587         return 0;
2588     block += old_length - length;
2589 
2590     tc = ((time * mkv_d->tc_scale + mkv_d->cluster_tc) / 1000000.0 -
2591           mkv_d->first_tc);
2592     if (tc < 0)
2593         tc = 0;
2594     if (mkv_d->stop_timecode > 0 && tc > mkv_d->stop_timecode) {
2595         free(lace_size);
2596         return -1;
2597     }
2598     current_pts = tc / 1000.0;
2599 
2600     for (i = 0; i < mkv_d->num_tracks; i++)
2601         if (mkv_d->tracks[i]->tnum == num) {
2602             track = mkv_d->tracks[i];
2603             break;
2604         }
2605     if (track == NULL) {
2606         free(lace_size);
2607         return 1;
2608     }
2609     if (num == demuxer->audio->id) {
2610         ds = demuxer->audio;
2611 
2612         if (mkv_d->a_skip_to_keyframe) {
2613             if (simpleblock) {
2614                 if (!(flags & 0x80))    /*current frame isn't a keyframe */
2615                     use_this_block = 0;
2616             } else if (block_bref != 0)
2617                 use_this_block = 0;
2618         } else if (mkv_d->v_skip_to_keyframe)
2619             use_this_block = 0;
2620 
2621         if (track->fix_i_bps && use_this_block) {
2622             sh_audio_t *sh = (sh_audio_t *) ds->sh;
2623 
2624             if (block_duration != 0) {
2625                 sh->i_bps = length * 1000 / block_duration;
2626                 track->fix_i_bps = 0;
2627             } else if (track->qt_last_a_pts == 0.0)
2628                 track->qt_last_a_pts = current_pts;
2629             else if (track->qt_last_a_pts != current_pts) {
2630                 sh->i_bps = length / (current_pts - track->qt_last_a_pts);
2631                 track->fix_i_bps = 0;
2632             }
2633         }
2634     } else if (tc < mkv_d->skip_to_timecode)
2635         use_this_block = 0;
2636     else if (num == demuxer->video->id) {
2637         ds = demuxer->video;
2638         if (mkv_d->v_skip_to_keyframe) {
2639             if (simpleblock) {
2640                 if (!(flags & 0x80))    /*current frame isn't a keyframe */
2641                     use_this_block = 0;
2642             } else if (block_bref != 0 || block_fref != 0)
2643                 use_this_block = 0;
2644         }
2645     } else if (num == demuxer->sub->id) {
2646         ds = demuxer->sub;
2647         if (track->subtitle_type != MATROSKA_SUBTYPE_VOBSUB) {
2648             if (!mkv_d->v_skip_to_keyframe)
2649                 handle_subtitles(demuxer, track, block, length, block_duration,
2650                                  tc);
2651             use_this_block = 0;
2652         }
2653     } else
2654         use_this_block = 0;
2655 
2656     if (use_this_block) {
2657         mkv_d->last_pts = current_pts;
2658         mkv_d->last_filepos = demuxer->filepos;
2659 
2660         for (i = 0; i < laces; i++) {
2661             if (ds == demuxer->video && track->realmedia)
2662                 handle_realvideo(demuxer, track, block, lace_size[i],
2663                                  block_bref);
2664             else if (ds == demuxer->audio && track->realmedia)
2665                 handle_realaudio(demuxer, track, block, lace_size[i],
2666                                  block_bref);
2667             else if (ds == demuxer->video && track->reorder_timecodes)
2668                 handle_video_bframes(demuxer, track, block, lace_size[i],
2669                                      block_bref, block_fref);
2670             else {
2671                 int modified;
2672                 size_t size = lace_size[i];
2673                 demux_packet_t *dp;
2674                 uint8_t *buffer;
2675                 modified = demux_mkv_decode(track, block, &buffer, &size, 1);
2676                 if (buffer) {
2677                     dp = new_demux_packet(size);
2678                     memcpy(dp->buffer, buffer, size);
2679                     if (modified)
2680                         free(buffer);
2681                     dp->flags = (block_bref == 0
2682                                  && block_fref == 0) ? 0x10 : 0;
2683                     /* If default_duration is 0, assume no pts value is known
2684                      * for packets after the first one (rather than all pts
2685                      * values being the same) */
2686                     if (i == 0 || track->default_duration)
2687                         dp->pts =
2688                             mkv_d->last_pts + i * track->default_duration;
2689                     ds_add_packet(ds, dp);
2690                 }
2691             }
2692             block += lace_size[i];
2693         }
2694 
2695         if (ds == demuxer->video) {
2696             mkv_d->v_skip_to_keyframe = 0;
2697             mkv_d->skip_to_timecode = 0;
2698         } else if (ds == demuxer->audio)
2699             mkv_d->a_skip_to_keyframe = 0;
2700 
2701         free(lace_size);
2702         return 1;
2703     }
2704 
2705     free(lace_size);
2706     return 0;
2707 }
2708 
demux_mkv_fill_buffer(demuxer_t * demuxer,demux_stream_t * ds)2709 static int demux_mkv_fill_buffer(demuxer_t *demuxer, demux_stream_t *ds)
2710 {
2711     mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2712     stream_t *s = demuxer->stream;
2713     uint64_t l;
2714     int il, tmp;
2715 
2716     while (1) {
2717         while (mkv_d->cluster_size > 0) {
2718             uint64_t block_duration = 0, block_length = 0;
2719             int64_t block_bref = 0, block_fref = 0;
2720             uint8_t *block = NULL;
2721 
2722             while (mkv_d->blockgroup_size > 0) {
2723                 switch (ebml_read_id(s, &il)) {
2724                 case MATROSKA_ID_BLOCKDURATION:
2725                     block_duration = ebml_read_uint(s, &l);
2726                     if (block_duration == EBML_UINT_INVALID) {
2727                         free(block);
2728                         return 0;
2729                     }
2730                     block_duration *= mkv_d->tc_scale / 1000000.0;
2731                     break;
2732 
2733                 case MATROSKA_ID_BLOCK:
2734                     block_length = ebml_read_length(s, &tmp);
2735                     free(block);
2736                     if (block_length > SIZE_MAX - AV_LZO_INPUT_PADDING)
2737                         return 0;
2738                     block = malloc(block_length + AV_LZO_INPUT_PADDING);
2739                     demuxer->filepos = stream_tell(s);
2740                     if (stream_read(s, block, block_length) !=
2741                         (int) block_length) {
2742                         free(block);
2743                         return 0;
2744                     }
2745                     l = tmp + block_length;
2746                     break;
2747 
2748                 case MATROSKA_ID_REFERENCEBLOCK:
2749                 {
2750                     int64_t num = ebml_read_int(s, &l);
2751                     if (num == EBML_INT_INVALID) {
2752                         free(block);
2753                         return 0;
2754                     }
2755                     if (num <= 0)
2756                         block_bref = num;
2757                     else
2758                         block_fref = num;
2759                     break;
2760                 }
2761 
2762                 case EBML_ID_INVALID:
2763                     free(block);
2764                     return 0;
2765 
2766                 default:
2767                     ebml_read_skip(s, &l);
2768                     break;
2769                 }
2770                 mkv_d->blockgroup_size -= l + il;
2771                 mkv_d->cluster_size -= l + il;
2772             }
2773 
2774             if (block) {
2775                 int res = handle_block(demuxer, block, block_length,
2776                                        block_duration, block_bref, block_fref,
2777                                        0);
2778                 free(block);
2779                 if (res < 0)
2780                     return 0;
2781                 if (res)
2782                     return 1;
2783             }
2784 
2785             if (mkv_d->cluster_size > 0) {
2786                 switch (ebml_read_id(s, &il)) {
2787                 case MATROSKA_ID_CLUSTERTIMECODE:
2788                 {
2789                     uint64_t num = ebml_read_uint(s, &l);
2790                     if (num == EBML_UINT_INVALID)
2791                         return 0;
2792                     if (!mkv_d->has_first_tc) {
2793                         mkv_d->first_tc = num * mkv_d->tc_scale / 1000000.0;
2794                         mkv_d->has_first_tc = 1;
2795                     }
2796                     mkv_d->cluster_tc = num * mkv_d->tc_scale;
2797                     break;
2798                 }
2799 
2800                 case MATROSKA_ID_BLOCKGROUP:
2801                     mkv_d->blockgroup_size = ebml_read_length(s, &tmp);
2802                     l = tmp;
2803                     break;
2804 
2805                 case MATROSKA_ID_SIMPLEBLOCK:
2806                 {
2807                     int res;
2808                     block_length = ebml_read_length(s, &tmp);
2809                     if (block_length > SIZE_MAX)
2810                         return 0;
2811                     block = malloc(block_length);
2812                     demuxer->filepos = stream_tell(s);
2813                     if (stream_read(s, block, block_length) !=
2814                         (int) block_length) {
2815                         free(block);
2816                         return 0;
2817                     }
2818                     l = tmp + block_length;
2819                     res = handle_block(demuxer, block, block_length,
2820                                        block_duration, block_bref,
2821                                        block_fref, 1);
2822                     free(block);
2823                     mkv_d->cluster_size -= l + il;
2824                     if (res < 0)
2825                         return 0;
2826                     else if (res)
2827                         return 1;
2828                     else
2829                         mkv_d->cluster_size += l + il;
2830                     break;
2831                 }
2832                 case EBML_ID_INVALID:
2833                     return 0;
2834 
2835                 default:
2836                     ebml_read_skip(s, &l);
2837                     break;
2838                 }
2839                 mkv_d->cluster_size -= l + il;
2840             }
2841         }
2842 
2843         if (ebml_read_id(s, &il) != MATROSKA_ID_CLUSTER)
2844             return 0;
2845         add_cluster_position(mkv_d, stream_tell(s) - il);
2846         mkv_d->cluster_size = ebml_read_length(s, NULL);
2847     }
2848 
2849     return 0;
2850 }
2851 
demux_mkv_seek(demuxer_t * demuxer,float rel_seek_secs,float audio_delay,int flags)2852 static void demux_mkv_seek(demuxer_t *demuxer, float rel_seek_secs,
2853                            float audio_delay, int flags)
2854 {
2855     free_cached_dps(demuxer);
2856     if (!(flags & SEEK_FACTOR)) {       /* time in secs */
2857         mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2858         stream_t *s = demuxer->stream;
2859         int64_t target_timecode = 0, diff, min_diff = 0xFFFFFFFFFFFFFFFLL;
2860         int i;
2861 
2862         if (!(flags & SEEK_ABSOLUTE))   /* relative seek */
2863             target_timecode = (int64_t) (mkv_d->last_pts * 1000.0);
2864         target_timecode += (int64_t) (rel_seek_secs * 1000.0);
2865         if (target_timecode < 0)
2866             target_timecode = 0;
2867 
2868         if (mkv_d->indexes == NULL) {   /* no index was found */
2869             uint64_t target_filepos, cluster_pos, max_pos;
2870 
2871             target_filepos =
2872                 (uint64_t) (target_timecode * mkv_d->last_filepos /
2873                             (mkv_d->last_pts * 1000.0));
2874 
2875             max_pos = mkv_d->num_cluster_pos ?
2876                 mkv_d->cluster_positions[mkv_d->num_cluster_pos - 1] : 0;
2877             if (target_filepos > max_pos) {
2878                 if ((off_t) max_pos > stream_tell(s))
2879                     stream_seek(s, max_pos);
2880                 else
2881                     stream_seek(s, stream_tell(s) + mkv_d->cluster_size);
2882                 /* parse all the clusters upto target_filepos */
2883                 while (!s->eof && stream_tell(s) < (off_t) target_filepos) {
2884                     switch (ebml_read_id(s, &i)) {
2885                     case MATROSKA_ID_CLUSTER:
2886                         add_cluster_position(mkv_d,
2887                                              (uint64_t) stream_tell(s) - i);
2888                         break;
2889 
2890                     case MATROSKA_ID_CUES:
2891                         demux_mkv_read_cues(demuxer);
2892                         break;
2893                     }
2894                     ebml_read_skip(s, NULL);
2895                 }
2896                 if (s->eof)
2897                     stream_reset(s);
2898             }
2899 
2900             if (mkv_d->indexes == NULL) {
2901                 cluster_pos = mkv_d->cluster_positions[0];
2902                 /* Let's find the nearest cluster */
2903                 for (i = 0; i < mkv_d->num_cluster_pos; i++) {
2904                     diff = mkv_d->cluster_positions[i] - target_filepos;
2905                     if (rel_seek_secs < 0 && diff < 0 && -diff < min_diff) {
2906                         cluster_pos = mkv_d->cluster_positions[i];
2907                         min_diff = -diff;
2908                     } else if (rel_seek_secs > 0
2909                                && (diff < 0 ? -1 * diff : diff) < min_diff) {
2910                         cluster_pos = mkv_d->cluster_positions[i];
2911                         min_diff = diff < 0 ? -1 * diff : diff;
2912                     }
2913                 }
2914                 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
2915                 stream_seek(s, cluster_pos);
2916             }
2917         } else {
2918             mkv_index_t *index = NULL;
2919             int seek_id = (demuxer->video->id < 0) ?
2920                 demuxer->audio->id : demuxer->video->id;
2921 
2922             /* let's find the entry in the indexes with the smallest */
2923             /* difference to the wanted timecode. */
2924             for (i = 0; i < mkv_d->num_indexes; i++)
2925                 if (mkv_d->indexes[i].tnum == seek_id) {
2926                     diff =
2927                         target_timecode + mkv_d->first_tc -
2928                         (int64_t) mkv_d->indexes[i].timecode *
2929                         mkv_d->tc_scale / 1000000.0;
2930 
2931                     if ((flags & SEEK_ABSOLUTE
2932                          || target_timecode <= mkv_d->last_pts * 1000)) {
2933                         // Absolute seek or seek backward: find the last index
2934                         // position before target time
2935                         if (diff < 0 || diff >= min_diff)
2936                             continue;
2937                     } else {
2938                         // Relative seek forward: find the first index position
2939                         // after target time. If no such index exists, find last
2940                         // position between current position and target time.
2941                         if (diff <= 0) {
2942                             if (min_diff <= 0 && diff <= min_diff)
2943                                 continue;
2944                         } else if (diff >=
2945                                    FFMIN(target_timecode - mkv_d->last_pts,
2946                                          min_diff))
2947                             continue;
2948                     }
2949                     min_diff = diff;
2950                     index = mkv_d->indexes + i;
2951                 }
2952 
2953             if (index) {        /* We've found an entry. */
2954                 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
2955                 stream_seek(s, index->filepos);
2956             }
2957         }
2958 
2959         if (demuxer->video->id >= 0)
2960             mkv_d->v_skip_to_keyframe = 1;
2961         if (rel_seek_secs > 0.0)
2962             mkv_d->skip_to_timecode = target_timecode;
2963         mkv_d->a_skip_to_keyframe = 1;
2964 
2965         demux_mkv_fill_buffer(demuxer, NULL);
2966     } else if ((demuxer->movi_end <= 0) || !(flags & SEEK_ABSOLUTE))
2967         mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
2968     else {
2969         mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2970         stream_t *s = demuxer->stream;
2971         uint64_t target_filepos;
2972         mkv_index_t *index = NULL;
2973         int i;
2974 
2975         if (mkv_d->indexes == NULL) {   /* no index was found *//* I'm lazy... */
2976             mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
2977             return;
2978         }
2979 
2980         target_filepos = (uint64_t) (demuxer->movi_end * rel_seek_secs);
2981         for (i = 0; i < mkv_d->num_indexes; i++)
2982             if (mkv_d->indexes[i].tnum == demuxer->video->id)
2983                 if ((index == NULL)
2984                     || ((mkv_d->indexes[i].filepos >= target_filepos)
2985                         && ((index->filepos < target_filepos)
2986                             || (mkv_d->indexes[i].filepos < index->filepos))))
2987                     index = &mkv_d->indexes[i];
2988 
2989         if (!index)
2990             return;
2991 
2992         mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
2993         stream_seek(s, index->filepos);
2994 
2995         if (demuxer->video->id >= 0)
2996             mkv_d->v_skip_to_keyframe = 1;
2997         mkv_d->skip_to_timecode = index->timecode;
2998         mkv_d->a_skip_to_keyframe = 1;
2999 
3000         demux_mkv_fill_buffer(demuxer, NULL);
3001     }
3002 }
3003 
demux_mkv_control(demuxer_t * demuxer,int cmd,void * arg)3004 static int demux_mkv_control(demuxer_t *demuxer, int cmd, void *arg)
3005 {
3006     mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3007 
3008     switch (cmd) {
3009     case DEMUXER_CTRL_CORRECT_PTS:
3010         return DEMUXER_CTRL_OK;
3011     case DEMUXER_CTRL_GET_TIME_LENGTH:
3012         if (mkv_d->duration == 0)
3013             return DEMUXER_CTRL_DONTKNOW;
3014 
3015         *((double *) arg) = (double) mkv_d->duration;
3016         return DEMUXER_CTRL_OK;
3017 
3018     case DEMUXER_CTRL_GET_PERCENT_POS:
3019         if (mkv_d->duration == 0) {
3020             return DEMUXER_CTRL_DONTKNOW;
3021         }
3022 
3023         *((int *) arg) = (int) (100 * mkv_d->last_pts / mkv_d->duration);
3024         return DEMUXER_CTRL_OK;
3025 
3026     case DEMUXER_CTRL_SWITCH_AUDIO:
3027         if (demuxer->audio && demuxer->audio->sh) {
3028             sh_audio_t *sh = demuxer->a_streams[demuxer->audio->id];
3029             int aid = *(int *) arg;
3030             if (aid < 0)
3031                 aid = (sh->aid + 1) % mkv_d->last_aid;
3032             if (aid != sh->aid) {
3033                 mkv_track_t *track =
3034                     demux_mkv_find_track_by_num(mkv_d, aid,
3035                                                 MATROSKA_TRACK_AUDIO);
3036                 if (track) {
3037                     demuxer->audio->id = track->tnum;
3038                     sh = demuxer->a_streams[demuxer->audio->id];
3039                     ds_free_packs(demuxer->audio);
3040                 }
3041             }
3042             *(int *) arg = sh->aid;
3043         } else
3044             *(int *) arg = -2;
3045         return DEMUXER_CTRL_OK;
3046 
3047     default:
3048         return DEMUXER_CTRL_NOTIMPL;
3049     }
3050 }
3051 
3052 const demuxer_desc_t demuxer_desc_matroska = {
3053     "Matroska demuxer",
3054     "mkv",
3055     "Matroska",
3056     "Aurelien Jacobs",
3057     "",
3058     DEMUXER_TYPE_MATROSKA,
3059     1,                          // safe autodetect
3060     demux_mkv_open,
3061     demux_mkv_fill_buffer,
3062     NULL,
3063     demux_close_mkv,
3064     demux_mkv_seek,
3065     demux_mkv_control
3066 };
3067