1 /*
2  * Copyright (C) 2000-2020 the xine project
3  *
4  * This file is part of xine, a free video player.
5  *
6  * xine is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * xine is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
19  *
20  * demultiplexer for matroska streams
21  *
22  * TODO:
23  *   more decoders init
24  *   metadata
25  *   non seekable input plugins support
26  */
27 
28 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif
31 
32 #include <ctype.h>
33 #include <stdio.h>
34 #include <fcntl.h>
35 #include <unistd.h>
36 #include <string.h>
37 #include <stdlib.h>
38 #include <zlib.h>
39 
40 #define LOG_MODULE "demux_matroska"
41 #define LOG_VERBOSE
42 /*
43 #define LOG
44 */
45 
46 #include "group_video.h"
47 
48 #include <xine/xine_internal.h>
49 #include <xine/xineutils.h>
50 #include <xine/demux.h>
51 #include <xine/buffer.h>
52 #include "bswap.h"
53 
54 #include "ebml.h"
55 #include "matroska.h"
56 #include "demux_matroska.h"
57 
58 #define LITERAL_UTF_8_LEN  5
59 #define LITERAL_UTF_8_SIZE 6
60 #define LITERAL_UTF_8     "utf-8"
61 
check_newpts(demux_matroska_t * this,int64_t pts,matroska_track_t * track)62 static void check_newpts (demux_matroska_t *this, int64_t pts,
63                           matroska_track_t *track) {
64   int64_t diff;
65 
66   if ((track->track_type == MATROSKA_TRACK_VIDEO) ||
67       (track->track_type == MATROSKA_TRACK_AUDIO)) {
68 
69     diff = pts - track->last_pts;
70 
71     if (pts && (this->send_newpts || (track->last_pts && llabs(diff)>WRAP_THRESHOLD)) ) {
72       int i;
73 
74       lprintf ("sending newpts %" PRId64 ", diff %" PRId64 ", track %d\n", pts, diff, track->track_num);
75 
76       if (this->buf_flag_seek) {
77         _x_demux_control_newpts(this->stream, pts, BUF_FLAG_SEEK);
78         this->buf_flag_seek = 0;
79       } else {
80         _x_demux_control_newpts(this->stream, pts, 0);
81       }
82 
83       this->send_newpts = 0;
84       for (i = 0; i < this->num_tracks; i++) {
85         this->tracks[i]->last_pts = 0;
86       }
87     } else {
88   #ifdef LOG
89       if (pts)
90         lprintf ("diff %" PRId64 ", track %d\n", diff, track->track_num);
91   #endif
92     }
93 
94     if (pts)
95       track->last_pts = pts;
96   }
97 }
98 
99 /* Add an entry to the top_level element list */
add_top_level_entry(demux_matroska_t * this,off_t pos)100 static int add_top_level_entry (demux_matroska_t *this, off_t pos) {
101   if (this->top_level_list_size == this->top_level_list_max_size) {
102     void *tmp = this->top_level_list;
103     this->top_level_list_max_size += 50;
104     lprintf("top_level_list_max_size: %d\n", this->top_level_list_max_size);
105     this->top_level_list = realloc(this->top_level_list,
106                                    this->top_level_list_max_size * sizeof(off_t));
107     if (this->top_level_list == NULL) {
108       this->top_level_list_max_size = 0;
109       this->top_level_list_size = 0;
110       free(tmp);
111       return 0;
112     }
113   }
114   this->top_level_list[this->top_level_list_size] = pos;
115   this->top_level_list_size++;
116   return 1;
117 }
118 
119 /* Find an entry in the top_level elem list
120  * return
121  *   0: not found
122  *   1: found
123  */
find_top_level_entry(demux_matroska_t * this,off_t pos)124 static int find_top_level_entry (demux_matroska_t *this, off_t pos) {
125   int i;
126 
127   for (i = 0; i < this->top_level_list_size; i++) {
128     if (this->top_level_list[i] == pos)
129       return 1;
130   }
131   return 0;
132 }
133 
134 
parse_info(demux_matroska_t * this)135 static int parse_info(demux_matroska_t *this) {
136   ebml_parser_t *ebml = this->ebml;
137   int next_level = 2;
138   double duration = 0.0; /* in matroska unit */
139 
140   while (next_level == 2) {
141     ebml_elem_t elem;
142 
143     if (!ebml_read_elem_head(ebml, &elem))
144       return 0;
145 
146     switch (elem.id) {
147       case MATROSKA_ID_I_TIMECODESCALE:
148         lprintf("timecode_scale\n");
149         if (!ebml_read_uint(ebml, &elem, &this->timecode_scale))
150           return 0;
151         break;
152 
153       case MATROSKA_ID_I_DURATION:
154         lprintf("duration\n");
155         if (!ebml_read_float(ebml, &elem, &duration))
156           return 0;
157         break;
158 
159       case MATROSKA_ID_I_TITLE:
160         lprintf("title\n");
161         if (NULL != this->title)
162           free(this->title);
163 
164         this->title = ebml_alloc_read_ascii(ebml, &elem);
165         _x_meta_info_set_utf8(this->stream, XINE_META_INFO_TITLE, this->title);
166         break;
167 
168       default:
169         lprintf("Unhandled ID: 0x%x\n", elem.id);
170         if (!ebml_skip(ebml, &elem))
171           return 0;
172     }
173     next_level = ebml_get_next_level(ebml, &elem);
174   }
175   if (this->timecode_scale == 0) {
176     this->timecode_scale = 1000000;
177   }
178   this->duration = (int)(duration * (double)this->timecode_scale / 1000000.0);
179   lprintf("timecode_scale: %" PRId64 "\n", this->timecode_scale);
180   lprintf("duration: %d\n", this->duration);
181   lprintf("title: %s\n", (NULL != this->title ? this->title : "(none)"));
182 
183   return 1;
184 }
185 
186 
parse_video_track(demux_matroska_t * this,matroska_video_track_t * vt)187 static int parse_video_track (demux_matroska_t *this, matroska_video_track_t *vt) {
188   ebml_parser_t *ebml = this->ebml;
189   int this_level = ebml->level;
190   int next_level = this_level;
191   uint64_t val;
192 
193   while (next_level == this_level) {
194     ebml_elem_t elem;
195 
196     if (!ebml_read_elem_head(ebml, &elem))
197       return 0;
198 
199     switch (elem.id) {
200       case MATROSKA_ID_TV_FLAGINTERLACED:
201         lprintf("MATROSKA_ID_TV_FLAGINTERLACED\n");
202         if (!ebml_read_uint(ebml, &elem, &val))
203           return 0;
204         vt->flag_interlaced = val;
205         break;
206       case MATROSKA_ID_TV_PIXELWIDTH:
207         lprintf("MATROSKA_ID_TV_PIXELWIDTH\n");
208         if (!ebml_read_uint(ebml, &elem, &val))
209           return 0;
210         vt->pixel_width = val;
211         break;
212       case MATROSKA_ID_TV_PIXELHEIGHT:
213         lprintf("MATROSKA_ID_TV_PIXELHEIGHT\n");
214         if (!ebml_read_uint(ebml, &elem, &val))
215           return 0;
216         vt->pixel_height = val;
217         break;
218       case MATROSKA_ID_TV_VIDEODISPLAYWIDTH:
219         lprintf("MATROSKA_ID_TV_VIDEODISPLAYWIDTH\n");
220         if (!ebml_read_uint(ebml, &elem, &val))
221           return 0;
222         vt->display_width = val;
223         break;
224       case MATROSKA_ID_TV_VIDEODISPLAYHEIGHT:
225         lprintf("MATROSKA_ID_TV_VIDEODISPLAYHEIGHT\n");
226         if (!ebml_read_uint(ebml, &elem, &val))
227           return 0;
228         vt->display_height = val;
229         break;
230       default:
231         lprintf("Unhandled ID: 0x%x\n", elem.id);
232         if (!ebml_skip(ebml, &elem))
233           return 0;
234     }
235     next_level = ebml_get_next_level(ebml, &elem);
236   }
237   return 1;
238 }
239 
240 
parse_audio_track(demux_matroska_t * this,matroska_audio_track_t * at)241 static int parse_audio_track (demux_matroska_t *this, matroska_audio_track_t *at) {
242   ebml_parser_t *ebml = this->ebml;
243   int this_level = ebml->level;
244   int next_level = this_level;
245 
246   while (next_level == this_level) {
247     ebml_elem_t elem;
248     uint64_t    val;
249     double      fval;
250 
251     if (!ebml_read_elem_head(ebml, &elem))
252       return 0;
253 
254     switch (elem.id) {
255       case MATROSKA_ID_TA_SAMPLINGFREQUENCY:
256         lprintf("MATROSKA_ID_TA_SAMPLINGFREQUENCY\n");
257         if (!ebml_read_float(ebml, &elem, &fval))
258           return 0;
259         at->sampling_freq = (int)fval;
260         break;
261       case MATROSKA_ID_TA_OUTPUTSAMPLINGFREQUENCY:
262         lprintf("MATROSKA_ID_TA_OUTPUTSAMPLINGFREQUENCY\n");
263         if (!ebml_read_float(ebml, &elem, &fval))
264           return 0;
265         at->output_sampling_freq = (int)fval;
266         break;
267       case MATROSKA_ID_TA_CHANNELS:
268         lprintf("MATROSKA_ID_TA_CHANNELS\n");
269         if (!ebml_read_uint(ebml, &elem, &val))
270           return 0;
271         at->channels = val;
272         break;
273       case MATROSKA_ID_TA_BITDEPTH:
274         lprintf("MATROSKA_ID_TA_BITDEPTH\n");
275         if (!ebml_read_uint(ebml, &elem, &val))
276           return 0;
277         at->bits_per_sample = val;
278         break;
279       default:
280         lprintf("Unhandled ID: 0x%x\n", elem.id);
281         if (!ebml_skip(ebml, &elem))
282           return 0;
283     }
284     next_level = ebml_get_next_level(ebml, &elem);
285   }
286   return 1;
287 }
288 
289 
parse_content_compression(demux_matroska_t * this,matroska_track_t * track)290 static int parse_content_compression (demux_matroska_t *this, matroska_track_t *track) {
291   ebml_parser_t *ebml = this->ebml;
292   int this_level = ebml->level;
293   int next_level = this_level;
294 
295   while (next_level == this_level) {
296     ebml_elem_t elem;
297     uint64_t    val;
298 
299     if (!ebml_read_elem_head(ebml, &elem))
300       return 0;
301 
302     switch (elem.id) {
303       case MATROSKA_ID_CE_COMPALGO:
304         lprintf("ContentCompAlgo\n");
305         if (!ebml_read_uint(ebml, &elem, &val))
306           return 0;
307         switch (val)
308         {
309           case MATROSKA_COMPRESS_ZLIB:
310           case MATROSKA_COMPRESS_BZLIB:
311           case MATROSKA_COMPRESS_LZO1X:
312           case MATROSKA_COMPRESS_HEADER_STRIP:
313             track->compress_algo = val;
314             break;
315           default:
316             track->compress_algo = MATROSKA_COMPRESS_UNKNOWN;
317             break;
318         }
319         break;
320       case MATROSKA_ID_CE_COMPSETTINGS:
321         lprintf("ContentCompSettings\n");
322         track->compress_settings = calloc(1, elem.len);
323         track->compress_len = elem.len;
324         if (elem.len > this->compress_maxlen)
325 		this->compress_maxlen = elem.len;
326         if(!ebml_read_binary(ebml, &elem, track->compress_settings))
327           return 0;
328         break;
329       default:
330         lprintf("Unhandled ID: 0x%x\n", elem.id);
331         if (!ebml_skip(ebml, &elem))
332           return 0;
333     }
334     next_level = ebml_get_next_level(ebml, &elem);
335   }
336   return 1;
337 }
338 
339 
parse_content_encoding(demux_matroska_t * this,matroska_track_t * track)340 static int parse_content_encoding (demux_matroska_t *this, matroska_track_t *track) {
341   ebml_parser_t *ebml = this->ebml;
342   int this_level = ebml->level;
343   int next_level = this_level;
344 
345   while (next_level == this_level) {
346     ebml_elem_t elem;
347     uint64_t    val;
348 
349     if (!ebml_read_elem_head(ebml, &elem))
350       return 0;
351 
352     switch (elem.id) {
353       case MATROSKA_ID_CE_ORDER:
354         lprintf("ContentEncodingOrder\n");
355         if (!ebml_read_uint(ebml, &elem, &val))
356           return 0;
357         if (val != 0) {  // multiple content encoding isn't supported
358           lprintf("   warning: a non-zero encoding order is UNSUPPORTED\n");
359           return 0;
360         }
361         break;
362       case MATROSKA_ID_CE_SCOPE:
363         lprintf("ContentEncodingScope\n");
364         if (!ebml_read_uint(ebml, &elem, &val))
365           return 0;
366         if (val != 1) {  // 1 (all frame contents) is the only supported option
367           lprintf("   warning: UNSUPPORTED encoding scope (%" PRId64 ")\n", val);
368           return 0;
369         }
370         break;
371       case MATROSKA_ID_CE_TYPE:
372         lprintf("ContentEncodingType\n");
373         if (!ebml_read_uint(ebml, &elem, &val))
374           return 0;
375         if (val != 0)  // only compression (0) is supported
376           return 0;
377         break;
378       case MATROSKA_ID_CE_COMPRESSION:
379         lprintf("ContentCompression\n");
380         if (!ebml_read_master (ebml, &elem))
381           return 0;
382 	track->compress_algo = 0; /* default */
383         if ((elem.len > 0) && !parse_content_compression(this, track))
384           return 0;
385         break;
386       case MATROSKA_ID_CE_ENCRYPTION:
387         lprintf("ContentEncryption (UNSUPPORTED)\n");
388         if (!ebml_skip(ebml, &elem))
389           return 0;
390         break;
391       default:
392         lprintf("Unhandled ID: 0x%x\n", elem.id);
393         if (!ebml_skip(ebml, &elem))
394           return 0;
395     }
396     next_level = ebml_get_next_level(ebml, &elem);
397   }
398   return 1;
399 }
400 
401 
parse_content_encodings(demux_matroska_t * this,matroska_track_t * track)402 static int parse_content_encodings (demux_matroska_t *this, matroska_track_t *track) {
403   ebml_parser_t *ebml = this->ebml;
404   int this_level = ebml->level;
405   int next_level = this_level;
406 
407   while (next_level == this_level) {
408     ebml_elem_t elem;
409 
410     if (!ebml_read_elem_head(ebml, &elem))
411       return 0;
412 
413     switch (elem.id) {
414       case MATROSKA_ID_CONTENTENCODING:
415         lprintf("ContentEncoding\n");
416         if (!ebml_read_master (ebml, &elem))
417           return 0;
418         if ((elem.len > 0) && !parse_content_encoding(this, track))
419           return 0;
420         break;
421       default:
422         lprintf("Unhandled ID: 0x%x\n", elem.id);
423         if (!ebml_skip(ebml, &elem))
424           return 0;
425     }
426     next_level = ebml_get_next_level(ebml, &elem);
427   }
428   return 1;
429 }
430 
431 
init_codec_video(demux_matroska_t * this,matroska_track_t * track)432 static void init_codec_video(demux_matroska_t *this, matroska_track_t *track) {
433   buf_element_t *buf;
434 
435   buf = track->fifo->buffer_pool_size_alloc (track->fifo, track->codec_private_len);
436 
437   if (track->codec_private_len > (unsigned int)(buf->max_size)) {
438     xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
439             "demux_matroska: private decoder data length (%d) is greater than fifo buffer length (%" PRId32 ")\n",
440              track->codec_private_len, buf->max_size);
441     buf->free_buffer(buf);
442     return;
443   }
444   buf->size          = track->codec_private_len;
445   buf->decoder_flags = BUF_FLAG_HEADER | BUF_FLAG_STDHEADER | BUF_FLAG_FRAME_END;
446   buf->type          = track->buf_type;
447   buf->pts           = 0;
448 
449   if (buf->size)
450     xine_fast_memcpy (buf->content, track->codec_private, buf->size);
451 
452   if(track->default_duration) {
453     buf->decoder_flags   |= BUF_FLAG_FRAMERATE;
454     buf->decoder_info[0]  = (int64_t)track->default_duration *
455                             (int64_t)90 / (int64_t)1000000;
456   }
457 
458   if(track->video_track && track->video_track->display_width &&
459      track->video_track->display_height) {
460     buf->decoder_flags   |= BUF_FLAG_ASPECT;
461     buf->decoder_info[1]  = track->video_track->display_width;
462     buf->decoder_info[2]  = track->video_track->display_height;
463   }
464 
465   track->fifo->put (track->fifo, buf);
466 }
467 
468 
init_codec_audio(demux_matroska_t * this,matroska_track_t * track)469 static void init_codec_audio(demux_matroska_t *this, matroska_track_t *track) {
470   buf_element_t *buf;
471 
472   /* Standard head shall either be empty, or contain a xine_waveformatex struct,
473    * optioally appended by codec private data. Unfortunatly, we have no format tag
474    * for Opus. Thus, send private data as a second buf. */
475   buf = track->fifo->buffer_pool_size_alloc (track->fifo, 0);
476   buf->size = 0;
477   /* default param */
478   buf->decoder_info[0] = 0;
479   buf->decoder_info[1] = 44100;
480   buf->decoder_info[2] = 16;
481   buf->decoder_info[3] = 2;
482   /* track param */
483   if (track->audio_track) {
484     if (track->audio_track->sampling_freq)
485       buf->decoder_info[1] = track->audio_track->sampling_freq;
486     if (track->audio_track->bits_per_sample)
487       buf->decoder_info[2] = track->audio_track->bits_per_sample;
488     if (track->audio_track->channels)
489       buf->decoder_info[3] = track->audio_track->channels;
490   }
491   lprintf ("%d Hz, %d bits, %d channels\n", buf->decoder_info[1],
492     buf->decoder_info[2], buf->decoder_info[3]);
493   buf->type          = track->buf_type;
494   buf->decoder_flags = BUF_FLAG_HEADER | BUF_FLAG_STDHEADER | BUF_FLAG_FRAME_END;
495   buf->pts           = 0;
496   track->fifo->put (track->fifo, buf);
497 
498   if (track->codec_private_len > 0) {
499     buf = track->fifo->buffer_pool_size_alloc (track->fifo, track->codec_private_len);
500     if (track->codec_private_len > (unsigned int)buf->max_size) {
501       xprintf (this->stream->xine, XINE_VERBOSITY_LOG,
502         "demux_matroska: private decoder data length (%d) is greater than fifo buffer length (%d).\n",
503         track->codec_private_len, buf->max_size);
504       buf->free_buffer (buf);
505     } else {
506       memcpy (buf->content, track->codec_private, track->codec_private_len);
507       buf->decoder_info_ptr[2] = buf->content;
508       buf->decoder_info[2]     = track->codec_private_len;
509       buf->type                = track->buf_type;
510       buf->decoder_flags       = BUF_FLAG_HEADER | BUF_FLAG_SPECIAL;
511       buf->decoder_info[1]     = BUF_SPECIAL_DECODER_CONFIG;
512       buf->pts                 = 0;
513       track->fifo->put (track->fifo, buf);
514     }
515   }
516 }
517 
init_codec_real(demux_matroska_t * this,matroska_track_t * track)518 static void init_codec_real(demux_matroska_t *this, matroska_track_t * track) {
519   buf_element_t *buf;
520 
521   buf = track->fifo->buffer_pool_size_alloc (track->fifo, track->codec_private_len);
522 
523   if (track->codec_private_len > (unsigned int)buf->max_size) {
524     xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
525             "demux_matroska: private decoder data length (%d) is greater than fifo buffer length (%" PRId32 ")\n",
526              track->codec_private_len, buf->max_size);
527     buf->free_buffer(buf);
528     return;
529   }
530 
531   buf->size          = track->codec_private_len;
532   buf->decoder_flags = BUF_FLAG_HEADER | BUF_FLAG_FRAME_END;
533   buf->type          = track->buf_type;
534   buf->pts           = 0;
535 
536   if (buf->size)
537     xine_fast_memcpy (buf->content, track->codec_private, buf->size);
538 
539   if(track->default_duration) {
540     buf->decoder_flags   |= BUF_FLAG_FRAMERATE;
541     buf->decoder_info[0]  = (int64_t)track->default_duration *
542                             (int64_t)90 / (int64_t)1000000;
543   }
544 
545   if(track->video_track && track->video_track->display_width &&
546      track->video_track->display_height) {
547     buf->decoder_flags   |= BUF_FLAG_ASPECT;
548     buf->decoder_info[1]  = track->video_track->display_width;
549     buf->decoder_info[2]  = track->video_track->display_height;
550   }
551 
552   track->fifo->put (track->fifo, buf);
553 }
554 
init_codec_xiph(demux_matroska_t * this,matroska_track_t * track)555 static void init_codec_xiph(demux_matroska_t *this, matroska_track_t *track) {
556   buf_element_t *buf;
557   uint8_t nb_lace;
558   int frame[3];
559   int i;
560   uint8_t *data;
561 
562   if (track->codec_private_len < 3)
563     return;
564   nb_lace = track->codec_private[0];
565   if (nb_lace != 2)
566     return;
567 
568   frame[0] = track->codec_private[1];
569   frame[1] = track->codec_private[2];
570   frame[2] = track->codec_private_len - frame[0] - frame[1] - 3;
571   if (frame[2] < 0)
572     return;
573 
574   data = track->codec_private + 3;
575   for (i = 0; i < 3; i++) {
576     buf = track->fifo->buffer_pool_size_alloc (track->fifo, frame[i]);
577 
578     if (frame[i] > buf->max_size) {
579       xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
580               "demux_matroska: private decoder data length (%d) is greater than fifo buffer length (%" PRId32 ")\n",
581               frame[i], buf->max_size);
582       buf->free_buffer(buf);
583       return;
584     }
585     buf->size = frame[i];
586 
587     buf->decoder_flags = BUF_FLAG_HEADER | BUF_FLAG_FRAME_START | BUF_FLAG_FRAME_END;
588     buf->type          = track->buf_type;
589     buf->pts           = 0;
590 
591     xine_fast_memcpy (buf->content, data, buf->size);
592     data += buf->size;
593 
594     track->fifo->put (track->fifo, buf);
595   }
596 }
597 
598 
aac_get_sr_index(uint32_t sample_rate)599 static int aac_get_sr_index (uint32_t sample_rate) {
600   if (92017 <= sample_rate)
601     return 0;
602   else if (75132 <= sample_rate)
603     return 1;
604   else if (55426 <= sample_rate)
605     return 2;
606   else if (46009 <= sample_rate)
607     return 3;
608   else if (37566 <= sample_rate)
609     return 4;
610   else if (27713 <= sample_rate)
611     return 5;
612   else if (23004 <= sample_rate)
613     return 6;
614   else if (18783 <= sample_rate)
615     return 7;
616   else if (13856 <= sample_rate)
617     return 8;
618   else if (11502 <= sample_rate)
619     return 9;
620   else if (9391 <= sample_rate)
621     return 10;
622   else
623     return 11;
624 }
625 
626 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
init_codec_aac(demux_matroska_t * this,matroska_track_t * track)627 static void init_codec_aac(demux_matroska_t *this, matroska_track_t *track) {
628   matroska_audio_track_t *atrack = track->audio_track;
629   buf_element_t *buf;
630   int profile;
631   int sr_index;
632 
633   (void)this;
634 
635   /* Create a DecoderSpecificInfo for initialising libfaad */
636   sr_index = aac_get_sr_index(atrack->sampling_freq);
637   /* newer specification with appended CodecPrivate */
638   if (strlen(track->codec_id) <= 12)
639     profile = 3;
640   /* older specification */
641   else if (!strncmp (&track->codec_id[12], "MAIN", 4))
642     profile = 0;
643   else if (!strncmp (&track->codec_id[12], "LC", 2))
644     profile = 1;
645   else if (!strncmp (&track->codec_id[12], "SSR", 3))
646     profile = 2;
647   else
648     profile = 3;
649 
650   buf = track->fifo->buffer_pool_alloc (track->fifo);
651 
652   buf->size = 0;
653   buf->type = track->buf_type;
654   buf->pts = 0;
655 
656   buf->decoder_flags = BUF_FLAG_SPECIAL|BUF_FLAG_HEADER;
657   buf->decoder_info[1] = BUF_SPECIAL_DECODER_CONFIG;
658   buf->decoder_info_ptr[2] = buf->mem;
659 
660   buf->mem[0] = ((profile + 1) << 3) | ((sr_index & 0x0e) >> 1);
661   buf->mem[1] = ((sr_index & 0x01) << 7) | (atrack->channels << 3);
662 
663   if (strstr(track->codec_id, "SBR") == NULL)
664     buf->decoder_info[2] = 2;
665   else {
666     /* HE-AAC (aka SBR AAC) */
667     sr_index = aac_get_sr_index(atrack->sampling_freq*2);
668     buf->mem[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
669     buf->mem[3] = ((AAC_SYNC_EXTENSION_TYPE & 0x07) << 5) | 5;
670     buf->mem[4] = (1 << 7) | (sr_index << 3);
671 
672     buf->decoder_info[2] = 5;
673   }
674 
675   track->fifo->put(track->fifo, buf);
676 }
677 
678 
vobsub_parse_size(matroska_track_t * t,const char * start)679 static int vobsub_parse_size(matroska_track_t *t, const char *start) {
680   if (sscanf(&start[6], "%dx%d", &t->sub_track->width,
681              &t->sub_track->height) == 2) {
682     lprintf("VobSub size: %ux%u\n", t->sub_track->width, t->sub_track->height);
683     return 1;
684   }
685   return 0;
686 }
687 
vobsub_parse_palette(matroska_track_t * t,const char * start)688 static int vobsub_parse_palette(matroska_track_t *t, const char *start) {
689   int i, r, g, b, y, u, v;
690   unsigned tmp;
691 
692   start += 8;
693   while (isspace(*start))
694     start++;
695   for (i = 0; i < 16; i++) {
696     if (sscanf(start, "%06x", &tmp) != 1)
697       break;
698     r = tmp >> 16 & 0xff;
699     g = tmp >> 8 & 0xff;
700     b = tmp & 0xff;
701     y = MIN(MAX((int)(0.1494 * r + 0.6061 * g + 0.2445 * b), 0), 0xff);
702     u = MIN(MAX((int)(0.6066 * r - 0.4322 * g - 0.1744 * b) + 128, 0), 0xff);
703     v = MIN(MAX((int)(-0.08435 * r - 0.3422 * g + 0.4266 * b) + 128, 0), 0xff);
704     t->sub_track->palette[i] = y << 16 | u << 8 | v;
705     start += 6;
706     while ((*start == ',') || isspace(*start))
707       start++;
708   }
709   if (i == 16) {
710     lprintf("VobSub palette: %06x,%06x,%06x,%06x,%06x,%06x,%06x,%06x,%06x,"
711             "%06x,%06x,%06x,%06x,%06x,%06x,%06x\n", t->sub_track->palette[0],
712             t->sub_track->palette[1], t->sub_track->palette[2],
713             t->sub_track->palette[3], t->sub_track->palette[4],
714             t->sub_track->palette[5], t->sub_track->palette[6],
715             t->sub_track->palette[7], t->sub_track->palette[8],
716             t->sub_track->palette[9], t->sub_track->palette[10],
717             t->sub_track->palette[11], t->sub_track->palette[12],
718             t->sub_track->palette[13], t->sub_track->palette[14],
719             t->sub_track->palette[15]);
720     return 2;
721   }
722   return 0;
723 }
724 
vobsub_parse_custom_colors(matroska_track_t * t,const char * start)725 static int vobsub_parse_custom_colors(matroska_track_t *t, const char *start) {
726   int use_custom_colors, i;
727 
728   start += 14;
729   while (isspace(*start))
730     start++;
731   use_custom_colors = 0;
732   if (!strncasecmp(start, "ON", 2) || (*start == '1'))
733     use_custom_colors = 1;
734   else if (!strncasecmp(start, "OFF", 3) || (*start == '0'))
735     use_custom_colors = 0;
736   lprintf("VobSub custom colours: %s\n", use_custom_colors ? "ON" : "OFF");
737   if ((start = strstr(start, "colors:")) != NULL) {
738     start += 7;
739     while (isspace(*start))
740       start++;
741     for (i = 0; i < 4; i++) {
742       if (sscanf(start, "%06x", &t->sub_track->colors[i]) != 1)
743         break;
744       start += 6;
745       while ((*start == ',') || isspace(*start))
746         start++;
747     }
748     if (i == 4) {
749       t->sub_track->custom_colors = 4;
750       lprintf("VobSub colours: %06x,%06x,%06x,%06x\n", t->sub_track->colors[0],
751               t->sub_track->colors[1], t->sub_track->colors[2],
752               t->sub_track->colors[3]);
753     }
754   }
755   if (!use_custom_colors)
756     t->sub_track->custom_colors = 0;
757   return 4;
758 }
759 
vobsub_parse_forced_subs(matroska_track_t * t,const char * start)760 static int vobsub_parse_forced_subs(matroska_track_t *t, const char *start) {
761   start += 12;
762   while (isspace(*start))
763     start++;
764   if (!strncasecmp(start, "on", 2) || (*start == '1'))
765     t->sub_track->forced_subs_only = 1;
766   else if (!strncasecmp(start, "off", 3) || (*start == '0'))
767     t->sub_track->forced_subs_only = 0;
768   else
769     return 0;
770   lprintf("VobSub forced subs: %d\n", t->sub_track->forced_subs_only);
771   return 8;
772 }
773 
init_codec_vobsub(demux_matroska_t * this,matroska_track_t * track)774 static void init_codec_vobsub(demux_matroska_t *this,
775                               matroska_track_t *track) {
776   int things_found, last;
777   char *buf, *pos, *start;
778   buf_element_t *buf_el;
779 
780   lprintf("init_codec_vobsub for %d\n", track->track_num);
781 
782   (void)this;
783 
784   if ((track->codec_private == NULL) || (track->codec_private_len == 0))
785     return;
786 
787   track->sub_track = calloc(1, sizeof(matroska_sub_track_t));
788   if (track->sub_track == NULL)
789     return;
790   things_found = 0;
791   buf = (char *)malloc(track->codec_private_len + 1);
792   if (buf == NULL)
793     return;
794   xine_fast_memcpy(buf, track->codec_private, track->codec_private_len);
795   buf[track->codec_private_len] = 0;
796   track->sub_track->type = 'v';
797 
798   pos = buf;
799   start = buf;
800   last = 0;
801 
802   do {
803     if ((*pos == 0) || (*pos == '\r') || (*pos == '\n')) {
804       if (*pos == 0)
805         last = 1;
806       *pos = 0;
807 
808       if (!strncasecmp(start, "size: ", 6))
809         things_found |= vobsub_parse_size(track, start);
810       else if (!strncasecmp(start, "palette:", 8))
811         things_found |= vobsub_parse_palette(track, start);
812       else if (!strncasecmp(start, "custom colours:", 14))
813         things_found |= vobsub_parse_custom_colors(track, start);
814       else if (!strncasecmp(start, "forced subs:", 12))
815         things_found |= vobsub_parse_forced_subs(track, start);
816 
817       if (last)
818         break;
819       do {
820         pos++;
821       } while ((*pos == '\r') || (*pos == '\n'));
822       start = pos;
823     } else
824       pos++;
825   } while (!last && (*start != 0));
826 
827   free(buf);
828 
829   if ((things_found & 2) == 2) {
830     buf_el = track->fifo->buffer_pool_alloc(track->fifo);
831     xine_fast_memcpy(buf_el->content, track->sub_track->palette,
832                      16 * sizeof(uint32_t));
833     buf_el->type = BUF_SPU_DVD;
834     buf_el->decoder_flags |= BUF_FLAG_SPECIAL;
835     buf_el->decoder_info[1] = BUF_SPECIAL_SPU_DVD_SUBTYPE;
836     buf_el->decoder_info[2] = SPU_DVD_SUBTYPE_CLUT;
837     track->fifo->put(track->fifo, buf_el);
838   }
839 }
840 
init_codec_dvbsub(demux_matroska_t * this,matroska_track_t * track)841 static void init_codec_dvbsub(demux_matroska_t *this, matroska_track_t *track) {
842   buf_element_t *buf;
843   spu_dvb_descriptor_t *desc;
844 
845   (void)this;
846 
847   if (!track->codec_private || track->codec_private_len < 4)
848     return;
849 
850   buf = track->fifo->buffer_pool_alloc (track->fifo);
851 
852   desc = (spu_dvb_descriptor_t *)buf->mem;
853   memset(desc, 0, sizeof(*desc));
854   desc->comp_page_id = _X_BE_16(track->codec_private);
855   desc->aux_page_id  = _X_BE_16(track->codec_private + 2);
856 
857   buf->type = track->buf_type;
858   buf->decoder_flags = BUF_FLAG_SPECIAL;
859   buf->decoder_info[1] = BUF_SPECIAL_SPU_DVB_DESCRIPTOR;
860   buf->decoder_info[2] = sizeof(*desc);
861   buf->decoder_info_ptr[2] = desc;
862 
863   track->fifo->put (track->fifo, buf);
864 }
865 
866 
init_codec_spu(demux_matroska_t * this,matroska_track_t * track)867 static void init_codec_spu(demux_matroska_t *this, matroska_track_t *track) {
868   buf_element_t *buf;
869 
870   (void)this;
871 
872   buf = track->fifo->buffer_pool_alloc (track->fifo);
873   buf->type = track->buf_type;
874 
875   track->fifo->put (track->fifo, buf);
876 }
877 
handle_realvideo(demux_plugin_t * this_gen,matroska_track_t * track,int decoder_flags,uint8_t * data,size_t data_len,int64_t data_pts,int data_duration,int input_normpos,int input_time)878 static void handle_realvideo (demux_plugin_t *this_gen, matroska_track_t *track,
879                               int decoder_flags,
880                               uint8_t *data, size_t data_len,
881                               int64_t data_pts, int data_duration,
882                               int input_normpos, int input_time) {
883   demux_matroska_t *this = (demux_matroska_t *) this_gen;
884   int chunks;
885   int chunk_tab_size;
886 
887   if (data_len < 1)
888     return;
889 
890   chunks = data[0];
891   chunk_tab_size = (chunks + 1) * 8;
892 
893   if ((int)data_len - 1 < chunk_tab_size)
894     return;
895 
896   lprintf("chunks: %d, chunk_tab_size: %d\n", chunks, chunk_tab_size);
897 
898   _x_demux_send_data(track->fifo,
899                      data + chunk_tab_size + 1,
900                      data_len - chunk_tab_size - 1,
901                      data_pts, track->buf_type, decoder_flags,
902                      input_normpos, input_time,
903                      this->duration, 0);
904 
905   /* sends the fragment table */
906   {
907     buf_element_t *buf;
908 
909     buf = track->fifo->buffer_pool_size_alloc(track->fifo, chunk_tab_size);
910 
911     if (chunk_tab_size > buf->max_size) {
912       xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
913               "demux_matroska: Real Chunk Table length (%d) is greater than fifo buffer length (%" PRId32 ")\n",
914               chunk_tab_size, buf->max_size);
915       buf->free_buffer(buf);
916       return;
917     }
918     buf->decoder_flags = decoder_flags | BUF_FLAG_SPECIAL | BUF_FLAG_FRAMERATE;
919     buf->decoder_info[0] = data_duration;
920     buf->decoder_info[1] = BUF_SPECIAL_RV_CHUNK_TABLE;
921     buf->decoder_info[2] = chunks;
922     buf->decoder_info_ptr[2] = buf->content;
923 
924     buf->type = track->buf_type;
925 
926     xine_fast_memcpy(buf->decoder_info_ptr[2], data + 1, chunk_tab_size);
927 
928     track->fifo->put(track->fifo, buf);
929   }
930 }
931 
handle_sub_ssa(demux_plugin_t * this_gen,matroska_track_t * track,int decoder_flags,uint8_t * data,size_t data_len,int64_t data_pts,int data_duration,int input_normpos,int input_time)932 static void handle_sub_ssa (demux_plugin_t *this_gen, matroska_track_t *track,
933                             int decoder_flags,
934                             uint8_t *data, size_t data_len,
935                             int64_t data_pts, int data_duration,
936                             int input_normpos, int input_time) {
937   buf_element_t *buf;
938   uint32_t *val;
939   int commas = 0;
940   int lines = 1;
941   char last_char = 0;
942   char *dest;
943   int dest_len;
944   int skip = 0;
945 
946   lprintf ("pts: %" PRId64 ", duration: %d\n", data_pts, data_duration);
947   (void)this_gen;
948 
949   /* skip ',' */
950   while (data_len && (commas < 8)) {
951     if (*data == ',') commas++;
952     data++; data_len--;
953   }
954 
955   buf = track->fifo->buffer_pool_size_alloc(track->fifo, data_len + 8 + LITERAL_UTF_8_SIZE);
956   buf->type = track->buf_type;
957   buf->decoder_flags = decoder_flags | BUF_FLAG_SPECIAL;
958   buf->decoder_info[1] = BUF_SPECIAL_CHARSET_ENCODING;
959   buf->decoder_info_ptr[2] = buf->content + buf->max_size - LITERAL_UTF_8_SIZE;
960   buf->decoder_info[2] = LITERAL_UTF_8_LEN;
961 
962   memcpy(buf->decoder_info_ptr[2], "utf-8", LITERAL_UTF_8_SIZE);
963 
964   val = (uint32_t *)buf->content;
965   *val++ = data_pts / 90;                    /* start time */
966   *val++ = (data_pts + data_duration) / 90;  /* end time   */
967 
968   dest = buf->content + 8;
969   dest_len = buf->max_size - 8 - LITERAL_UTF_8_SIZE;
970 
971   while (data_len && dest_len) {
972     if (skip) {
973       if (*data == '}')
974         skip--;
975       else if (*data == '{')
976         skip++;
977     } else {
978       if ((last_char == '\\') && ((*data == 'n') || (*data == 'N'))) {
979         lines++;
980         *dest = '\n';
981         dest++; dest_len--;
982       } else {
983         if (*data != '\\') {
984           if (*data == '{') {
985             skip++;
986           } else {
987             *dest = *data;
988             dest++; dest_len--;
989           }
990         }
991       }
992     }
993 
994     last_char = *data;
995     data++; data_len--;
996   }
997 
998   if (dest_len) {
999 
1000     *dest = '\0'; dest++; dest_len--;
1001     buf->size = dest - (char *)buf->content;
1002     buf->extra_info->input_normpos = input_normpos;
1003     buf->extra_info->input_time    = input_time;
1004 
1005     track->fifo->put(track->fifo, buf);
1006   } else {
1007     buf->free_buffer(buf);
1008   }
1009 }
1010 
handle_sub_utf8(demux_plugin_t * this_gen,matroska_track_t * track,int decoder_flags,uint8_t * data,size_t data_len,int64_t data_pts,int data_duration,int input_normpos,int input_time)1011 static void handle_sub_utf8 (demux_plugin_t *this_gen, matroska_track_t *track,
1012                              int decoder_flags,
1013                              uint8_t *data, size_t data_len,
1014                              int64_t data_pts, int data_duration,
1015                              int input_normpos, int input_time) {
1016   demux_matroska_t *this = (demux_matroska_t *) this_gen;
1017   buf_element_t *buf;
1018   uint32_t *val;
1019 
1020   buf = track->fifo->buffer_pool_size_alloc(track->fifo, data_len + 9 + LITERAL_UTF_8_SIZE);
1021 
1022   buf->size = data_len + 9;  /* 2 uint32_t + '\0' */
1023 
1024   if (buf->max_size >= buf->size + LITERAL_UTF_8_SIZE) {
1025 
1026     buf->decoder_flags = decoder_flags;
1027     buf->type = track->buf_type;
1028     buf->decoder_flags = decoder_flags | BUF_FLAG_SPECIAL;
1029     buf->decoder_info[1] = BUF_SPECIAL_CHARSET_ENCODING;
1030     buf->decoder_info_ptr[2] = buf->content + buf->max_size - LITERAL_UTF_8_SIZE;
1031     buf->decoder_info[2] = LITERAL_UTF_8_LEN;
1032 
1033     memcpy(buf->decoder_info_ptr[2], "utf-8", LITERAL_UTF_8_SIZE);
1034 
1035     val = (uint32_t *)buf->content;
1036     *val++ = data_pts / 90;                    /* start time */
1037     *val++ = (data_pts + data_duration) / 90;  /* end time   */
1038 
1039     xine_fast_memcpy(buf->content + 8, data, data_len);
1040     buf->content[8 + data_len] = '\0';
1041 
1042     lprintf("sub: %s\n", buf->content + 8);
1043     buf->extra_info->input_normpos = input_normpos;
1044     buf->extra_info->input_time    = input_time;
1045     track->fifo->put(track->fifo, buf);
1046   } else {
1047     xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
1048             "demux_matroska: data length is greater than fifo buffer length\n");
1049     buf->free_buffer(buf);
1050   }
1051 }
1052 
1053 /* 0x02 (not a keyframe) | 0x01 (is visible) */
vp9_frametype(const uint8_t * h)1054 static int vp9_frametype (const uint8_t *h) {
1055   if ((h[0] & 0xc0) != 0x80) /* frame marker missing */
1056     return 1;
1057   if ((h[0] & 0x30) == 0x30) { /* profile 3+ */
1058     if (h[0] & 0x08) /* profile 4+ not supported */
1059       return 0;
1060     if (h[0] & 0x04) /* 3 bits ref */
1061       return 1;
1062     return h[0] & 3;
1063   }
1064   if (h[0] & 0x08) /* 3 bits ref */
1065     return 1;
1066   return (h[0] >> 1) & 3;
1067 }
1068 
handle_vp9(demux_plugin_t * this_gen,matroska_track_t * track,int decoder_flags,uint8_t * data,size_t data_len,int64_t data_pts,int data_duration,int input_normpos,int input_time)1069 static void handle_vp9 (demux_plugin_t *this_gen, matroska_track_t *track, int decoder_flags,
1070   uint8_t *data, size_t data_len, int64_t data_pts, int data_duration, int input_normpos, int input_time) {
1071   (void)this_gen;
1072   /* !@$%*#~ undocumented multiframe feature */
1073   do {
1074     uint8_t mfhead;
1075     uint8_t *l;
1076     int mfframes, i;
1077     size_t mfbytes, mfsize;
1078 
1079     if (!data_len)
1080       return;
1081     mfhead = data[data_len - 1];
1082     if ((mfhead & 0xe0) != 0xc0)
1083       break;
1084     mfframes =  (mfhead & 7) + 1;
1085     mfbytes  = ((mfhead >> 3) & 3) + 1;
1086     mfsize   =   mfframes * mfbytes + 2;
1087     if (mfsize > data_len)
1088       break;
1089     l = data + data_len - mfsize;
1090     if (*l++ != mfhead)
1091       break;
1092     data_len -= mfsize;
1093     data_duration /= mfframes;
1094     for (i = 0; i < mfframes; i++) {
1095       size_t flen = *l++;
1096       if (mfbytes > 1)
1097         flen += (size_t)(*l++) << 8;
1098       if (mfbytes > 2)
1099         flen += (size_t)(*l++) << 16;
1100       if (mfbytes > 3)
1101         flen += (size_t)(*l++) << 24;
1102       if (flen > data_len)
1103         flen = data_len;
1104       if (flen) {
1105         /* Nasty kludge: take invisible frames out of pts sequence.
1106          * A conventional b-frame sequence looks like this:
1107          * I1 P1 B1 B2 B3 P2 B4 ...
1108          * after reordering:
1109          * I1 B1 B2 B3 P1 B4 ... P2
1110          * VP9 now avoids reordering and storing both dts and pts
1111          * by adding "P" as "invisible" to a (multiframe group):
1112          * I1 (P1 B1) B2 B3 (P2 B4) ...
1113          * "B3" usually is very small, and yields a quite verbatim copy of "P1",
1114          * which does not stay completely hidden this way.
1115          */
1116         int64_t pts = data_pts;
1117         int type = vp9_frametype (data);
1118         if (type & 2)
1119           decoder_flags &= ~BUF_FLAG_KEYFRAME;
1120         else
1121           decoder_flags |= BUF_FLAG_KEYFRAME;
1122         if (type & 1) { /* visible */
1123           if (!pts)
1124             pts = track->delayed_pts;
1125           track->delayed_pts = data_pts = 0;
1126         } else { /* invisible */
1127           pts = 0;
1128           track->delayed_pts = data_pts;
1129         }
1130         _x_demux_send_data (track->fifo, data, flen, pts, track->buf_type,
1131           decoder_flags, input_normpos, input_time, data_duration, 0);
1132         data += flen;
1133         data_len -= flen;
1134       }
1135     }
1136     return;
1137   } while (0);
1138 
1139   {
1140     int64_t pts = data_pts;
1141     int type = vp9_frametype (data);
1142     if (type & 2)
1143       decoder_flags &= ~BUF_FLAG_KEYFRAME;
1144     else
1145       decoder_flags |= BUF_FLAG_KEYFRAME;
1146     if (type & 1) { /* visible */
1147       if (!pts)
1148         pts = track->delayed_pts;
1149       track->delayed_pts = data_pts = 0;
1150     } else { /* invisible */
1151       pts = 0;
1152       track->delayed_pts = data_pts;
1153     }
1154     _x_demux_send_data (track->fifo, data, data_len, pts, track->buf_type,
1155       decoder_flags, input_normpos, input_time, data_duration, 0);
1156   }
1157 }
1158 
1159 
uncompress_zlib(demux_matroska_t * this,const uint8_t * data,size_t data_len,uint8_t ** out_data,size_t * out_data_len)1160 static int uncompress_zlib(demux_matroska_t *this,
1161                            const uint8_t *data, size_t data_len, uint8_t **out_data, size_t *out_data_len)
1162 {
1163     z_stream zstream;
1164     uint8_t *dest;
1165     int result;
1166 
1167     *out_data = NULL;
1168 
1169     zstream.zalloc = (alloc_func) 0;
1170     zstream.zfree = (free_func) 0;
1171     zstream.opaque = (voidpf) 0;
1172     if (inflateInit (&zstream) != Z_OK) {
1173       xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
1174               "demux_matroska: zlib inflateInit failed.\n");
1175       return -1;
1176     }
1177     zstream.next_in = (Bytef *)data;
1178     zstream.avail_in = data_len;
1179 
1180     dest = (uint8_t *)malloc(data_len);
1181     zstream.avail_out = data_len;
1182     do {
1183       data_len += 4000;
1184       dest = (uint8_t *)realloc(dest, data_len);
1185       zstream.next_out = (Bytef *)(dest + zstream.total_out);
1186       result = inflate (&zstream, Z_NO_FLUSH);
1187       if ((result != Z_OK) && (result != Z_STREAM_END)) {
1188         xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
1189                 "demux_matroska: zlib decompression failed: %d\n", result);
1190         free(dest);
1191         inflateEnd(&zstream);
1192 	return 0;
1193       }
1194       zstream.avail_out += 4000;
1195     } while ((zstream.avail_out == 4000) &&
1196             (zstream.avail_in != 0) && (result != Z_STREAM_END));
1197 
1198     *out_data = dest;
1199     *out_data_len = zstream.total_out;
1200 
1201     inflateEnd(&zstream);
1202 
1203     return 1;
1204 }
1205 
1206 /* Note: This function assumes that the VobSub track is compressed with zlib.
1207  * This is not necessarily true - or not enough. The Matroska 'content
1208  * encoding' elements allow for a layer of changes applied to the contents,
1209  * e.g. compression or encryption. Anyway, only zlib compression is used
1210  * at the moment, and everyone compresses the VobSubs.
1211  */
handle_vobsub(demux_plugin_t * this_gen,matroska_track_t * track,int decoder_flags,uint8_t * data,size_t data_len,int64_t data_pts,int data_duration,int input_normpos,int input_time)1212 static void handle_vobsub (demux_plugin_t *this_gen, matroska_track_t *track,
1213                            int decoder_flags,
1214                            uint8_t *data, size_t data_len,
1215                            int64_t data_pts, int data_duration,
1216                            int input_normpos, int input_time) {
1217   demux_matroska_t *this = (demux_matroska_t *) this_gen;
1218   buf_element_t *buf;
1219   uint8_t *new_data = NULL;
1220   size_t new_data_len = 0;
1221 
1222   (void)data_duration;
1223 
1224   if (track->compress_algo == MATROSKA_COMPRESS_ZLIB ||
1225       track->compress_algo == MATROSKA_COMPRESS_UNKNOWN) {
1226 
1227     if (uncompress_zlib(this, data, data_len, &new_data, &new_data_len) < 0) {
1228       return;
1229     }
1230 
1231     if (!new_data) {
1232       if (track->compress_algo == MATROSKA_COMPRESS_UNKNOWN) {
1233 	track->compress_algo = MATROSKA_COMPRESS_NONE;
1234 	xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
1235 		"demux_matroska: VobSub: falling back to uncompressed mode.\n");
1236       } else {
1237 	return;
1238       }
1239     } else {
1240       track->compress_algo = MATROSKA_COMPRESS_ZLIB;
1241       data = new_data;
1242       data_len = new_data_len;
1243     }
1244   }
1245   else
1246   {
1247     lprintf("VobSub: track %d isn't compressed (%zu bytes)\n",
1248             (int)track->track_num, data_len);
1249   }
1250 
1251   buf = track->fifo->buffer_pool_size_alloc(track->fifo, data_len);
1252 
1253   if ((size_t)buf->max_size >= data_len) {
1254     buf->decoder_flags = decoder_flags | BUF_FLAG_SPECIAL;
1255     buf->decoder_info[1] = BUF_SPECIAL_SPU_DVD_SUBTYPE;
1256     buf->decoder_info[2] = SPU_DVD_SUBTYPE_VOBSUB_PACKAGE;
1257     buf->type = track->buf_type;
1258     buf->size = data_len;
1259 
1260     xine_fast_memcpy(buf->content, data, data_len);
1261 
1262     buf->extra_info->input_normpos = input_normpos;
1263     buf->extra_info->input_time    = input_time;
1264 
1265     buf->pts = data_pts;
1266     track->fifo->put(track->fifo, buf);
1267 
1268   } else {
1269     xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
1270             "demux_matroska: VobSub: data length is greater than fifo buffer length\n");
1271     buf->free_buffer(buf);
1272   }
1273 
1274   free(new_data);
1275 }
1276 
handle_dvbsub(demux_plugin_t * this_gen,matroska_track_t * track,int decoder_flags,uint8_t * data,size_t data_len,int64_t data_pts,int data_duration,int input_normpos,int input_time)1277 static void handle_dvbsub (demux_plugin_t *this_gen, matroska_track_t *track,
1278                              int decoder_flags,
1279                              uint8_t *data, size_t data_len,
1280                              int64_t data_pts, int data_duration,
1281                              int input_normpos, int input_time) {
1282   demux_matroska_t *this = (demux_matroska_t *) this_gen;
1283   uint8_t *new_data = NULL;
1284   size_t new_data_len = 0;
1285 
1286   (void)data_duration;
1287 
1288   if (track->compress_algo == MATROSKA_COMPRESS_ZLIB) {
1289     uncompress_zlib(this, data, data_len, &new_data, &new_data_len);
1290     if (!new_data)
1291       return;
1292     data = new_data;
1293     data_len = new_data_len;
1294   }
1295 
1296   /* hmm ... */
1297   buf_element_t *buf = track->fifo->buffer_pool_alloc(track->fifo);
1298   buf->decoder_info[2] = data_len + 2;
1299   buf->size = 2;
1300   buf->pts = data_pts;
1301   buf->content[0] = 0x20;
1302   buf->content[1] = 0x00;
1303   buf->type = track->buf_type;
1304   track->fifo->put(track->fifo, buf);
1305 
1306   _x_demux_send_data(track->fifo, data, data_len,
1307                      data_pts, track->buf_type, decoder_flags,
1308                      input_normpos, input_time,
1309                      0, 0);
1310 
1311   free(new_data);
1312 }
1313 
handle_hdmv_pgs(demux_plugin_t * this_gen,matroska_track_t * track,int decoder_flags,uint8_t * data,size_t data_len,int64_t data_pts,int data_duration,int input_normpos,int input_time)1314 static void handle_hdmv_pgs (demux_plugin_t *this_gen, matroska_track_t *track,
1315                              int decoder_flags,
1316                              uint8_t *data, size_t data_len,
1317                              int64_t data_pts, int data_duration,
1318                              int input_normpos, int input_time) {
1319   demux_matroska_t *this = (demux_matroska_t *) this_gen;
1320   uint8_t *new_data = NULL;
1321   size_t new_data_len = 0;
1322 
1323   (void)data_duration;
1324 
1325   if (track->compress_algo == MATROSKA_COMPRESS_ZLIB) {
1326     uncompress_zlib(this, data, data_len, &new_data, &new_data_len);
1327     if (!new_data)
1328       return;
1329     data = new_data;
1330     data_len = new_data_len;
1331   }
1332 
1333   _x_demux_send_data(track->fifo, data, data_len,
1334 		     data_pts, track->buf_type, decoder_flags,
1335 		     input_normpos, input_time,
1336 		     0, 0);
1337 
1338   free(new_data);
1339 }
1340 
handle_hdmv_textst(demux_plugin_t * this_gen,matroska_track_t * track,int decoder_flags,uint8_t * data,size_t data_len,int64_t data_pts,int data_duration,int input_normpos,int input_time)1341 static void handle_hdmv_textst (demux_plugin_t *this_gen, matroska_track_t *track,
1342                                 int decoder_flags,
1343                                 uint8_t *data, size_t data_len,
1344                                 int64_t data_pts, int data_duration,
1345                                 int input_normpos, int input_time) {
1346   buf_element_t *buf;
1347   uint32_t *val;
1348   char *dest;
1349   int dest_len;
1350   int dest_pos;
1351   int i;
1352   uint8_t *ptr;
1353   int palette_update_flag;
1354   int num_regions;
1355 
1356   (void)this_gen;
1357   (void)data_len;
1358   (void)input_normpos;
1359   (void)input_time;
1360 
1361   ptr = data;
1362   if (*ptr != 0x82) {
1363     lprintf("Not a dialog presentation segment\n");
1364     return;
1365   }
1366   ++ptr;
1367 
1368   // Skip length and start/end pts values
1369   ptr += 12;
1370 
1371   palette_update_flag = *ptr++;
1372   if (palette_update_flag) {
1373     lprintf("Dunno what to do with palette updates\n");
1374     return;
1375   }
1376 
1377   buf = track->fifo->buffer_pool_alloc(track->fifo);
1378   buf->type = track->buf_type;
1379   buf->decoder_flags = decoder_flags | BUF_FLAG_SPECIAL;
1380   buf->decoder_info[1] = BUF_SPECIAL_CHARSET_ENCODING;
1381   buf->decoder_info_ptr[2] = buf->content + buf->max_size - LITERAL_UTF_8_SIZE;
1382   buf->decoder_info[2] = LITERAL_UTF_8_LEN;
1383 
1384   memcpy (buf->decoder_info_ptr[2], "utf-8", LITERAL_UTF_8_SIZE);
1385 
1386   val = (uint32_t *)buf->content;
1387   *val++ = data_pts / 90;                    /* start time */
1388   *val++ = (data_pts + data_duration) / 90;  /* end time   */
1389 
1390   dest = buf->content + 8;
1391   dest_len = buf->max_size - 8 - LITERAL_UTF_8_SIZE;
1392   dest_pos = 0;
1393 
1394   num_regions = *ptr++;
1395   for (i = 0; i < num_regions; ++i) {
1396     int length;
1397     uint8_t *end;
1398 
1399     // skip flags and style id reference
1400     ptr += 2;
1401 
1402     length = (ptr[0]<<8) | ptr[1];
1403     ptr += 2;
1404 
1405     end = ptr + length;
1406     while (ptr < end && dest_pos < dest_len - 2) {
1407       int marker;
1408       int type;
1409       int length;
1410 
1411       marker = *ptr++;
1412       if (marker != 0x1B)
1413         continue;
1414 
1415       type = *ptr++;
1416       length = *ptr++;
1417 
1418       if (type == 0x01) {
1419         int k;
1420         for (k = 0; k < length && dest_pos < dest_len - 1; ++k)
1421           dest[dest_pos++] = ptr[k];
1422       } else if (type == 0x0A) {
1423         dest[dest_pos++] = '\n';
1424       } else {
1425         lprintf("Unknown TextST data %02X\n", type);
1426       }
1427 
1428       ptr += length;
1429     }
1430   }
1431 
1432   dest[dest_pos] = 0;
1433 
1434   track->fifo->put(track->fifo, buf);
1435 }
1436 
fill_extra_data(matroska_track_t * track,uint32_t fourcc)1437 static void fill_extra_data(matroska_track_t *track, uint32_t fourcc) {
1438 
1439   xine_bmiheader *bih;
1440 
1441   if (track->codec_private_len > 0x7fffffff - sizeof(xine_bmiheader))
1442     track->codec_private_len = 0x7fffffff - sizeof(xine_bmiheader);
1443 
1444   /* create a bitmap info header struct */
1445   bih = calloc(1, sizeof(xine_bmiheader) + track->codec_private_len);
1446   if (!bih)
1447     return;
1448   bih->biSize = sizeof(xine_bmiheader) + track->codec_private_len;
1449   bih->biCompression = fourcc;
1450   if (track->video_track) {
1451     bih->biWidth = track->video_track->pixel_width;
1452     bih->biHeight = track->video_track->pixel_height;
1453   }
1454   /* this is to be passed to decoder in native machine endian */
1455   /* (no _x_bmiheader_le2me(bih);) */
1456 
1457   /* add bih extra data */
1458   if (track->codec_private_len > 0)
1459     memcpy(bih + 1, track->codec_private, track->codec_private_len);
1460   free(track->codec_private);
1461   track->codec_private = (uint8_t *)bih;
1462   track->codec_private_len = bih->biSize;
1463 }
1464 
parse_track_entry(demux_matroska_t * this,matroska_track_t * track)1465 static int parse_track_entry(demux_matroska_t *this, matroska_track_t *track) {
1466   ebml_parser_t *ebml = this->ebml;
1467   int this_level = ebml->level;
1468   int next_level = this_level;
1469 
1470   while (next_level == this_level) {
1471     ebml_elem_t elem;
1472 
1473     if (!ebml_read_elem_head(ebml, &elem))
1474       return 0;
1475 
1476     switch (elem.id) {
1477       case MATROSKA_ID_TR_NUMBER:
1478         {
1479           uint64_t num;
1480           lprintf("TrackNumber\n");
1481           if (!ebml_read_uint(ebml, &elem, &num))
1482             return 0;
1483           track->track_num = num;
1484         }
1485         break;
1486 
1487       case MATROSKA_ID_TR_TYPE:
1488         {
1489           uint64_t num;
1490           lprintf("TrackType\n");
1491           if (!ebml_read_uint(ebml, &elem, &num))
1492             return 0;
1493           track->track_type = num;
1494         }
1495         break;
1496 
1497       case MATROSKA_ID_TR_CODECID:
1498         {
1499           char *codec_id = ebml_alloc_read_ascii (ebml, &elem);
1500           lprintf("CodecID\n");
1501           if (!codec_id)
1502             return 0;
1503           track->codec_id = codec_id;
1504         }
1505         break;
1506 
1507       case MATROSKA_ID_TR_CODECPRIVATE:
1508         {
1509           uint8_t *codec_private;
1510           if (elem.len >= 0x80000000)
1511             return 0;
1512           codec_private = malloc (elem.len);
1513           if (! codec_private)
1514             return 0;
1515           lprintf("CodecPrivate\n");
1516           if (!ebml_read_binary(ebml, &elem, codec_private)) {
1517             free(codec_private);
1518             return 0;
1519           }
1520           track->codec_private = codec_private;
1521           track->codec_private_len = elem.len;
1522         }
1523         break;
1524 
1525       case MATROSKA_ID_TR_LANGUAGE:
1526         {
1527           char *language = ebml_alloc_read_ascii (ebml, &elem);
1528           lprintf("Language\n");
1529           if (!language)
1530             return 0;
1531           track->language = language;
1532         }
1533         break;
1534 
1535       case MATROSKA_ID_TV:
1536         lprintf("Video\n");
1537         if (track->video_track)
1538           return 1;
1539         track->video_track = (matroska_video_track_t *)calloc(1, sizeof(matroska_video_track_t));
1540         if (!ebml_read_master (ebml, &elem))
1541           return 0;
1542         if ((elem.len > 0) && !parse_video_track(this, track->video_track))
1543           return 0;
1544         break;
1545 
1546       case MATROSKA_ID_TA:
1547         lprintf("Audio\n");
1548         if (track->audio_track)
1549           return 1;
1550         track->audio_track = (matroska_audio_track_t *)calloc(1, sizeof(matroska_audio_track_t));
1551         if (!ebml_read_master (ebml, &elem))
1552           return 0;
1553         if ((elem.len > 0) && !parse_audio_track(this, track->audio_track))
1554           return 0;
1555         break;
1556 
1557       case MATROSKA_ID_TR_FLAGDEFAULT:
1558         {
1559           uint64_t val;
1560 
1561           lprintf("Default\n");
1562           if (!ebml_read_uint(ebml, &elem, &val))
1563             return 0;
1564           track->default_flag = (int)val;
1565         }
1566         break;
1567 
1568       case MATROSKA_ID_TR_DEFAULTDURATION:
1569         {
1570           uint64_t val;
1571 
1572           if (!ebml_read_uint(ebml, &elem, &val))
1573             return 0;
1574           track->default_duration = val;
1575           lprintf("Default Duration: %"PRIu64"\n", track->default_duration);
1576         }
1577         break;
1578 
1579       case MATROSKA_ID_CONTENTENCODINGS:
1580         {
1581           lprintf("ContentEncodings\n");
1582           if (!ebml_read_master (ebml, &elem))
1583             return 0;
1584           if ((elem.len > 0) && !parse_content_encodings(this, track))
1585             return 0;
1586         }
1587         break;
1588 
1589       case MATROSKA_ID_TR_UID:
1590         {
1591           uint64_t val;
1592 
1593           if (!ebml_read_uint(ebml, &elem, &val)) {
1594             lprintf("Track UID (invalid)\n");
1595             return 0;
1596           }
1597 
1598           track->uid = val;
1599           lprintf("Track UID: 0x%" PRIx64 "\n", track->uid);
1600         }
1601         break;
1602 
1603       case MATROSKA_ID_TR_FLAGENABLED:
1604       case MATROSKA_ID_TR_FLAGLACING:
1605       case MATROSKA_ID_TR_MINCACHE:
1606       case MATROSKA_ID_TR_MAXCACHE:
1607       case MATROSKA_ID_TR_TIMECODESCALE:
1608       case MATROSKA_ID_TR_NAME:
1609       case MATROSKA_ID_TR_CODECNAME:
1610       case MATROSKA_ID_TR_CODECSETTINGS:
1611       case MATROSKA_ID_TR_CODECINFOURL:
1612       case MATROSKA_ID_TR_CODECDOWNLOADURL:
1613       case MATROSKA_ID_TR_CODECDECODEALL:
1614       case MATROSKA_ID_TR_OVERLAY:
1615       default:
1616         lprintf("Unhandled ID: 0x%x\n", elem.id);
1617         if (!ebml_skip(ebml, &elem)) {
1618           return 0;
1619         }
1620     }
1621     next_level = ebml_get_next_level(ebml, &elem);
1622   }
1623 
1624   xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
1625           "demux_matroska: Track %d, %s %s\n",
1626           track->track_num,
1627           (track->codec_id ? track->codec_id : ""),
1628           (track->language ? track->language : ""));
1629   if (track->codec_id) {
1630     void (*init_codec)(demux_matroska_t *, matroska_track_t *) = NULL;
1631 
1632     if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_VFW_FOURCC)) {
1633       xine_bmiheader *bih;
1634 
1635       if (track->codec_private_len >= sizeof(xine_bmiheader)) {
1636         lprintf("MATROSKA_CODEC_ID_V_VFW_FOURCC\n");
1637         bih = (xine_bmiheader*)track->codec_private;
1638         _x_bmiheader_le2me(bih);
1639 
1640         track->buf_type = _x_fourcc_to_buf_video(bih->biCompression);
1641         if (!track->buf_type)
1642           _x_report_video_fourcc (this->stream->xine, LOG_MODULE, bih->biCompression);
1643         init_codec = init_codec_video;
1644       }
1645 
1646     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_UNCOMPRESSED)) {
1647     } else if ((!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_MPEG4_SP)) ||
1648                (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_MPEG4_ASP)) ||
1649                (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_MPEG4_AP))) {
1650 
1651       lprintf("MATROSKA_CODEC_ID_V_MPEG4_*\n");
1652       fill_extra_data(track, ME_FOURCC('M', 'P', '4', 'S'));
1653       track->buf_type = BUF_VIDEO_MPEG4;
1654 
1655       /* init as a vfw decoder */
1656       init_codec = init_codec_video;
1657     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_MPEG4_AVC)) {
1658       lprintf("MATROSKA_CODEC_ID_V_MPEG4_AVC\n");
1659       fill_extra_data(track, ME_FOURCC('a', 'v', 'c', '1'));
1660       track->buf_type = BUF_VIDEO_H264;
1661 
1662       /* init as a vfw decoder */
1663       init_codec = init_codec_video;
1664     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_MSMPEG4V3)) {
1665       track->buf_type = BUF_VIDEO_MSMPEG4_V3;
1666     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_MPEG1)) {
1667       lprintf("MATROSKA_CODEC_ID_V_MPEG1\n");
1668       track->buf_type = BUF_VIDEO_MPEG;
1669       init_codec = init_codec_video;
1670     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_MPEG2)) {
1671       lprintf("MATROSKA_CODEC_ID_V_MPEG2\n");
1672       track->buf_type = BUF_VIDEO_MPEG;
1673       init_codec = init_codec_video;
1674     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_VP8)) {
1675       lprintf("MATROSKA_CODEC_ID_V_VP8\n");
1676       fill_extra_data(track, ME_FOURCC('v', 'p', '8', '0'));
1677       track->buf_type = BUF_VIDEO_VP8;
1678       init_codec = init_codec_video;
1679     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_VP9)) {
1680       lprintf("MATROSKA_CODEC_ID_V_VP9\n");
1681       fill_extra_data(track, ME_FOURCC('v', 'p', '9', '0'));
1682       track->buf_type = BUF_VIDEO_VP9;
1683       init_codec = init_codec_video;
1684       track->handle_content = handle_vp9;
1685     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_HEVC)) {
1686       lprintf("MATROSKA_CODEC_ID_V_HEVC\n");
1687       fill_extra_data(track, ME_FOURCC('h', 'e', 'v', 'c'));
1688       track->buf_type = BUF_VIDEO_HEVC;
1689       init_codec = init_codec_video;
1690     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_AV1)) {
1691       lprintf("MATROSKA_CODEC_ID_V_AV1\n");
1692       fill_extra_data(track, ME_FOURCC('a', 'v', '1', '0'));
1693       track->buf_type = BUF_VIDEO_AV1;
1694       init_codec = init_codec_video;
1695     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_REAL_RV10)) {
1696     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_REAL_RV20)) {
1697     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_REAL_RV30)) {
1698       lprintf("MATROSKA_CODEC_ID_V_REAL_RV30\n");
1699       track->buf_type = BUF_VIDEO_RV30;
1700       track->handle_content = handle_realvideo;
1701       init_codec = init_codec_real;
1702     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_REAL_RV40)) {
1703 
1704       lprintf("MATROSKA_CODEC_ID_V_REAL_RV40\n");
1705       track->buf_type = BUF_VIDEO_RV40;
1706       track->handle_content = handle_realvideo;
1707       init_codec = init_codec_real;
1708 
1709     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_MJPEG)) {
1710     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_V_THEORA)) {
1711       lprintf("MATROSKA_CODEC_ID_V_THEORA\n");
1712       track->buf_type = BUF_VIDEO_THEORA_RAW;
1713       init_codec = init_codec_xiph;
1714     } else if ((!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_MPEG1_L1)) ||
1715                (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_MPEG1_L2)) ||
1716                (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_MPEG1_L3))) {
1717       lprintf("MATROSKA_CODEC_ID_A_MPEG1\n");
1718       track->buf_type = BUF_AUDIO_MPEG;
1719       init_codec = init_codec_audio;
1720 
1721     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_PCM_INT_BE)) {
1722       lprintf("MATROSKA_CODEC_ID_A_PCM_INT_BE");
1723       track->buf_type = BUF_AUDIO_LPCM_BE;
1724       init_codec = init_codec_audio;
1725 
1726     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_PCM_INT_LE)) {
1727       lprintf("MATROSKA_CODEC_ID_A_PCM_INT_LE");
1728       track->buf_type = BUF_AUDIO_LPCM_LE;
1729       init_codec = init_codec_audio;
1730 
1731     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_PCM_FLOAT)) {
1732     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_AC3)) {
1733       lprintf("MATROSKA_CODEC_ID_A_AC3\n");
1734       track->buf_type = BUF_AUDIO_A52;
1735       init_codec = init_codec_audio;
1736 
1737     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_EAC3)) {
1738       lprintf("MATROSKA_CODEC_ID_A_EAC3\n");
1739       track->buf_type = BUF_AUDIO_EAC3;
1740       init_codec = init_codec_audio;
1741 
1742     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_TRUEHD)) {
1743       lprintf("MATROSKA_CODEC_ID_A_TRUEHD\n");
1744       track->buf_type = BUF_AUDIO_TRUEHD;
1745       init_codec = init_codec_audio;
1746 
1747     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_FLAC)) {
1748       lprintf("MATROSKA_CODEC_ID_A_FLAC\n");
1749       track->buf_type = BUF_AUDIO_FLAC;
1750       init_codec = init_codec_audio;
1751 
1752     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_DTS)) {
1753       lprintf("MATROSKA_CODEC_ID_A_DTS\n");
1754       track->buf_type = BUF_AUDIO_DTS;
1755       init_codec = init_codec_audio;
1756 
1757     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_VORBIS)) {
1758 
1759       lprintf("MATROSKA_CODEC_ID_A_VORBIS\n");
1760       track->buf_type = BUF_AUDIO_VORBIS;
1761       init_codec = init_codec_xiph;
1762 
1763     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_OPUS)) {
1764       lprintf("MATROSKA_CODEC_ID_A_OPUS\n");
1765       track->buf_type = BUF_AUDIO_OPUS;
1766       init_codec = init_codec_audio;
1767 
1768     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_ACM)) {
1769       xine_waveformatex *wfh;
1770       lprintf("MATROSKA_CODEC_ID_A_ACM\n");
1771 
1772       if (track->codec_private_len >= sizeof(xine_waveformatex)) {
1773         wfh = (xine_waveformatex*)track->codec_private;
1774         _x_waveformatex_le2me(wfh);
1775 
1776         track->buf_type = _x_formattag_to_buf_audio(wfh->wFormatTag);
1777         if (!track->buf_type)
1778           _x_report_audio_format_tag (this->stream->xine, LOG_MODULE, wfh->wFormatTag);
1779         init_codec = init_codec_audio;
1780       }
1781     } else if (!strncmp(track->codec_id, MATROSKA_CODEC_ID_A_AAC,
1782                         sizeof(MATROSKA_CODEC_ID_A_AAC) - 1)) {
1783       lprintf("MATROSKA_CODEC_ID_A_AAC\n");
1784       track->buf_type = BUF_AUDIO_AAC;
1785       init_codec = init_codec_aac;
1786     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_REAL_14_4)) {
1787     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_REAL_28_8)) {
1788     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_REAL_COOK)) {
1789       lprintf("MATROSKA_CODEC_ID_A_REAL_COOK\n");
1790       track->buf_type = BUF_AUDIO_COOK;
1791       init_codec = init_codec_real;
1792     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_REAL_SIPR)) {
1793       lprintf("MATROSKA_CODEC_ID_A_REAL_SIPR\n");
1794       track->buf_type = BUF_AUDIO_SIPRO;
1795       init_codec = init_codec_real;
1796     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_REAL_RALF)) {
1797     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_A_REAL_ATRC)) {
1798       lprintf("MATROSKA_CODEC_ID_A_REAL_ATRC\n");
1799       track->buf_type = BUF_AUDIO_ATRK;
1800       init_codec = init_codec_real;
1801     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_S_TEXT_UTF8) ||
1802         !strcmp(track->codec_id, MATROSKA_CODEC_ID_S_UTF8)) {
1803       lprintf("MATROSKA_CODEC_ID_S_TEXT_UTF8\n");
1804       track->buf_type = BUF_SPU_OGM;
1805       track->handle_content = handle_sub_utf8;
1806     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_S_TEXT_SSA) ||
1807         !strcmp(track->codec_id, MATROSKA_CODEC_ID_S_SSA)) {
1808       lprintf("MATROSKA_CODEC_ID_S_TEXT_SSA\n");
1809       track->buf_type = BUF_SPU_OGM;
1810       track->handle_content = handle_sub_ssa;
1811     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_S_TEXT_ASS) ||
1812         !strcmp(track->codec_id, MATROSKA_CODEC_ID_S_ASS)) {
1813       lprintf("MATROSKA_CODEC_ID_S_TEXT_ASS\n");
1814       track->buf_type = BUF_SPU_OGM;
1815       track->handle_content = handle_sub_ssa;
1816     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_S_TEXT_USF)) {
1817       lprintf("MATROSKA_CODEC_ID_S_TEXT_USF\n");
1818       track->buf_type = BUF_SPU_OGM;
1819       track->handle_content = handle_sub_utf8;
1820     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_S_DVBSUB)) {
1821       lprintf("MATROSKA_CODEC_ID_S_DVBSUB\n");
1822       track->buf_type = BUF_SPU_DVB;
1823       track->handle_content = handle_dvbsub;
1824       init_codec = init_codec_dvbsub;
1825     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_S_VOBSUB)) {
1826       lprintf("MATROSKA_CODEC_ID_S_VOBSUB\n");
1827       track->buf_type = BUF_SPU_DVD;
1828       track->handle_content = handle_vobsub;
1829       init_codec = init_codec_vobsub;
1830 
1831       /* Enable autodetection of the zlib compression, unless it was
1832        * explicitely set. Most vobsubs are compressed with zlib but
1833        * are not declared as such.
1834        */
1835       if (track->compress_algo == MATROSKA_COMPRESS_NONE) {
1836         track->compress_algo = MATROSKA_COMPRESS_UNKNOWN;
1837       }
1838     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_S_HDMV_PGS)) {
1839       lprintf("MATROSKA_CODEC_ID_S_HDMV_PGS\n");
1840       track->buf_type = BUF_SPU_HDMV;
1841       track->handle_content = handle_hdmv_pgs;
1842       init_codec = init_codec_spu;
1843     } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_S_HDMV_TEXTST)) {
1844       lprintf("MATROSKA_CODEC_ID_S_HDMV_TEXTST\n");
1845       track->buf_type = BUF_SPU_OGM;
1846       track->handle_content = handle_hdmv_textst;
1847       init_codec = init_codec_spu;
1848     } else {
1849       xprintf(this->stream->xine, XINE_VERBOSITY_DEBUG, "unknown codec %s\n", track->codec_id);
1850     }
1851 
1852     if (track->buf_type) {
1853 
1854       switch(track->track_type) {
1855         case MATROSKA_TRACK_VIDEO:
1856           track->fifo = this->stream->video_fifo;
1857           track->buf_type |= this->num_video_tracks;
1858           this->num_video_tracks++;
1859           break;
1860         case MATROSKA_TRACK_AUDIO:
1861           track->fifo = this->stream->audio_fifo;
1862           track->buf_type |= this->num_audio_tracks;
1863           this->num_audio_tracks++;
1864           break;
1865         case MATROSKA_TRACK_SUBTITLE:
1866           track->fifo = this->stream->video_fifo;
1867           track->buf_type |= this->num_sub_tracks;
1868           this->num_sub_tracks++;
1869           break;
1870         case MATROSKA_TRACK_COMPLEX:
1871         case MATROSKA_TRACK_LOGO:
1872         case MATROSKA_TRACK_CONTROL:
1873           break;
1874       }
1875 
1876       if (init_codec) {
1877 	if (! track->fifo) {
1878 	  xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
1879 		  "demux_matroska: Error: fifo not set up for track of type type %" PRIu32 "\n", track->track_type);
1880 	  return 0;
1881         }
1882         init_codec(this, track);
1883       }
1884     }
1885   }
1886 
1887   return 1;
1888 }
1889 
1890 
parse_tracks(demux_matroska_t * this)1891 static int parse_tracks(demux_matroska_t *this) {
1892   ebml_parser_t *ebml = this->ebml;
1893   int this_level = ebml->level;
1894   int next_level = this_level;
1895 
1896   while (next_level == this_level) {
1897     ebml_elem_t elem;
1898 
1899     if (!ebml_read_elem_head(ebml, &elem))
1900       return 0;
1901 
1902     switch (elem.id) {
1903       case MATROSKA_ID_TR_ENTRY: {
1904         matroska_track_t *track;
1905 
1906         /* bail out early if no more tracks can be handled! */
1907         if (this->num_tracks >= MAX_STREAMS) {
1908           lprintf("Too many tracks!\n");
1909           return 0;
1910         }
1911 
1912         /* alloc and initialize a track with 0 */
1913         track = calloc(1, sizeof(matroska_track_t));
1914         track->compress_algo = MATROSKA_COMPRESS_NONE;
1915         this->tracks[this->num_tracks] = track;
1916 
1917         lprintf("TrackEntry\n");
1918         if (!ebml_read_master (ebml, &elem))
1919           return 0;
1920         if ((elem.len > 0) && !parse_track_entry(this, track))
1921           return 0;
1922         this->num_tracks++;
1923       }
1924       break;
1925 
1926       default:
1927         lprintf("Unhandled ID: 0x%x\n", elem.id);
1928         if (!ebml_skip(ebml, &elem))
1929           return 0;
1930     }
1931     next_level = ebml_get_next_level(ebml, &elem);
1932   }
1933   return 1;
1934 }
1935 
parse_cue_trackposition(demux_matroska_t * this,int * track_num,int64_t * pos)1936 static int parse_cue_trackposition(demux_matroska_t *this, int *track_num,
1937                                    int64_t *pos) {
1938   ebml_parser_t *ebml = this->ebml;
1939   int next_level = 4;
1940 
1941   while (next_level == 4) {
1942     ebml_elem_t elem;
1943 
1944     if (!ebml_read_elem_head(ebml, &elem))
1945       return 0;
1946 
1947     switch (elem.id) {
1948       case MATROSKA_ID_CU_TRACK: {
1949         uint64_t num;
1950         lprintf("CueTrackpositionTrack\n");
1951         if (!ebml_read_uint(ebml, &elem, &num))
1952           return 0;
1953         *track_num = num;
1954         break;
1955       }
1956       case MATROSKA_ID_CU_CLUSTERPOSITION: {
1957         uint64_t num;
1958         lprintf("CueTrackpositionClusterposition\n");
1959         if (!ebml_read_uint(ebml, &elem, &num))
1960           return 0;
1961         *pos = this->segment.start + num;
1962         break;
1963       }
1964       default:
1965         lprintf("Unhandled ID: 0x%x\n", elem.id);
1966         if (!ebml_skip(ebml, &elem))
1967           return 0;
1968     }
1969     next_level = ebml_get_next_level(ebml, &elem);
1970   }
1971   return 1;
1972 }
1973 
1974 
parse_cue_point(demux_matroska_t * this)1975 static int parse_cue_point(demux_matroska_t *this) {
1976   ebml_parser_t *ebml = this->ebml;
1977   int next_level = 3;
1978   int64_t timecode = -1, pos = -1;
1979   int track_num = -1;
1980 
1981   while (next_level == 3) {
1982     ebml_elem_t elem;
1983 
1984     if (!ebml_read_elem_head(ebml, &elem))
1985       return 0;
1986 
1987     switch (elem.id) {
1988       case MATROSKA_ID_CU_TIME: {
1989         uint64_t num;
1990         lprintf("CueTime\n");
1991         if (!ebml_read_uint(ebml, &elem, &num))
1992           return 0;
1993         timecode = num;
1994         break;
1995       }
1996       case MATROSKA_ID_CU_TRACKPOSITION:
1997         lprintf("CueTrackPosition\n");
1998         if (!ebml_read_master (ebml, &elem))
1999           return 0;
2000         if ((elem.len > 0) && !parse_cue_trackposition(this, &track_num, &pos))
2001           return 0;
2002         break;
2003       default:
2004         lprintf("Unhandled ID: 0x%x\n", elem.id);
2005         if (!ebml_skip(ebml, &elem))
2006           return 0;
2007     }
2008     next_level = ebml_get_next_level(ebml, &elem);
2009   }
2010 
2011   if ((timecode != -1) && (track_num != -1) && (pos != -1)) {
2012     matroska_index_t *index;
2013     int i;
2014 
2015     index = NULL;
2016     for (i = 0; i < this->num_indexes; i++)
2017       if (this->indexes[i].track_num == track_num) {
2018         index = &this->indexes[i];
2019         break;
2020       }
2021     if (index == NULL) {
2022       this->indexes = (matroska_index_t *)realloc(this->indexes,
2023                                                   (this->num_indexes + 1) *
2024                                                   sizeof(matroska_index_t));
2025       memset(&this->indexes[this->num_indexes], 0, sizeof(matroska_index_t));
2026       index = &this->indexes[this->num_indexes];
2027       index->track_num = track_num;
2028       this->num_indexes++;
2029     }
2030     if ((index->num_entries % 1024) == 0) {
2031       index->pos = realloc(index->pos, sizeof(off_t) *
2032 			   (index->num_entries + 1024));
2033       index->timecode = realloc(index->timecode, sizeof(uint64_t) *
2034 				(index->num_entries + 1024));
2035     }
2036     index->pos[index->num_entries] = pos;
2037     index->timecode[index->num_entries] = timecode;
2038     index->num_entries++;
2039   }
2040 
2041   return 1;
2042 }
2043 
2044 
parse_cues(demux_matroska_t * this)2045 static int parse_cues(demux_matroska_t *this) {
2046   ebml_parser_t *ebml = this->ebml;
2047   int next_level = 2;
2048 
2049   while (next_level == 2) {
2050     ebml_elem_t elem;
2051 
2052     if (!ebml_read_elem_head(ebml, &elem))
2053       return 0;
2054 
2055     switch (elem.id) {
2056       case MATROSKA_ID_CU_POINT:
2057         lprintf("CuePoint\n");
2058         if (!ebml_read_master (ebml, &elem))
2059           return 0;
2060         if ((elem.len > 0) && !parse_cue_point(this))
2061           return 0;
2062         break;
2063       default:
2064         lprintf("Unhandled ID: 0x%x\n", elem.id);
2065         if (!ebml_skip(ebml, &elem))
2066           return 0;
2067     }
2068     next_level = ebml_get_next_level(ebml, &elem);
2069   }
2070   return 1;
2071 }
2072 
2073 
parse_attachments(demux_matroska_t * this)2074 static int parse_attachments(demux_matroska_t *this) {
2075   ebml_parser_t *ebml = this->ebml;
2076   int next_level = 2;
2077 
2078   while (next_level == 2) {
2079     ebml_elem_t elem;
2080 
2081     if (!ebml_read_elem_head(ebml, &elem))
2082       return 0;
2083 
2084     switch (elem.id) {
2085       default:
2086         lprintf("Unhandled ID: 0x%x\n", elem.id);
2087         if (!ebml_skip(ebml, &elem))
2088           return 0;
2089     }
2090     next_level = ebml_get_next_level(ebml, &elem);
2091   }
2092   return 1;
2093 }
2094 
2095 
parse_tags(demux_matroska_t * this)2096 static int parse_tags(demux_matroska_t *this) {
2097   ebml_parser_t *ebml = this->ebml;
2098   int next_level = 2;
2099 
2100   while (next_level == 2) {
2101     ebml_elem_t elem;
2102 
2103     if (!ebml_read_elem_head(ebml, &elem))
2104       return 0;
2105 
2106     switch (elem.id) {
2107       default:
2108         lprintf("Unhandled ID: 0x%x\n", elem.id);
2109         if (!ebml_skip(ebml, &elem))
2110           return 0;
2111     }
2112     next_level = ebml_get_next_level(ebml, &elem);
2113   }
2114   return 1;
2115 }
2116 
alloc_block_data(demux_matroska_t * this,size_t len)2117 static void alloc_block_data (demux_matroska_t *this, size_t len) {
2118   /* memory management */
2119   if (this->block_data_size < len) {
2120     this->block_data = realloc(this->block_data, len);
2121     this->block_data_size = len;
2122   }
2123 }
2124 
2125 
parse_ebml_uint(demux_matroska_t * this,uint8_t * data,uint64_t * num)2126 static int parse_ebml_uint(demux_matroska_t *this, uint8_t *data, uint64_t *num) {
2127   uint8_t mask = 0x80;
2128   int size = 1;
2129   int i;
2130 
2131   /* compute the size of the "data len" (1-8 bytes) */
2132   while (size <= 8 && !(data[0] & mask)) {
2133     size++;
2134     mask >>= 1;
2135   }
2136   if (size > 8) {
2137     off_t pos = this->input->get_current_pos(this->input);
2138     xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
2139             "demux_matroska: Invalid Track Number at position %" PRIdMAX "\n",
2140             (intmax_t)pos);
2141     return 0;
2142   }
2143 
2144   *num = data[0];
2145   *num &= mask - 1;
2146 
2147   for (i = 1; i < size; i++) {
2148     *num = (*num << 8) | data[i];
2149   }
2150   return size;
2151 }
2152 
2153 
parse_ebml_sint(demux_matroska_t * this,uint8_t * data,int64_t * num)2154 static int parse_ebml_sint(demux_matroska_t *this, uint8_t *data, int64_t *num) {
2155   uint64_t unum;
2156   int size;
2157 
2158   size = parse_ebml_uint(this, data, &unum);
2159   if (!size)
2160     return 0;
2161 
2162   /* formula taken from gstreamer demuxer */
2163   if (unum == (uint64_t)-1)
2164     *num = -1;
2165   else
2166     *num = unum - ((1 << ((7 * size) - 1)) - 1);
2167 
2168   return size;
2169 }
2170 
find_track_by_id(demux_matroska_t * this,int track_num,matroska_track_t ** track)2171 static int find_track_by_id(demux_matroska_t *this, int track_num,
2172                             matroska_track_t **track) {
2173   int i;
2174 
2175   *track = NULL;
2176   for (i = 0; i < this->num_tracks; i++) {
2177     if (this->tracks[i]->track_num == track_num) {
2178       *track = this->tracks[i];
2179       return 1;
2180     }
2181   }
2182   return 0;
2183 }
2184 
2185 
read_block_data(demux_matroska_t * this,size_t len,size_t offset)2186 static int read_block_data (demux_matroska_t *this, size_t len, size_t offset) {
2187   alloc_block_data(this, len + offset);
2188 
2189   /* block datas */
2190   if (! this->block_data) {
2191     xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
2192             "demux_matroska: memory allocation error\n");
2193     return 0;
2194   }
2195   if (this->input->read (this->input, this->block_data + offset, len) != (int)len) {
2196     off_t pos = this->input->get_current_pos(this->input);
2197     xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
2198             "demux_matroska: read error at position %" PRIdMAX "\n",
2199             (intmax_t)pos);
2200     return 0;
2201   }
2202   return 1;
2203 }
2204 
parse_int16(uint8_t * data)2205 static int parse_int16(uint8_t *data) {
2206   int value = (int)_X_BE_16(data);
2207   if (value & 1<<15)
2208   {
2209     value -= 1<<16;
2210   }
2211   return value;
2212 }
2213 
parse_block(demux_matroska_t * this,size_t block_size,uint64_t cluster_timecode,uint64_t block_duration,int normpos,int is_key)2214 static int parse_block (demux_matroska_t *this, size_t block_size,
2215                         uint64_t cluster_timecode, uint64_t block_duration,
2216                         int normpos, int is_key) {
2217   matroska_track_t *track;
2218   uint64_t          track_num;
2219   uint8_t          *data;
2220   uint8_t           flags;
2221   int               lacing;
2222   unsigned int      num_len;
2223   int16_t           timecode_diff;
2224   int64_t           pts, xduration;
2225   int               decoder_flags = 0;
2226   size_t            headers_len = 0;
2227 
2228   data = this->block_data + this->compress_maxlen;
2229   if (!(num_len = parse_ebml_uint(this, data, &track_num)))
2230     return 0;
2231   data += num_len;
2232 
2233   /* timecode_diff is signed */
2234   timecode_diff = (int16_t)parse_int16(data);
2235   data += 2;
2236 
2237   flags = *data;
2238   data += 1;
2239 
2240   lprintf("track_num: %" PRIu64 ", timecode_diff: %d, flags: 0x%x\n", track_num, timecode_diff, flags);
2241 
2242   /*gap = flags & 1;*/
2243   lacing = (flags >> 1) & 0x3;
2244   lprintf("lacing: %x\n", lacing);
2245 
2246   if (!find_track_by_id(this, (int)track_num, &track)) {
2247      xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
2248              "demux_matroska: invalid track id: %" PRIu64 "\n", track_num);
2249      return 0;
2250   }
2251 
2252   pts = ((int64_t)cluster_timecode + timecode_diff) *
2253         (int64_t)this->timecode_scale * (int64_t)90 /
2254         (int64_t)1000000;
2255 
2256   /* After seeking we have to skip to the next key frame. */
2257   if (this->skip_to_timecode > 0) {
2258     if ((this->skip_for_track != track->track_num) || !is_key ||
2259         (pts < this->skip_to_timecode))
2260       return 1;
2261     this->skip_to_timecode = 0;
2262   }
2263 
2264   if (block_duration) {
2265     xduration = (int64_t)block_duration *
2266                 (int64_t)this->timecode_scale * (int64_t)90 /
2267                 (int64_t)1000000;
2268   } else {
2269     block_duration = track->default_duration;
2270     xduration = (int64_t)block_duration * (int64_t)90 / (int64_t)1000000;
2271   }
2272   lprintf("pts: %" PRId64 ", duration: %" PRId64 "\n", pts, xduration);
2273 
2274   check_newpts(this, pts, track);
2275 
2276   if (this->preview_mode) {
2277     this->preview_sent++;
2278     decoder_flags |= BUF_FLAG_PREVIEW;
2279   }
2280 
2281   if (track->compress_algo == MATROSKA_COMPRESS_HEADER_STRIP)
2282     headers_len = track->compress_len;
2283 
2284   if (lacing == MATROSKA_NO_LACING) {
2285     size_t block_size_left;
2286     lprintf("no lacing\n");
2287 
2288     if (is_key)
2289       decoder_flags |= BUF_FLAG_KEYFRAME;
2290 
2291     block_size_left = (this->block_data + block_size + this->compress_maxlen) - data;
2292     lprintf("size: %zu, block_size: %zu, block_offset: %zu\n", block_size_left, block_size, this->compress_maxlen);
2293 
2294     if (headers_len) {
2295       data -= headers_len;
2296       xine_fast_memcpy(data, track->compress_settings, headers_len);
2297       block_size_left += headers_len;
2298     }
2299 
2300     if (track->handle_content != NULL) {
2301       track->handle_content ((demux_plugin_t *)this, track, decoder_flags,
2302         data, block_size_left, pts, xduration, normpos, pts / 90);
2303     } else {
2304       _x_demux_send_data (track->fifo, data, block_size_left, pts, track->buf_type,
2305         decoder_flags, normpos, pts / 90, this->duration, 0);
2306     }
2307 
2308   } else {
2309 
2310     size_t block_size_left;
2311     uint8_t lace_num;
2312     size_t frame[MAX_FRAMES];
2313     int i;
2314 
2315     /* number of laced frames */
2316     lace_num = *data;
2317     data++;
2318     lprintf("lace_num: %d\n", lace_num);
2319     if ((lace_num + 1) > MAX_FRAMES) {
2320       xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
2321               "demux_matroska: too many frames: %d\n", lace_num);
2322       return 0;
2323     }
2324     block_size_left = this->block_data + block_size + this->compress_maxlen - data;
2325 
2326     switch (lacing) {
2327       case MATROSKA_XIPH_LACING: {
2328 
2329         lprintf("xiph lacing\n");
2330 
2331         /* size of each frame */
2332         for (i = 0; i < lace_num; i++) {
2333           int size = 0;
2334           int partial_size;
2335           do
2336           {
2337             partial_size = *data;
2338             size += partial_size;
2339             data++; block_size_left--;
2340           } while (partial_size == 255);
2341           frame[i] = size;
2342           block_size_left -= size;
2343         }
2344 
2345         /* last frame */
2346         frame[lace_num] = block_size_left;
2347       }
2348       break;
2349 
2350       case MATROSKA_FIXED_SIZE_LACING: {
2351         size_t frame_size;
2352 
2353         lprintf("fixed size lacing\n");
2354 
2355         frame_size = block_size_left / (lace_num + 1);
2356         for (i = 0; i < lace_num; i++) {
2357           frame[i] = frame_size;
2358         }
2359         frame[lace_num] = block_size_left - ((size_t)lace_num * frame_size);
2360         block_size_left = 0;
2361       }
2362       break;
2363 
2364       case MATROSKA_EBML_LACING: {
2365         uint64_t first_frame_size;
2366 
2367         lprintf("ebml lacing\n");
2368 
2369         /* size of each frame */
2370         if (!(num_len = parse_ebml_uint(this, data, &first_frame_size)))
2371           return 0;
2372         if (num_len > block_size_left) {
2373           xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
2374                   "demux_matroska: block too small\n");
2375           return 0;
2376         }
2377         if (first_frame_size > INT_MAX) {
2378           xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
2379                   "demux_matroska: invalid first frame size (%" PRIu64 ")\n",
2380                   first_frame_size);
2381           return 0;
2382         }
2383         data += num_len; block_size_left -= num_len;
2384         frame[0] = (int) first_frame_size;
2385         lprintf("first frame len: %zu\n", frame[0]);
2386         block_size_left -= frame[0];
2387 
2388         for (i = 1; i < lace_num; i++) {
2389           int64_t frame_size_diff;
2390           int64_t frame_size;
2391 
2392           if (!(num_len = parse_ebml_sint(this, data, &frame_size_diff)))
2393             return 0;
2394 
2395           if (num_len > block_size_left) {
2396             xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
2397                     "demux_matroska: block too small\n");
2398             return 0;
2399           }
2400           data += num_len; block_size_left -= num_len;
2401 
2402           frame_size = frame[i-1] + frame_size_diff;
2403           if (frame_size > INT_MAX || frame_size < 0) {
2404             xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
2405                     "demux_matroska: invalid frame size (%" PRId64 ")\n",
2406                     frame_size);
2407             return 0;
2408           }
2409           frame[i] = frame_size;
2410           block_size_left -= frame[i];
2411         }
2412 
2413         /* last frame */
2414         frame[lace_num] = block_size_left;
2415       }
2416       break;
2417       default:
2418         xprintf(this->stream->xine, XINE_VERBOSITY_LOG,
2419                 "demux_matroska: invalid lacing: %d\n", lacing);
2420         return 0;
2421     }
2422     /* send each frame to the decoder */
2423     for (i = 0; i <= lace_num; i++) {
2424 
2425       if (headers_len) {
2426         data -= headers_len;
2427         xine_fast_memcpy(data, track->compress_settings, headers_len);
2428         frame[i] += headers_len;
2429       }
2430 
2431       if (track->handle_content != NULL) {
2432         track->handle_content((demux_plugin_t *)this, track,
2433                                decoder_flags,
2434                                data, frame[i],
2435                                pts, 0,
2436                                normpos, pts / 90);
2437       } else {
2438         _x_demux_send_data(track->fifo, data, frame[i],
2439                            pts, track->buf_type, decoder_flags,
2440                            normpos, pts / 90,
2441                            this->duration, 0);
2442       }
2443       data += frame[i];
2444       pts = 0;
2445     }
2446   }
2447   return 1;
2448 }
2449 
parse_simpleblock(demux_matroska_t * this,size_t block_len,uint64_t cluster_timecode,uint64_t block_duration)2450 static int parse_simpleblock(demux_matroska_t *this, size_t block_len, uint64_t cluster_timecode, uint64_t block_duration)
2451 {
2452   off_t block_pos         = 0;
2453   off_t file_len          = 0;
2454   int normpos             = 0;
2455   int is_key              = 1;
2456 
2457   lprintf("simpleblock\n");
2458   block_pos = this->input->get_current_pos(this->input);
2459   file_len = this->input->get_length(this->input);
2460   if( file_len )
2461     normpos = (int) ( (double) block_pos * 65535 / file_len );
2462 
2463   if (!read_block_data(this, block_len, this->compress_maxlen))
2464     return 0;
2465 
2466     /* we have the duration, we can parse the block now */
2467   if (!parse_block(this, block_len, cluster_timecode, block_duration,
2468                    normpos, is_key))
2469     return 0;
2470   return 1;
2471 }
2472 
parse_block_group(demux_matroska_t * this,uint64_t cluster_timecode,uint64_t cluster_duration)2473 static int parse_block_group(demux_matroska_t *this,
2474                              uint64_t cluster_timecode,
2475                              uint64_t cluster_duration) {
2476   ebml_parser_t *ebml     = this->ebml;
2477   int next_level          = 3;
2478   int has_block           = 0;
2479   uint64_t block_duration = 0;
2480   off_t block_pos         = 0;
2481   off_t file_len          = 0;
2482   int normpos             = 0;
2483   size_t block_len        = 0;
2484   int is_key              = 1;
2485 
2486   (void)cluster_duration;
2487 
2488   while (next_level == 3) {
2489     ebml_elem_t elem;
2490 
2491     if (!ebml_read_elem_head(ebml, &elem))
2492       return 0;
2493 
2494     switch (elem.id) {
2495       case MATROSKA_ID_CL_BLOCK:
2496         lprintf("block\n");
2497         block_pos = this->input->get_current_pos(this->input);
2498         block_len = elem.len;
2499         file_len = this->input->get_length(this->input);
2500         if( file_len )
2501           normpos = (int) ( (double) block_pos * 65535 / file_len );
2502 
2503         if (!read_block_data(this, elem.len, this->compress_maxlen))
2504           return 0;
2505 
2506         has_block = 1;
2507         break;
2508       case MATROSKA_ID_CL_BLOCKDURATION:
2509         /* should override track duration */
2510         if (!ebml_read_uint(ebml, &elem, &block_duration))
2511           return 0;
2512         lprintf("duration: %" PRIu64 "\n", block_duration);
2513         break;
2514       case MATROSKA_ID_CL_REFERENCEBLOCK:
2515         is_key = 0;
2516         if (!ebml_skip(ebml, &elem))
2517           return 0;
2518         break;
2519       default:
2520         lprintf("Unhandled ID: 0x%x\n", elem.id);
2521         if (!ebml_skip(ebml, &elem))
2522           return 0;
2523     }
2524     next_level = ebml_get_next_level(ebml, &elem);
2525   }
2526 
2527   if (!has_block)
2528     return 0;
2529 
2530   /* we have the duration, we can parse the block now */
2531   if (!parse_block(this, block_len, cluster_timecode, block_duration,
2532                    normpos, is_key))
2533     return 0;
2534   return 1;
2535 }
2536 
2537 static int demux_matroska_seek (demux_plugin_t*, off_t, int, int);
2538 
handle_events(demux_matroska_t * this)2539 static void handle_events(demux_matroska_t *this) {
2540   xine_event_t* event;
2541 
2542   while ((event = xine_event_get(this->event_queue))) {
2543     if (this->num_editions > 0) {
2544       matroska_edition_t* ed = this->editions[0];
2545       int chapter_idx = matroska_get_chapter(this, this->last_timecode, &ed);
2546       uint64_t next_time;
2547 
2548       if (chapter_idx < 0) {
2549         xine_event_free(event);
2550         continue;
2551       }
2552 
2553       switch(event->type) {
2554         case XINE_EVENT_INPUT_NEXT:
2555           if (chapter_idx < ed->num_chapters-1) {
2556             next_time = ed->chapters[chapter_idx+1]->time_start / 90;
2557             demux_matroska_seek((demux_plugin_t*)this, 0, next_time, 1);
2558           }
2559           break;
2560 
2561           /* TODO: should this try to implement common "start of chapter"
2562            *  functionality? */
2563         case XINE_EVENT_INPUT_PREVIOUS:
2564           if (chapter_idx > 0) {
2565             next_time = ed->chapters[chapter_idx-1]->time_start / 90;
2566             demux_matroska_seek((demux_plugin_t*)this, 0, next_time, 1);
2567           }
2568           break;
2569 
2570         default:
2571           break;
2572       }
2573     }
2574 
2575     xine_event_free(event);
2576   }
2577 }
2578 
parse_cluster(demux_matroska_t * this)2579 static int parse_cluster(demux_matroska_t *this) {
2580   ebml_parser_t *ebml = this->ebml;
2581   int this_level = ebml->level;
2582   int next_level = this_level;
2583   uint64_t timecode = 0;
2584   uint64_t duration = 0;
2585 
2586   if (!this->first_cluster_found) {
2587     int idx, entry;
2588 
2589     /* Scale the cues to ms precision. */
2590     for (idx = 0; idx < this->num_indexes; idx++) {
2591       matroska_index_t *index = &this->indexes[idx];
2592       for (entry = 0; entry < index->num_entries; entry++)
2593         index->timecode[entry] = index->timecode[entry] *
2594           this->timecode_scale / 1000000;
2595     }
2596     this->first_cluster_found = 1;
2597   }
2598 
2599   handle_events(this);
2600 
2601   while (next_level == this_level) {
2602     ebml_elem_t elem;
2603 
2604     if (!ebml_read_elem_head(ebml, &elem))
2605       return 0;
2606 
2607     switch (elem.id) {
2608       case MATROSKA_ID_CL_TIMECODE:
2609         lprintf("timecode\n");
2610         if (!ebml_read_uint(ebml, &elem, &timecode))
2611           return 0;
2612         break;
2613       case MATROSKA_ID_CL_DURATION:
2614         lprintf("duration\n");
2615         if (!ebml_read_uint(ebml, &elem, &duration))
2616           return 0;
2617         break;
2618       case MATROSKA_ID_CL_BLOCKGROUP:
2619         lprintf("blockgroup\n");
2620         if (!ebml_read_master (ebml, &elem))
2621           return 0;
2622         if ((elem.len > 0) && !parse_block_group(this, timecode, duration))
2623           return 0;
2624         break;
2625       case MATROSKA_ID_CL_SIMPLEBLOCK:
2626         lprintf("simpleblock\n");
2627         if (!parse_simpleblock(this, elem.len, timecode, duration))
2628           return 0;
2629         break;
2630       case MATROSKA_ID_CL_BLOCK:
2631         lprintf("block\n");
2632         if (!ebml_skip(ebml, &elem))
2633           return 0;
2634         break;
2635       default:
2636         lprintf("Unhandled ID: 0x%x\n", elem.id);
2637         if (!ebml_skip(ebml, &elem))
2638           return 0;
2639     }
2640     next_level = ebml_get_next_level(ebml, &elem);
2641   }
2642 
2643   /* at this point, we MUST have a timecode (according to format spec).
2644    * Use that to find the chapter we are in, and adjust the title.
2645    *
2646    * TODO: this only looks at the chapters in the first edition.
2647    */
2648 
2649   this->last_timecode = timecode;
2650 
2651   if (this->num_editions <= 0)
2652     return 1;
2653   matroska_edition_t *ed = this->editions[0];
2654 
2655   if (ed->num_chapters <= 0)
2656     return 1;
2657 
2658   /* fix up a makeshift title if none has been set yet (e.g. filename) */
2659   if (NULL == this->title && NULL != _x_meta_info_get(this->stream, XINE_META_INFO_TITLE))
2660     this->title = strdup(_x_meta_info_get(this->stream, XINE_META_INFO_TITLE));
2661 
2662   if (NULL == this->title)
2663     this->title = strdup("(No title)");
2664 
2665   if (NULL == this->title) {
2666     lprintf("Failed to determine a valid stream title!\n");
2667     return 1;
2668   }
2669 
2670   int chapter_idx = matroska_get_chapter(this, timecode, &ed);
2671   if (chapter_idx < 0) {
2672     _x_meta_info_set_utf8(this->stream, XINE_META_INFO_TITLE, this->title);
2673     return 1;
2674   }
2675 
2676   xine_ui_data_t uidata = {
2677     .str = {0, },
2678     .str_len = 0,
2679   };
2680 
2681   uidata.str_len = snprintf(uidata.str, sizeof(uidata.str), "%s / (%d) %s",
2682       this->title, chapter_idx+1, ed->chapters[chapter_idx]->title);
2683   _x_meta_info_set_utf8(this->stream, XINE_META_INFO_TITLE, uidata.str);
2684 
2685   return 1;
2686 }
2687 
2688 static int parse_top_level_head(demux_matroska_t *this, int *next_level);
2689 
parse_seek_entry(demux_matroska_t * this)2690 static int parse_seek_entry(demux_matroska_t *this) {
2691   ebml_parser_t *ebml = this->ebml;
2692   int next_level = 3;
2693   int has_id = 0;
2694   int has_position = 0;
2695   uint64_t id = 0;
2696   uint64_t pos;
2697 
2698   while (next_level == 3) {
2699     ebml_elem_t elem;
2700 
2701     if (!ebml_read_elem_head(ebml, &elem))
2702       return 0;
2703 
2704     switch (elem.id) {
2705       case MATROSKA_ID_S_ID:
2706         lprintf("SeekID\n");
2707         if (!ebml_read_uint(ebml, &elem, &id))
2708           return 0;
2709         has_id = 1;
2710         break;
2711       case MATROSKA_ID_S_POSITION:
2712         lprintf("SeekPosition\n");
2713         if (!ebml_read_uint(ebml, &elem, &pos))
2714           return 0;
2715         has_position = 1;
2716         break;
2717       default:
2718         lprintf("Unhandled ID: 0x%x\n", elem.id);
2719         if (!ebml_skip(ebml, &elem))
2720           return 0;
2721     }
2722     next_level = ebml_get_next_level(ebml, &elem);
2723   }
2724 
2725   /* do not parse clusters */
2726   if (id == MATROSKA_ID_CLUSTER) {
2727     lprintf("skip cluster\n");
2728     return 1;
2729   }
2730 
2731   /* parse the referenced element */
2732   if (has_id && has_position) {
2733     off_t current_pos, seek_pos;
2734 
2735     seek_pos = this->segment.start + pos;
2736 
2737     if ((seek_pos > 0) && (seek_pos < this->input->get_length(this->input))) {
2738       ebml_parser_t ebml_bak;
2739 
2740       /* backup current state */
2741       current_pos = this->input->get_current_pos(this->input);
2742       memcpy(&ebml_bak, this->ebml, sizeof(ebml_parser_t));   /* FIXME */
2743 
2744       /* seek and parse the top_level element */
2745       this->ebml->level = 1;
2746       if (this->input->seek(this->input, seek_pos, SEEK_SET) < 0) {
2747         xprintf(this->stream->xine, XINE_VERBOSITY_DEBUG,
2748                 "demux_matroska: failed to seek to pos: %" PRIdMAX "\n",
2749                 (intmax_t)seek_pos);
2750         return 0;
2751       }
2752       if (!parse_top_level_head(this, &next_level))
2753         return 0;
2754 
2755       /* restore old state */
2756       memcpy(this->ebml, &ebml_bak, sizeof(ebml_parser_t));   /* FIXME */
2757       if (this->input->seek(this->input, current_pos, SEEK_SET) < 0) {
2758         xprintf(this->stream->xine, XINE_VERBOSITY_DEBUG,
2759                 "demux_matroska: failed to seek to pos: %" PRIdMAX "\n",
2760                 (intmax_t)current_pos);
2761         return 0;
2762       }
2763     } else {
2764       xprintf(this->stream->xine, XINE_VERBOSITY_DEBUG,
2765               "demux_matroska: out of stream seek pos: %" PRIdMAX "\n",
2766               (intmax_t)seek_pos);
2767     }
2768     return 1;
2769   } else {
2770     lprintf("incomplete Seek Entry\n");
2771     return 1;
2772   }
2773 }
2774 
2775 
parse_seekhead(demux_matroska_t * this)2776 static int parse_seekhead(demux_matroska_t *this) {
2777   ebml_parser_t *ebml = this->ebml;
2778   int next_level = 2;
2779 
2780   while (next_level == 2) {
2781     ebml_elem_t elem;
2782 
2783     if (!ebml_read_elem_head(ebml, &elem))
2784       return 0;
2785 
2786     switch (elem.id) {
2787       case MATROSKA_ID_S_ENTRY:
2788         lprintf("Seek Entry\n");
2789         if (!ebml_read_master (ebml, &elem))
2790           return 0;
2791         if ((elem.len > 0) && !parse_seek_entry(this))
2792           return 0;
2793         break;
2794       default:
2795         lprintf("Unhandled ID: 0x%x\n", elem.id);
2796         if (!ebml_skip(ebml, &elem))
2797           return 0;
2798     }
2799     next_level = ebml_get_next_level(ebml, &elem);
2800   }
2801 
2802   return 1;
2803 }
2804 
2805 
2806 /*
2807  * Function used to parse a top level when opening the file.
2808  * It does'nt parse clusters.
2809  * retuned value:
2810  *   0: error
2811  *   1: ok
2812  *   2: cluster
2813  */
parse_top_level_head(demux_matroska_t * this,int * next_level)2814 static int parse_top_level_head(demux_matroska_t *this, int *next_level) {
2815   ebml_parser_t *ebml = this->ebml;
2816   ebml_elem_t elem;
2817   int ret_value = 1;
2818   off_t current_pos;
2819 
2820 
2821   current_pos = this->input->get_current_pos(this->input);
2822   lprintf("current_pos: %" PRIdMAX "\n", (intmax_t)current_pos);
2823 
2824   if (!ebml_read_elem_head(ebml, &elem))
2825     return 0;
2826 
2827   if (!find_top_level_entry(this, current_pos)) {
2828 
2829     if (!add_top_level_entry(this, current_pos))
2830       return 0;
2831 
2832     switch (elem.id) {
2833       case MATROSKA_ID_SEEKHEAD:
2834         lprintf("SeekHead\n");
2835         if (!ebml_read_master (ebml, &elem))
2836           return 0;
2837         if ((elem.len > 0) && !parse_seekhead(this))
2838           return 0;
2839         break;
2840       case MATROSKA_ID_INFO:
2841         lprintf("Info\n");
2842         if (!ebml_read_master (ebml, &elem))
2843           return 0;
2844         if ((elem.len > 0) && !parse_info(this))
2845           return 0;
2846         break;
2847       case MATROSKA_ID_TRACKS:
2848         lprintf("Tracks\n");
2849         if (!ebml_read_master (ebml, &elem))
2850           return 0;
2851         if ((elem.len > 0) && !parse_tracks(this))
2852           return 0;
2853         break;
2854       case MATROSKA_ID_CHAPTERS:
2855         lprintf("Chapters\n");
2856         if (!ebml_read_master (ebml, &elem))
2857           return 0;
2858         if ((elem.len > 0) && !matroska_parse_chapters(this))
2859           return 0;
2860         break;
2861       case MATROSKA_ID_CLUSTER:
2862         lprintf("Slipping Cluster\n");
2863         if (!ebml_skip(ebml, &elem))
2864           return 0;
2865         ret_value = 2;
2866         break;
2867       case MATROSKA_ID_CUES:
2868         lprintf("Cues\n");
2869         if (!ebml_read_master (ebml, &elem))
2870           return 0;
2871         if ((elem.len > 0) && !parse_cues(this))
2872           return 0;
2873         break;
2874       case MATROSKA_ID_ATTACHMENTS:
2875         lprintf("Attachments\n");
2876         if (!ebml_read_master (ebml, &elem))
2877           return 0;
2878         if ((elem.len > 0) && !parse_attachments(this))
2879           return 0;
2880         break;
2881       case MATROSKA_ID_TAGS:
2882         lprintf("Tags\n");
2883         if (!ebml_read_master (ebml, &elem))
2884           return 0;
2885         if ((elem.len > 0) && !parse_tags(this))
2886           return 0;
2887         break;
2888       default:
2889         lprintf("unknown top_level ID: 0x%x\n", elem.id);
2890         if (!ebml_skip(ebml, &elem))
2891           return 0;
2892     }
2893   } else {
2894     lprintf("top_level entry already parsed, ID: 0x%x\n", elem.id);
2895     if (!ebml_skip(ebml, &elem))
2896       return 0;
2897   }
2898 
2899   if (next_level)
2900     *next_level = ebml_get_next_level(ebml, &elem);
2901 
2902   return ret_value;
2903 }
2904 
2905 /*
2906  * Function used to parse a top level element during the playback.
2907  * It skips all elements except clusters.
2908  * Others elements should have been parsed before by the send_headers() function.
2909  */
parse_top_level(demux_matroska_t * this,int * next_level)2910 static int parse_top_level(demux_matroska_t *this, int *next_level) {
2911   ebml_parser_t *ebml = this->ebml;
2912   ebml_elem_t elem;
2913   off_t cluster_pos, cluster_len;
2914 
2915   if (!ebml_read_elem_head(ebml, &elem))
2916     return 0;
2917 
2918   switch (elem.id) {
2919     case MATROSKA_ID_SEEKHEAD:
2920       lprintf("Skipping SeekHead\n");
2921       if (!ebml_skip(ebml, &elem))
2922         return 0;
2923       this->has_seekhead = 1;
2924       break;
2925     case MATROSKA_ID_INFO:
2926       lprintf("Skipping Info\n");
2927       if (!ebml_skip(ebml, &elem))
2928         return 0;
2929       break;
2930     case MATROSKA_ID_TRACKS:
2931       lprintf("Skipping Tracks\n");
2932       if (!ebml_skip(ebml, &elem))
2933         return 0;
2934       break;
2935     case MATROSKA_ID_CHAPTERS:
2936       lprintf("Skipping Chapters\n");
2937       if (!ebml_skip(ebml, &elem))
2938         return 0;
2939       break;
2940     case MATROSKA_ID_CLUSTER:
2941       lprintf("Cluster\n");
2942       cluster_pos = this->input->get_current_pos(this->input);
2943       cluster_len = elem.len;
2944       if (!ebml_read_master (ebml, &elem))
2945         return 0;
2946       if (!parse_cluster(this)) {
2947         off_t fail_pos = this->input->get_current_pos(this->input);
2948         off_t skip = cluster_pos + cluster_len - fail_pos;
2949         xprintf(ebml->xine, XINE_VERBOSITY_LOG, LOG_MODULE
2950                 "parse_cluster failed ! Skipping %" PRId64 " bytes\n", (int64_t)skip);
2951         if (this->input->seek(ebml->input, skip, SEEK_CUR) < 0) {
2952           xprintf(ebml->xine, XINE_VERBOSITY_LOG,
2953                   "seek error (skipping %" PRId64 " bytes)\n", (int64_t)skip);
2954         }
2955       }
2956       break;
2957     case MATROSKA_ID_CUES:
2958       lprintf("Skipping Cues\n");
2959       if (!ebml_skip(ebml, &elem))
2960         return 0;
2961       break;
2962     case MATROSKA_ID_ATTACHMENTS:
2963       lprintf("Skipping Attachments\n");
2964       if (!ebml_skip(ebml, &elem))
2965         return 0;
2966       break;
2967     case MATROSKA_ID_TAGS:
2968       lprintf("Skipping Tags\n");
2969       if (!ebml_skip(ebml, &elem))
2970         return 0;
2971       break;
2972 
2973     default:
2974       lprintf("Unhandled ID: 0x%x\n", elem.id);
2975       if (!ebml_skip(ebml, &elem))
2976         return 0;
2977   }
2978   if (next_level)
2979     *next_level = ebml_get_next_level(ebml, &elem);
2980 
2981   lprintf("parse_top_level() done\n");
2982   return 1;
2983 }
2984 
2985 /*
2986  * Parse the mkv file structure.
2987  */
parse_segment(demux_matroska_t * this)2988 static int parse_segment(demux_matroska_t *this) {
2989   ebml_parser_t *ebml = this->ebml;
2990 
2991   /* check segment id */
2992   if (!ebml_read_elem_head(ebml, &this->segment))
2993     return 0;
2994 
2995   if (this->segment.id == MATROSKA_ID_SEGMENT) {
2996     int res;
2997     int next_level;
2998 
2999     lprintf("Segment detected\n");
3000 
3001     if (!ebml_read_master (ebml, &this->segment))
3002       return 0;
3003 
3004     res = 1;
3005     next_level = 1;
3006     /* stop the loop on the first cluster */
3007     while ((next_level == 1) && (res == 1)) {
3008       res = parse_top_level_head(this, &next_level);
3009       if (!res)
3010         return 0;
3011     }
3012     return 1;
3013   } else {
3014     /* not a segment */
3015     xprintf(this->stream->xine, XINE_VERBOSITY_DEBUG,
3016             "demux_matroska: invalid segment\n");
3017     return 0;
3018   }
3019 }
3020 
demux_matroska_send_chunk(demux_plugin_t * this_gen)3021 static int demux_matroska_send_chunk (demux_plugin_t *this_gen) {
3022 
3023   demux_matroska_t *this = (demux_matroska_t *) this_gen;
3024   int next_level;
3025 
3026   if (!parse_top_level(this, &next_level)) {
3027     this->status = DEMUX_FINISHED;
3028   }
3029   return this->status;
3030 }
3031 
3032 
demux_matroska_get_status(demux_plugin_t * this_gen)3033 static int demux_matroska_get_status (demux_plugin_t *this_gen) {
3034   demux_matroska_t *this = (demux_matroska_t *) this_gen;
3035 
3036   return this->status;
3037 }
3038 
3039 
demux_matroska_send_headers(demux_plugin_t * this_gen)3040 static void demux_matroska_send_headers (demux_plugin_t *this_gen) {
3041 
3042   demux_matroska_t *this = (demux_matroska_t *) this_gen;
3043   int next_level;
3044 
3045   _x_demux_control_start (this->stream);
3046 
3047   if (!parse_segment(this))
3048     this->status = DEMUX_FINISHED;
3049   else
3050     this->status = DEMUX_OK;
3051 
3052   _x_stream_info_set(this->stream, XINE_STREAM_INFO_HAS_VIDEO, (this->num_video_tracks != 0));
3053   _x_stream_info_set(this->stream, XINE_STREAM_INFO_HAS_AUDIO, (this->num_audio_tracks != 0));
3054 
3055 
3056   /*
3057    * send preview buffers
3058    */
3059 
3060   /* enter in the segment */
3061   if (!ebml_read_master (this->ebml, &this->segment)) {
3062     xprintf(this->stream->xine, XINE_VERBOSITY_DEBUG,
3063             "demux_matroska: failed to read file header\n");
3064     this->status = DEMUX_FINISHED;
3065     return;
3066   }
3067 
3068   /* seek back to the beginning of the segment */
3069   next_level = 1;
3070   if (this->input->seek(this->input, this->segment.start, SEEK_SET) < 0) {
3071     xprintf(this->stream->xine, XINE_VERBOSITY_DEBUG,
3072             "demux_matroska: failed to seek to pos: %" PRIdMAX "\n",
3073             (intmax_t)this->segment.start);
3074     this->status = DEMUX_FINISHED;
3075     return;
3076   }
3077 
3078   this->preview_sent = 0;
3079   this->preview_mode = 1;
3080 
3081   while ((this->preview_sent < NUM_PREVIEW_BUFFERS) && (next_level == 1)) {
3082     if (!parse_top_level (this, &next_level)) {
3083       break;
3084     }
3085   }
3086   this->preview_mode = 0;
3087 
3088   /* seek back to the beginning of the segment */
3089   next_level = 1;
3090   if (this->input->seek(this->input, this->segment.start, SEEK_SET) < 0) {
3091     xprintf(this->stream->xine, XINE_VERBOSITY_DEBUG,
3092             "demux_matroska: failed to seek to pos: %" PRIdMAX "\n",
3093             (intmax_t)this->segment.start);
3094     this->status = DEMUX_FINISHED;
3095   }
3096 }
3097 
3098 
3099 /* support function that performs a binary seek on a track; returns the
3100  * best index entry or -1 if the seek was beyond the end of the file */
binary_seek(matroska_index_t * index,off_t start_pos,int start_time)3101 static int binary_seek(matroska_index_t *index, off_t start_pos,
3102                        int start_time) {
3103   int best_index;
3104   int left, middle, right;
3105   int found;
3106   uint32_t stime = start_time < 0 ? 0 : start_time;
3107 
3108   /* perform a binary search on the trak, testing the offset
3109    * boundaries first; offset request has precedent over time request */
3110   if (start_pos) {
3111     if (start_pos <= index->pos[0])
3112       best_index = 0;
3113     else if (start_pos >= index->pos[index->num_entries - 1])
3114       best_index = index->num_entries - 1;
3115     else {
3116       left = 0;
3117       right = index->num_entries - 1;
3118       found = 0;
3119 
3120       while (!found) {
3121         middle = (left + right + 1) / 2;
3122         if ((start_pos >= index->pos[middle]) &&
3123             (start_pos < index->pos[middle + 1]))
3124           found = 1;
3125         else if ((uint32_t)start_pos < index->pos[middle])
3126           right = middle - 1;
3127         else
3128           left = middle;
3129       }
3130 
3131       best_index = middle;
3132     }
3133   } else {
3134     if (stime <= index->timecode[0])
3135       best_index = 0;
3136     else if (stime >= index->timecode[index->num_entries - 1])
3137       best_index = index->num_entries - 1;
3138     else {
3139       left = 0;
3140       right = index->num_entries - 1;
3141       do {
3142         middle = (left + right + 1) / 2;
3143         if (stime < index->timecode[middle])
3144           right = (middle - 1);
3145         else
3146           left = middle;
3147       } while (left < right);
3148 
3149       best_index = left;
3150     }
3151   }
3152 
3153   return best_index;
3154 }
3155 
3156 
demux_matroska_seek(demux_plugin_t * this_gen,off_t start_pos,int start_time,int playing)3157 static int demux_matroska_seek (demux_plugin_t *this_gen,
3158                                 off_t start_pos, int start_time, int playing) {
3159 
3160   demux_matroska_t *this = (demux_matroska_t *) this_gen;
3161   matroska_index_t *index;
3162   matroska_track_t *track;
3163   int i, entry;
3164 
3165   (void)playing;
3166 
3167   start_pos = (off_t) ( (double) start_pos / 65535 *
3168     this->input->get_length (this->input) );
3169 
3170   this->status = DEMUX_OK;
3171 
3172   /* engine sync stuff */
3173   for (i = 0; i < this->num_tracks; i++) {
3174     this->tracks[i]->last_pts = 0;
3175   }
3176   this->send_newpts   = 1;
3177   this->buf_flag_seek = 1;
3178 
3179   /* Seeking without an index is not supported yet. */
3180   if (!this->num_indexes)
3181     return this->status;
3182 
3183   /* Find an index for a video track and use the first available index
3184      otherwise. */
3185   index = NULL;
3186   for (i = 0; i < this->num_indexes; i++) {
3187     if (this->indexes[i].num_entries == 0)
3188       continue;
3189     if ((find_track_by_id(this, this->indexes[i].track_num, &track)) &&
3190         (track->track_type == MATROSKA_TRACK_VIDEO)) {
3191       lprintf("video track found\n");
3192       index = &this->indexes[i];
3193       break;
3194     }
3195   }
3196   if (index == NULL)
3197     for (i = 0; i < this->num_indexes; i++) {
3198       if (this->indexes[i].num_entries == 0)
3199         continue;
3200       if (find_track_by_id(this, this->indexes[i].track_num, &track)) {
3201         index = &this->indexes[i];
3202         break;
3203       }
3204     }
3205 
3206   /* No suitable index found. */
3207   if (index == NULL)
3208     return this->status;
3209 
3210   entry = binary_seek(index, start_pos, start_time);
3211   if (entry == -1) {
3212     lprintf("seeking for track %d to %s %" PRIdMAX " - no entry found/EOS.\n",
3213             index->track_num, start_pos ? "pos" : "time",
3214             start_pos ? (intmax_t)start_pos : (intmax_t)start_time);
3215     this->status = DEMUX_FINISHED;
3216 
3217   } else {
3218     lprintf("seeking for track %d to %s %" PRIdMAX ". decision is #%d at %" PRIu64 "/%" PRIdMAX "\n",
3219             index->track_num, start_pos ? "pos" : "time",
3220             start_pos ? (intmax_t)start_pos : (intmax_t)start_time,
3221             index->track_num, index->timecode[entry], (intmax_t)index->pos[entry]);
3222 
3223     if (this->input->seek(this->input, index->pos[entry], SEEK_SET) < 0)
3224       this->status = DEMUX_FINISHED;
3225 
3226     /* we always seek to the ebml level 1 */
3227     this->ebml->level = 1;
3228 
3229     this->skip_to_timecode = index->timecode[entry];
3230     this->skip_for_track = track->track_num;
3231     _x_demux_flush_engine(this->stream);
3232   }
3233 
3234   return this->status;
3235 }
3236 
3237 
demux_matroska_dispose(demux_plugin_t * this_gen)3238 static void demux_matroska_dispose (demux_plugin_t *this_gen) {
3239 
3240   demux_matroska_t *this = (demux_matroska_t *) this_gen;
3241   int i;
3242 
3243   _x_freep (&this->block_data);
3244 
3245   /* free tracks */
3246   for (i = 0; i < this->num_tracks; i++) {
3247     matroska_track_t *const track = this->tracks[i];
3248 
3249     _x_freep (&track->language);
3250     _x_freep (&track->codec_id);
3251     _x_freep (&track->codec_private);
3252     _x_freep (&track->video_track);
3253     _x_freep (&track->audio_track);
3254     _x_freep (&track->sub_track);
3255 
3256     _x_freep (&this->tracks[i]);
3257   }
3258   /* Free the cues. */
3259   for (i = 0; i < this->num_indexes; i++) {
3260     _x_freep(&this->indexes[i].pos);
3261     _x_freep(&this->indexes[i].timecode);
3262   }
3263   _x_freep(&this->indexes);
3264 
3265   /* Free the top_level elem list */
3266   _x_freep(&this->top_level_list);
3267 
3268   _x_freep(&this->title);
3269 
3270   matroska_free_editions(this);
3271 
3272   dispose_ebml_parser(this->ebml);
3273   xine_event_dispose_queue(this->event_queue);
3274   free (this);
3275 }
3276 
3277 
demux_matroska_get_stream_length(demux_plugin_t * this_gen)3278 static int demux_matroska_get_stream_length (demux_plugin_t *this_gen) {
3279 
3280   demux_matroska_t *this = (demux_matroska_t *) this_gen;
3281 
3282   return (int)this->duration;
3283 }
3284 
3285 
demux_matroska_get_capabilities(demux_plugin_t * this_gen)3286 static uint32_t demux_matroska_get_capabilities (demux_plugin_t *this_gen) {
3287   demux_matroska_t* this = (demux_matroska_t*)this_gen;
3288   uint32_t caps = DEMUX_CAP_SPULANG | DEMUX_CAP_AUDIOLANG;
3289 
3290   if(this->num_editions > 0 && this->editions[0]->num_chapters > 0)
3291     caps |= DEMUX_CAP_CHAPTERS;
3292 
3293   return caps;
3294 }
3295 
3296 
demux_matroska_get_optional_data(demux_plugin_t * this_gen,void * data,int data_type)3297 static int demux_matroska_get_optional_data (demux_plugin_t *this_gen,
3298                                              void *data, int data_type) {
3299   demux_matroska_t *this = (demux_matroska_t *) this_gen;
3300   char *str = (char *) data;
3301   int channel = *((int *)data);
3302   int track_num;
3303 
3304   switch (data_type) {
3305     case DEMUX_OPTIONAL_DATA_SPULANG:
3306       lprintf ("DEMUX_OPTIONAL_DATA_SPULANG channel = %d\n",channel);
3307       if ((channel >= 0) && (channel < this->num_sub_tracks)) {
3308         for (track_num = 0; track_num < this->num_tracks; track_num++) {
3309           matroska_track_t *track = this->tracks[track_num];
3310 
3311           if ((int)(track->buf_type & 0xFF00001F) == (BUF_SPU_BASE + channel)) {
3312             if (track->language) {
3313               strncpy (str, track->language, XINE_LANG_MAX);
3314               str[XINE_LANG_MAX - 1] = '\0';
3315               if (strlen(track->language) >= XINE_LANG_MAX)
3316                 /* the string got truncated */
3317                 str[XINE_LANG_MAX - 2] = str[XINE_LANG_MAX - 3] = str[XINE_LANG_MAX - 4] = '.';
3318             } else {
3319               snprintf(str, XINE_LANG_MAX, "eng");
3320             }
3321             return DEMUX_OPTIONAL_SUCCESS;
3322           }
3323         }
3324       }
3325       return DEMUX_OPTIONAL_UNSUPPORTED;
3326 
3327     case DEMUX_OPTIONAL_DATA_AUDIOLANG:
3328       lprintf ("DEMUX_OPTIONAL_DATA_AUDIOLANG channel = %d\n",channel);
3329       if ((channel >= 0) && (channel < this->num_audio_tracks)) {
3330         for (track_num = 0; track_num < this->num_tracks; track_num++) {
3331           matroska_track_t *track = this->tracks[track_num];
3332 
3333           if ((int)(track->buf_type & 0xFF00001F) == (BUF_AUDIO_BASE + channel)) {
3334             if (track->language) {
3335               strncpy (str, track->language, XINE_LANG_MAX);
3336               str[XINE_LANG_MAX - 1] = '\0';
3337               if (strlen(track->language) >= XINE_LANG_MAX)
3338                 /* the string got truncated */
3339                 str[XINE_LANG_MAX - 2] = str[XINE_LANG_MAX - 3] = str[XINE_LANG_MAX - 4] = '.';
3340             } else {
3341               snprintf(str, XINE_LANG_MAX, "eng");
3342             }
3343             return DEMUX_OPTIONAL_SUCCESS;
3344           }
3345         }
3346       }
3347       return DEMUX_OPTIONAL_UNSUPPORTED;
3348 
3349     default:
3350       return DEMUX_OPTIONAL_UNSUPPORTED;
3351   }
3352 }
3353 
open_plugin(demux_class_t * class_gen,xine_stream_t * stream,input_plugin_t * input)3354 static demux_plugin_t *open_plugin (demux_class_t *class_gen, xine_stream_t *stream,
3355                                     input_plugin_t *input) {
3356 
3357   demux_matroska_t *this = NULL;
3358   ebml_parser_t    *ebml = NULL;
3359 
3360   lprintf("trying to open %s...\n", input->get_mrl(input));
3361 
3362   switch (stream->content_detection_method) {
3363 
3364   case METHOD_BY_CONTENT: {
3365     if (!(input->get_capabilities (input) & INPUT_CAP_SEEKABLE))
3366       return NULL;
3367     if (input->seek(input, 0, SEEK_SET) != 0)
3368       return NULL;
3369     ebml = new_ebml_parser(stream->xine, input);
3370     if (!ebml)
3371       goto error;
3372     if (!ebml_check_header(ebml))
3373       goto error;
3374   }
3375   break;
3376 
3377   case METHOD_BY_MRL:
3378   case METHOD_EXPLICIT:
3379   break;
3380 
3381   default:
3382     return NULL;
3383   }
3384 
3385   this = calloc(1, sizeof(demux_matroska_t));
3386   if (!this)
3387     goto error;
3388 
3389   this->demux_plugin.send_headers      = demux_matroska_send_headers;
3390   this->demux_plugin.send_chunk        = demux_matroska_send_chunk;
3391   this->demux_plugin.seek              = demux_matroska_seek;
3392   this->demux_plugin.dispose           = demux_matroska_dispose;
3393   this->demux_plugin.get_status        = demux_matroska_get_status;
3394   this->demux_plugin.get_stream_length = demux_matroska_get_stream_length;
3395   this->demux_plugin.get_capabilities  = demux_matroska_get_capabilities;
3396   this->demux_plugin.get_optional_data = demux_matroska_get_optional_data;
3397   this->demux_plugin.demux_class       = class_gen;
3398 
3399   this->input      = input;
3400   this->status     = DEMUX_FINISHED;
3401   this->stream     = stream;
3402 
3403   if (!ebml) {
3404     ebml = new_ebml_parser(stream->xine, input);
3405     if (!ebml)
3406       goto error;
3407     if (!ebml_check_header(ebml))
3408       goto error;
3409   }
3410   this->ebml = ebml;
3411 
3412   /* check header fields */
3413   if (ebml->max_id_len > 4)
3414     goto error;
3415   if (ebml->max_size_len > 8)
3416     goto error;
3417   /* handle both Matroska and WebM here; we don't (presently) differentiate */
3418   if (!ebml->doctype || (strcmp(ebml->doctype, "matroska") && strcmp(ebml->doctype, "webm")))
3419     goto error;
3420 
3421   this->event_queue = xine_event_new_queue(this->stream);
3422 
3423   return &this->demux_plugin;
3424 
3425 error:
3426   dispose_ebml_parser(ebml);
3427 
3428   if (this != NULL && this->event_queue != NULL) {
3429     xine_event_dispose_queue(this->event_queue);
3430   }
3431   free(this);
3432 
3433   return NULL;
3434 }
3435 
3436 
3437 /*
3438  * demux matroska class
3439  */
demux_matroska_init_class(xine_t * xine,const void * data)3440 void *demux_matroska_init_class (xine_t *xine, const void *data) {
3441 
3442   (void)xine;
3443   (void)data;
3444 
3445   static const demux_class_t demux_matroska_class = {
3446     .open_plugin     = open_plugin,
3447     .description     = N_("matroska & webm demux plugin"),
3448     .identifier      = "matroska",
3449     .mimetypes       =
3450       "video/mkv: mkv: matroska;"
3451       "video/x-matroska: mkv: matroska;"
3452       "video/webm: wbm,webm: WebM;",
3453     .extensions      = "mkv wbm webm",
3454     .dispose         = NULL,
3455   };
3456 
3457   return (void *)&demux_matroska_class;
3458 }
3459 
3460