You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2055 lines
74KB

  1. /*
  2. * Matroska file demuxer
  3. * Copyright (c) 2003-2008 The Libav Project
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * Matroska file demuxer
  24. * @author Ronald Bultje <rbultje@ronald.bitfreak.net>
  25. * @author with a little help from Moritz Bunkus <moritz@bunkus.org>
  26. * @author totally reworked by Aurelien Jacobs <aurel@gnuage.org>
  27. * @see specs available on the Matroska project page: http://www.matroska.org/
  28. */
  29. #include <stdio.h>
  30. #include "avformat.h"
  31. #include "internal.h"
  32. #include "avio_internal.h"
  33. /* For ff_codec_get_id(). */
  34. #include "riff.h"
  35. #include "isom.h"
  36. #include "rm.h"
  37. #include "matroska.h"
  38. #include "libavcodec/mpeg4audio.h"
  39. #include "libavutil/intfloat.h"
  40. #include "libavutil/intreadwrite.h"
  41. #include "libavutil/avstring.h"
  42. #include "libavutil/lzo.h"
  43. #include "libavutil/dict.h"
  44. #if CONFIG_ZLIB
  45. #include <zlib.h>
  46. #endif
  47. #if CONFIG_BZLIB
  48. #include <bzlib.h>
  49. #endif
  50. typedef enum {
  51. EBML_NONE,
  52. EBML_UINT,
  53. EBML_FLOAT,
  54. EBML_STR,
  55. EBML_UTF8,
  56. EBML_BIN,
  57. EBML_NEST,
  58. EBML_PASS,
  59. EBML_STOP,
  60. EBML_TYPE_COUNT
  61. } EbmlType;
  62. typedef const struct EbmlSyntax {
  63. uint32_t id;
  64. EbmlType type;
  65. int list_elem_size;
  66. int data_offset;
  67. union {
  68. uint64_t u;
  69. double f;
  70. const char *s;
  71. const struct EbmlSyntax *n;
  72. } def;
  73. } EbmlSyntax;
  74. typedef struct {
  75. int nb_elem;
  76. void *elem;
  77. } EbmlList;
  78. typedef struct {
  79. int size;
  80. uint8_t *data;
  81. int64_t pos;
  82. } EbmlBin;
  83. typedef struct {
  84. uint64_t version;
  85. uint64_t max_size;
  86. uint64_t id_length;
  87. char *doctype;
  88. uint64_t doctype_version;
  89. } Ebml;
  90. typedef struct {
  91. uint64_t algo;
  92. EbmlBin settings;
  93. } MatroskaTrackCompression;
  94. typedef struct {
  95. uint64_t scope;
  96. uint64_t type;
  97. MatroskaTrackCompression compression;
  98. } MatroskaTrackEncoding;
  99. typedef struct {
  100. double frame_rate;
  101. uint64_t display_width;
  102. uint64_t display_height;
  103. uint64_t pixel_width;
  104. uint64_t pixel_height;
  105. uint64_t fourcc;
  106. } MatroskaTrackVideo;
  107. typedef struct {
  108. double samplerate;
  109. double out_samplerate;
  110. uint64_t bitdepth;
  111. uint64_t channels;
  112. /* real audio header (extracted from extradata) */
  113. int coded_framesize;
  114. int sub_packet_h;
  115. int frame_size;
  116. int sub_packet_size;
  117. int sub_packet_cnt;
  118. int pkt_cnt;
  119. uint64_t buf_timecode;
  120. uint8_t *buf;
  121. } MatroskaTrackAudio;
  122. typedef struct {
  123. uint64_t num;
  124. uint64_t uid;
  125. uint64_t type;
  126. char *name;
  127. char *codec_id;
  128. EbmlBin codec_priv;
  129. char *language;
  130. double time_scale;
  131. uint64_t default_duration;
  132. uint64_t flag_default;
  133. uint64_t flag_forced;
  134. MatroskaTrackVideo video;
  135. MatroskaTrackAudio audio;
  136. EbmlList encodings;
  137. AVStream *stream;
  138. int64_t end_timecode;
  139. int ms_compat;
  140. } MatroskaTrack;
  141. typedef struct {
  142. uint64_t uid;
  143. char *filename;
  144. char *mime;
  145. EbmlBin bin;
  146. AVStream *stream;
  147. } MatroskaAttachement;
  148. typedef struct {
  149. uint64_t start;
  150. uint64_t end;
  151. uint64_t uid;
  152. char *title;
  153. AVChapter *chapter;
  154. } MatroskaChapter;
  155. typedef struct {
  156. uint64_t track;
  157. uint64_t pos;
  158. } MatroskaIndexPos;
  159. typedef struct {
  160. uint64_t time;
  161. EbmlList pos;
  162. } MatroskaIndex;
  163. typedef struct {
  164. char *name;
  165. char *string;
  166. char *lang;
  167. uint64_t def;
  168. EbmlList sub;
  169. } MatroskaTag;
  170. typedef struct {
  171. char *type;
  172. uint64_t typevalue;
  173. uint64_t trackuid;
  174. uint64_t chapteruid;
  175. uint64_t attachuid;
  176. } MatroskaTagTarget;
  177. typedef struct {
  178. MatroskaTagTarget target;
  179. EbmlList tag;
  180. } MatroskaTags;
  181. typedef struct {
  182. uint64_t id;
  183. uint64_t pos;
  184. } MatroskaSeekhead;
  185. typedef struct {
  186. uint64_t start;
  187. uint64_t length;
  188. } MatroskaLevel;
  189. typedef struct {
  190. AVFormatContext *ctx;
  191. /* EBML stuff */
  192. int num_levels;
  193. MatroskaLevel levels[EBML_MAX_DEPTH];
  194. int level_up;
  195. uint32_t current_id;
  196. uint64_t time_scale;
  197. double duration;
  198. char *title;
  199. EbmlList tracks;
  200. EbmlList attachments;
  201. EbmlList chapters;
  202. EbmlList index;
  203. EbmlList tags;
  204. EbmlList seekhead;
  205. /* byte position of the segment inside the stream */
  206. int64_t segment_start;
  207. /* the packet queue */
  208. AVPacket **packets;
  209. int num_packets;
  210. AVPacket *prev_pkt;
  211. int done;
  212. /* What to skip before effectively reading a packet. */
  213. int skip_to_keyframe;
  214. uint64_t skip_to_timecode;
  215. /* File has a CUES element, but we defer parsing until it is needed. */
  216. int cues_parsing_deferred;
  217. } MatroskaDemuxContext;
  218. typedef struct {
  219. uint64_t duration;
  220. int64_t reference;
  221. uint64_t non_simple;
  222. EbmlBin bin;
  223. } MatroskaBlock;
  224. typedef struct {
  225. uint64_t timecode;
  226. EbmlList blocks;
  227. } MatroskaCluster;
  228. static EbmlSyntax ebml_header[] = {
  229. { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
  230. { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
  231. { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
  232. { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
  233. { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
  234. { EBML_ID_EBMLVERSION, EBML_NONE },
  235. { EBML_ID_DOCTYPEVERSION, EBML_NONE },
  236. { 0 }
  237. };
  238. static EbmlSyntax ebml_syntax[] = {
  239. { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
  240. { 0 }
  241. };
  242. static EbmlSyntax matroska_info[] = {
  243. { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
  244. { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
  245. { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
  246. { MATROSKA_ID_WRITINGAPP, EBML_NONE },
  247. { MATROSKA_ID_MUXINGAPP, EBML_NONE },
  248. { MATROSKA_ID_DATEUTC, EBML_NONE },
  249. { MATROSKA_ID_SEGMENTUID, EBML_NONE },
  250. { 0 }
  251. };
  252. static EbmlSyntax matroska_track_video[] = {
  253. { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
  254. { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
  255. { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
  256. { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
  257. { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
  258. { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
  259. { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
  260. { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
  261. { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
  262. { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
  263. { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
  264. { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
  265. { MATROSKA_ID_VIDEOSTEREOMODE, EBML_NONE },
  266. { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
  267. { 0 }
  268. };
  269. static EbmlSyntax matroska_track_audio[] = {
  270. { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
  271. { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
  272. { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
  273. { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
  274. { 0 }
  275. };
  276. static EbmlSyntax matroska_track_encoding_compression[] = {
  277. { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
  278. { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
  279. { 0 }
  280. };
  281. static EbmlSyntax matroska_track_encoding[] = {
  282. { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
  283. { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
  284. { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
  285. { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
  286. { 0 }
  287. };
  288. static EbmlSyntax matroska_track_encodings[] = {
  289. { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
  290. { 0 }
  291. };
  292. static EbmlSyntax matroska_track[] = {
  293. { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
  294. { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
  295. { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
  296. { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
  297. { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
  298. { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
  299. { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
  300. { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
  301. { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
  302. { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
  303. { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
  304. { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
  305. { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
  306. { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
  307. { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
  308. { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
  309. { MATROSKA_ID_CODECNAME, EBML_NONE },
  310. { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
  311. { MATROSKA_ID_CODECINFOURL, EBML_NONE },
  312. { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
  313. { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
  314. { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
  315. { MATROSKA_ID_TRACKMAXBLKADDID, EBML_NONE },
  316. { 0 }
  317. };
  318. static EbmlSyntax matroska_tracks[] = {
  319. { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
  320. { 0 }
  321. };
  322. static EbmlSyntax matroska_attachment[] = {
  323. { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
  324. { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
  325. { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
  326. { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
  327. { MATROSKA_ID_FILEDESC, EBML_NONE },
  328. { 0 }
  329. };
  330. static EbmlSyntax matroska_attachments[] = {
  331. { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
  332. { 0 }
  333. };
  334. static EbmlSyntax matroska_chapter_display[] = {
  335. { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
  336. { MATROSKA_ID_CHAPLANG, EBML_NONE },
  337. { 0 }
  338. };
  339. static EbmlSyntax matroska_chapter_entry[] = {
  340. { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
  341. { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
  342. { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
  343. { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
  344. { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
  345. { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
  346. { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
  347. { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
  348. { 0 }
  349. };
  350. static EbmlSyntax matroska_chapter[] = {
  351. { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
  352. { MATROSKA_ID_EDITIONUID, EBML_NONE },
  353. { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
  354. { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
  355. { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
  356. { 0 }
  357. };
  358. static EbmlSyntax matroska_chapters[] = {
  359. { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
  360. { 0 }
  361. };
  362. static EbmlSyntax matroska_index_pos[] = {
  363. { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
  364. { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
  365. { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
  366. { 0 }
  367. };
  368. static EbmlSyntax matroska_index_entry[] = {
  369. { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
  370. { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
  371. { 0 }
  372. };
  373. static EbmlSyntax matroska_index[] = {
  374. { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
  375. { 0 }
  376. };
  377. static EbmlSyntax matroska_simpletag[] = {
  378. { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
  379. { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
  380. { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
  381. { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
  382. { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
  383. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
  384. { 0 }
  385. };
  386. static EbmlSyntax matroska_tagtargets[] = {
  387. { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget,type) },
  388. { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
  389. { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
  390. { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
  391. { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
  392. { 0 }
  393. };
  394. static EbmlSyntax matroska_tag[] = {
  395. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
  396. { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
  397. { 0 }
  398. };
  399. static EbmlSyntax matroska_tags[] = {
  400. { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
  401. { 0 }
  402. };
  403. static EbmlSyntax matroska_seekhead_entry[] = {
  404. { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
  405. { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
  406. { 0 }
  407. };
  408. static EbmlSyntax matroska_seekhead[] = {
  409. { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
  410. { 0 }
  411. };
  412. static EbmlSyntax matroska_segment[] = {
  413. { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
  414. { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
  415. { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
  416. { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
  417. { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
  418. { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
  419. { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
  420. { MATROSKA_ID_CLUSTER, EBML_STOP },
  421. { 0 }
  422. };
  423. static EbmlSyntax matroska_segments[] = {
  424. { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
  425. { 0 }
  426. };
  427. static EbmlSyntax matroska_blockgroup[] = {
  428. { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
  429. { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
  430. { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
  431. { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
  432. { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
  433. { 0 }
  434. };
  435. static EbmlSyntax matroska_cluster[] = {
  436. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  437. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  438. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  439. { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
  440. { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
  441. { 0 }
  442. };
  443. static EbmlSyntax matroska_clusters[] = {
  444. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
  445. { MATROSKA_ID_INFO, EBML_NONE },
  446. { MATROSKA_ID_CUES, EBML_NONE },
  447. { MATROSKA_ID_TAGS, EBML_NONE },
  448. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  449. { 0 }
  450. };
  451. static const char *const matroska_doctypes[] = { "matroska", "webm" };
  452. /*
  453. * Return: Whether we reached the end of a level in the hierarchy or not.
  454. */
  455. static int ebml_level_end(MatroskaDemuxContext *matroska)
  456. {
  457. AVIOContext *pb = matroska->ctx->pb;
  458. int64_t pos = avio_tell(pb);
  459. if (matroska->num_levels > 0) {
  460. MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
  461. if (pos - level->start >= level->length || matroska->current_id) {
  462. matroska->num_levels--;
  463. return 1;
  464. }
  465. }
  466. return 0;
  467. }
  468. /*
  469. * Read: an "EBML number", which is defined as a variable-length
  470. * array of bytes. The first byte indicates the length by giving a
  471. * number of 0-bits followed by a one. The position of the first
  472. * "one" bit inside the first byte indicates the length of this
  473. * number.
  474. * Returns: number of bytes read, < 0 on error
  475. */
  476. static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
  477. int max_size, uint64_t *number)
  478. {
  479. int read = 1, n = 1;
  480. uint64_t total = 0;
  481. /* The first byte tells us the length in bytes - avio_r8() can normally
  482. * return 0, but since that's not a valid first ebmlID byte, we can
  483. * use it safely here to catch EOS. */
  484. if (!(total = avio_r8(pb))) {
  485. /* we might encounter EOS here */
  486. if (!pb->eof_reached) {
  487. int64_t pos = avio_tell(pb);
  488. av_log(matroska->ctx, AV_LOG_ERROR,
  489. "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
  490. pos, pos);
  491. }
  492. return AVERROR(EIO); /* EOS or actual I/O error */
  493. }
  494. /* get the length of the EBML number */
  495. read = 8 - ff_log2_tab[total];
  496. if (read > max_size) {
  497. int64_t pos = avio_tell(pb) - 1;
  498. av_log(matroska->ctx, AV_LOG_ERROR,
  499. "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
  500. (uint8_t) total, pos, pos);
  501. return AVERROR_INVALIDDATA;
  502. }
  503. /* read out length */
  504. total ^= 1 << ff_log2_tab[total];
  505. while (n++ < read)
  506. total = (total << 8) | avio_r8(pb);
  507. *number = total;
  508. return read;
  509. }
  510. /**
  511. * Read a EBML length value.
  512. * This needs special handling for the "unknown length" case which has multiple
  513. * encodings.
  514. */
  515. static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
  516. uint64_t *number)
  517. {
  518. int res = ebml_read_num(matroska, pb, 8, number);
  519. if (res > 0 && *number + 1 == 1ULL << (7 * res))
  520. *number = 0xffffffffffffffULL;
  521. return res;
  522. }
  523. /*
  524. * Read the next element as an unsigned int.
  525. * 0 is success, < 0 is failure.
  526. */
  527. static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
  528. {
  529. int n = 0;
  530. if (size > 8)
  531. return AVERROR_INVALIDDATA;
  532. /* big-endian ordering; build up number */
  533. *num = 0;
  534. while (n++ < size)
  535. *num = (*num << 8) | avio_r8(pb);
  536. return 0;
  537. }
  538. /*
  539. * Read the next element as a float.
  540. * 0 is success, < 0 is failure.
  541. */
  542. static int ebml_read_float(AVIOContext *pb, int size, double *num)
  543. {
  544. if (size == 0) {
  545. *num = 0;
  546. } else if (size == 4) {
  547. *num = av_int2float(avio_rb32(pb));
  548. } else if (size == 8){
  549. *num = av_int2double(avio_rb64(pb));
  550. } else
  551. return AVERROR_INVALIDDATA;
  552. return 0;
  553. }
  554. /*
  555. * Read the next element as an ASCII string.
  556. * 0 is success, < 0 is failure.
  557. */
  558. static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
  559. {
  560. char *res;
  561. /* EBML strings are usually not 0-terminated, so we allocate one
  562. * byte more, read the string and NULL-terminate it ourselves. */
  563. if (!(res = av_malloc(size + 1)))
  564. return AVERROR(ENOMEM);
  565. if (avio_read(pb, (uint8_t *) res, size) != size) {
  566. av_free(res);
  567. return AVERROR(EIO);
  568. }
  569. (res)[size] = '\0';
  570. av_free(*str);
  571. *str = res;
  572. return 0;
  573. }
  574. /*
  575. * Read the next element as binary data.
  576. * 0 is success, < 0 is failure.
  577. */
  578. static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
  579. {
  580. av_free(bin->data);
  581. if (!(bin->data = av_malloc(length)))
  582. return AVERROR(ENOMEM);
  583. bin->size = length;
  584. bin->pos = avio_tell(pb);
  585. if (avio_read(pb, bin->data, length) != length) {
  586. av_freep(&bin->data);
  587. return AVERROR(EIO);
  588. }
  589. return 0;
  590. }
  591. /*
  592. * Read the next element, but only the header. The contents
  593. * are supposed to be sub-elements which can be read separately.
  594. * 0 is success, < 0 is failure.
  595. */
  596. static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
  597. {
  598. AVIOContext *pb = matroska->ctx->pb;
  599. MatroskaLevel *level;
  600. if (matroska->num_levels >= EBML_MAX_DEPTH) {
  601. av_log(matroska->ctx, AV_LOG_ERROR,
  602. "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  603. return AVERROR(ENOSYS);
  604. }
  605. level = &matroska->levels[matroska->num_levels++];
  606. level->start = avio_tell(pb);
  607. level->length = length;
  608. return 0;
  609. }
  610. /*
  611. * Read signed/unsigned "EBML" numbers.
  612. * Return: number of bytes processed, < 0 on error
  613. */
  614. static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
  615. uint8_t *data, uint32_t size, uint64_t *num)
  616. {
  617. AVIOContext pb;
  618. ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
  619. return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
  620. }
  621. /*
  622. * Same as above, but signed.
  623. */
  624. static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
  625. uint8_t *data, uint32_t size, int64_t *num)
  626. {
  627. uint64_t unum;
  628. int res;
  629. /* read as unsigned number first */
  630. if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
  631. return res;
  632. /* make signed (weird way) */
  633. *num = unum - ((1LL << (7*res - 1)) - 1);
  634. return res;
  635. }
  636. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  637. EbmlSyntax *syntax, void *data);
  638. static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  639. uint32_t id, void *data)
  640. {
  641. int i;
  642. for (i=0; syntax[i].id; i++)
  643. if (id == syntax[i].id)
  644. break;
  645. if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
  646. matroska->num_levels > 0 &&
  647. matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
  648. return 0; // we reached the end of an unknown size cluster
  649. if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
  650. av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
  651. return ebml_parse_elem(matroska, &syntax[i], data);
  652. }
  653. static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  654. void *data)
  655. {
  656. if (!matroska->current_id) {
  657. uint64_t id;
  658. int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
  659. if (res < 0)
  660. return res;
  661. matroska->current_id = id | 1 << 7*res;
  662. }
  663. return ebml_parse_id(matroska, syntax, matroska->current_id, data);
  664. }
  665. static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  666. void *data)
  667. {
  668. int i, res = 0;
  669. for (i=0; syntax[i].id; i++)
  670. switch (syntax[i].type) {
  671. case EBML_UINT:
  672. *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
  673. break;
  674. case EBML_FLOAT:
  675. *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
  676. break;
  677. case EBML_STR:
  678. case EBML_UTF8:
  679. *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
  680. break;
  681. }
  682. while (!res && !ebml_level_end(matroska))
  683. res = ebml_parse(matroska, syntax, data);
  684. return res;
  685. }
  686. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  687. EbmlSyntax *syntax, void *data)
  688. {
  689. static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
  690. [EBML_UINT] = 8,
  691. [EBML_FLOAT] = 8,
  692. // max. 16 MB for strings
  693. [EBML_STR] = 0x1000000,
  694. [EBML_UTF8] = 0x1000000,
  695. // max. 256 MB for binary data
  696. [EBML_BIN] = 0x10000000,
  697. // no limits for anything else
  698. };
  699. AVIOContext *pb = matroska->ctx->pb;
  700. uint32_t id = syntax->id;
  701. uint64_t length;
  702. int res;
  703. void *newelem;
  704. data = (char *)data + syntax->data_offset;
  705. if (syntax->list_elem_size) {
  706. EbmlList *list = data;
  707. newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
  708. if (!newelem)
  709. return AVERROR(ENOMEM);
  710. list->elem = newelem;
  711. data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
  712. memset(data, 0, syntax->list_elem_size);
  713. list->nb_elem++;
  714. }
  715. if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
  716. matroska->current_id = 0;
  717. if ((res = ebml_read_length(matroska, pb, &length)) < 0)
  718. return res;
  719. if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
  720. av_log(matroska->ctx, AV_LOG_ERROR,
  721. "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
  722. length, max_lengths[syntax->type], syntax->type);
  723. return AVERROR_INVALIDDATA;
  724. }
  725. }
  726. switch (syntax->type) {
  727. case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
  728. case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
  729. case EBML_STR:
  730. case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
  731. case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
  732. case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
  733. return res;
  734. if (id == MATROSKA_ID_SEGMENT)
  735. matroska->segment_start = avio_tell(matroska->ctx->pb);
  736. return ebml_parse_nest(matroska, syntax->def.n, data);
  737. case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
  738. case EBML_STOP: return 1;
  739. default: return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
  740. }
  741. if (res == AVERROR_INVALIDDATA)
  742. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  743. else if (res == AVERROR(EIO))
  744. av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  745. return res;
  746. }
  747. static void ebml_free(EbmlSyntax *syntax, void *data)
  748. {
  749. int i, j;
  750. for (i=0; syntax[i].id; i++) {
  751. void *data_off = (char *)data + syntax[i].data_offset;
  752. switch (syntax[i].type) {
  753. case EBML_STR:
  754. case EBML_UTF8: av_freep(data_off); break;
  755. case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
  756. case EBML_NEST:
  757. if (syntax[i].list_elem_size) {
  758. EbmlList *list = data_off;
  759. char *ptr = list->elem;
  760. for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
  761. ebml_free(syntax[i].def.n, ptr);
  762. av_free(list->elem);
  763. } else
  764. ebml_free(syntax[i].def.n, data_off);
  765. default: break;
  766. }
  767. }
  768. }
  769. /*
  770. * Autodetecting...
  771. */
  772. static int matroska_probe(AVProbeData *p)
  773. {
  774. uint64_t total = 0;
  775. int len_mask = 0x80, size = 1, n = 1, i;
  776. /* EBML header? */
  777. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  778. return 0;
  779. /* length of header */
  780. total = p->buf[4];
  781. while (size <= 8 && !(total & len_mask)) {
  782. size++;
  783. len_mask >>= 1;
  784. }
  785. if (size > 8)
  786. return 0;
  787. total &= (len_mask - 1);
  788. while (n < size)
  789. total = (total << 8) | p->buf[4 + n++];
  790. /* Does the probe data contain the whole header? */
  791. if (p->buf_size < 4 + size + total)
  792. return 0;
  793. /* The header should contain a known document type. For now,
  794. * we don't parse the whole header but simply check for the
  795. * availability of that array of characters inside the header.
  796. * Not fully fool-proof, but good enough. */
  797. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
  798. int probelen = strlen(matroska_doctypes[i]);
  799. if (total < probelen)
  800. continue;
  801. for (n = 4+size; n <= 4+size+total-probelen; n++)
  802. if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
  803. return AVPROBE_SCORE_MAX;
  804. }
  805. // probably valid EBML header but no recognized doctype
  806. return AVPROBE_SCORE_MAX/2;
  807. }
  808. static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
  809. int num)
  810. {
  811. MatroskaTrack *tracks = matroska->tracks.elem;
  812. int i;
  813. for (i=0; i < matroska->tracks.nb_elem; i++)
  814. if (tracks[i].num == num)
  815. return &tracks[i];
  816. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
  817. return NULL;
  818. }
  819. static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
  820. MatroskaTrack *track)
  821. {
  822. MatroskaTrackEncoding *encodings = track->encodings.elem;
  823. uint8_t* data = *buf;
  824. int isize = *buf_size;
  825. uint8_t* pkt_data = NULL;
  826. uint8_t av_unused *newpktdata;
  827. int pkt_size = isize;
  828. int result = 0;
  829. int olen;
  830. if (pkt_size >= 10000000)
  831. return -1;
  832. switch (encodings[0].compression.algo) {
  833. case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
  834. return encodings[0].compression.settings.size;
  835. case MATROSKA_TRACK_ENCODING_COMP_LZO:
  836. do {
  837. olen = pkt_size *= 3;
  838. pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
  839. result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
  840. } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
  841. if (result)
  842. goto failed;
  843. pkt_size -= olen;
  844. break;
  845. #if CONFIG_ZLIB
  846. case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
  847. z_stream zstream = {0};
  848. if (inflateInit(&zstream) != Z_OK)
  849. return -1;
  850. zstream.next_in = data;
  851. zstream.avail_in = isize;
  852. do {
  853. pkt_size *= 3;
  854. newpktdata = av_realloc(pkt_data, pkt_size);
  855. if (!newpktdata) {
  856. inflateEnd(&zstream);
  857. goto failed;
  858. }
  859. pkt_data = newpktdata;
  860. zstream.avail_out = pkt_size - zstream.total_out;
  861. zstream.next_out = pkt_data + zstream.total_out;
  862. result = inflate(&zstream, Z_NO_FLUSH);
  863. } while (result==Z_OK && pkt_size<10000000);
  864. pkt_size = zstream.total_out;
  865. inflateEnd(&zstream);
  866. if (result != Z_STREAM_END)
  867. goto failed;
  868. break;
  869. }
  870. #endif
  871. #if CONFIG_BZLIB
  872. case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
  873. bz_stream bzstream = {0};
  874. if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
  875. return -1;
  876. bzstream.next_in = data;
  877. bzstream.avail_in = isize;
  878. do {
  879. pkt_size *= 3;
  880. newpktdata = av_realloc(pkt_data, pkt_size);
  881. if (!newpktdata) {
  882. BZ2_bzDecompressEnd(&bzstream);
  883. goto failed;
  884. }
  885. pkt_data = newpktdata;
  886. bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
  887. bzstream.next_out = pkt_data + bzstream.total_out_lo32;
  888. result = BZ2_bzDecompress(&bzstream);
  889. } while (result==BZ_OK && pkt_size<10000000);
  890. pkt_size = bzstream.total_out_lo32;
  891. BZ2_bzDecompressEnd(&bzstream);
  892. if (result != BZ_STREAM_END)
  893. goto failed;
  894. break;
  895. }
  896. #endif
  897. default:
  898. return -1;
  899. }
  900. *buf = pkt_data;
  901. *buf_size = pkt_size;
  902. return 0;
  903. failed:
  904. av_free(pkt_data);
  905. return -1;
  906. }
  907. static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
  908. AVPacket *pkt, uint64_t display_duration)
  909. {
  910. char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
  911. for (; *ptr!=',' && ptr<end-1; ptr++);
  912. if (*ptr == ',')
  913. layer = ++ptr;
  914. for (; *ptr!=',' && ptr<end-1; ptr++);
  915. if (*ptr == ',') {
  916. int64_t end_pts = pkt->pts + display_duration;
  917. int sc = matroska->time_scale * pkt->pts / 10000000;
  918. int ec = matroska->time_scale * end_pts / 10000000;
  919. int sh, sm, ss, eh, em, es, len;
  920. sh = sc/360000; sc -= 360000*sh;
  921. sm = sc/ 6000; sc -= 6000*sm;
  922. ss = sc/ 100; sc -= 100*ss;
  923. eh = ec/360000; ec -= 360000*eh;
  924. em = ec/ 6000; ec -= 6000*em;
  925. es = ec/ 100; ec -= 100*es;
  926. *ptr++ = '\0';
  927. len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
  928. if (!(line = av_malloc(len)))
  929. return;
  930. snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
  931. layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
  932. av_free(pkt->data);
  933. pkt->data = line;
  934. pkt->size = strlen(line);
  935. }
  936. }
  937. static int matroska_merge_packets(AVPacket *out, AVPacket *in)
  938. {
  939. void *newdata = av_realloc(out->data, out->size+in->size);
  940. if (!newdata)
  941. return AVERROR(ENOMEM);
  942. out->data = newdata;
  943. memcpy(out->data+out->size, in->data, in->size);
  944. out->size += in->size;
  945. av_destruct_packet(in);
  946. av_free(in);
  947. return 0;
  948. }
  949. static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
  950. AVDictionary **metadata, char *prefix)
  951. {
  952. MatroskaTag *tags = list->elem;
  953. char key[1024];
  954. int i;
  955. for (i=0; i < list->nb_elem; i++) {
  956. const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
  957. if (!tags[i].name) {
  958. av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
  959. continue;
  960. }
  961. if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  962. else av_strlcpy(key, tags[i].name, sizeof(key));
  963. if (tags[i].def || !lang) {
  964. av_dict_set(metadata, key, tags[i].string, 0);
  965. if (tags[i].sub.nb_elem)
  966. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  967. }
  968. if (lang) {
  969. av_strlcat(key, "-", sizeof(key));
  970. av_strlcat(key, lang, sizeof(key));
  971. av_dict_set(metadata, key, tags[i].string, 0);
  972. if (tags[i].sub.nb_elem)
  973. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  974. }
  975. }
  976. ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
  977. }
  978. static void matroska_convert_tags(AVFormatContext *s)
  979. {
  980. MatroskaDemuxContext *matroska = s->priv_data;
  981. MatroskaTags *tags = matroska->tags.elem;
  982. int i, j;
  983. for (i=0; i < matroska->tags.nb_elem; i++) {
  984. if (tags[i].target.attachuid) {
  985. MatroskaAttachement *attachment = matroska->attachments.elem;
  986. for (j=0; j<matroska->attachments.nb_elem; j++)
  987. if (attachment[j].uid == tags[i].target.attachuid
  988. && attachment[j].stream)
  989. matroska_convert_tag(s, &tags[i].tag,
  990. &attachment[j].stream->metadata, NULL);
  991. } else if (tags[i].target.chapteruid) {
  992. MatroskaChapter *chapter = matroska->chapters.elem;
  993. for (j=0; j<matroska->chapters.nb_elem; j++)
  994. if (chapter[j].uid == tags[i].target.chapteruid
  995. && chapter[j].chapter)
  996. matroska_convert_tag(s, &tags[i].tag,
  997. &chapter[j].chapter->metadata, NULL);
  998. } else if (tags[i].target.trackuid) {
  999. MatroskaTrack *track = matroska->tracks.elem;
  1000. for (j=0; j<matroska->tracks.nb_elem; j++)
  1001. if (track[j].uid == tags[i].target.trackuid && track[j].stream)
  1002. matroska_convert_tag(s, &tags[i].tag,
  1003. &track[j].stream->metadata, NULL);
  1004. } else {
  1005. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  1006. tags[i].target.type);
  1007. }
  1008. }
  1009. }
  1010. static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
  1011. {
  1012. EbmlList *seekhead_list = &matroska->seekhead;
  1013. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1014. uint32_t level_up = matroska->level_up;
  1015. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1016. uint32_t saved_id = matroska->current_id;
  1017. MatroskaLevel level;
  1018. int64_t offset;
  1019. int ret = 0;
  1020. if (idx >= seekhead_list->nb_elem
  1021. || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
  1022. || seekhead[idx].id == MATROSKA_ID_CLUSTER)
  1023. return 0;
  1024. /* seek */
  1025. offset = seekhead[idx].pos + matroska->segment_start;
  1026. if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
  1027. /* We don't want to lose our seekhead level, so we add
  1028. * a dummy. This is a crude hack. */
  1029. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1030. av_log(matroska->ctx, AV_LOG_INFO,
  1031. "Max EBML element depth (%d) reached, "
  1032. "cannot parse further.\n", EBML_MAX_DEPTH);
  1033. ret = AVERROR_INVALIDDATA;
  1034. } else {
  1035. level.start = 0;
  1036. level.length = (uint64_t)-1;
  1037. matroska->levels[matroska->num_levels] = level;
  1038. matroska->num_levels++;
  1039. matroska->current_id = 0;
  1040. ret = ebml_parse(matroska, matroska_segment, matroska);
  1041. /* remove dummy level */
  1042. while (matroska->num_levels) {
  1043. uint64_t length = matroska->levels[--matroska->num_levels].length;
  1044. if (length == (uint64_t)-1)
  1045. break;
  1046. }
  1047. }
  1048. }
  1049. /* seek back */
  1050. avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
  1051. matroska->level_up = level_up;
  1052. matroska->current_id = saved_id;
  1053. return ret;
  1054. }
  1055. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  1056. {
  1057. EbmlList *seekhead_list = &matroska->seekhead;
  1058. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1059. int i;
  1060. // we should not do any seeking in the streaming case
  1061. if (!matroska->ctx->pb->seekable ||
  1062. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  1063. return;
  1064. for (i = 0; i < seekhead_list->nb_elem; i++) {
  1065. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1066. if (seekhead[i].pos <= before_pos)
  1067. continue;
  1068. // defer cues parsing until we actually need cue data.
  1069. if (seekhead[i].id == MATROSKA_ID_CUES) {
  1070. matroska->cues_parsing_deferred = 1;
  1071. continue;
  1072. }
  1073. if (matroska_parse_seekhead_entry(matroska, i) < 0)
  1074. break;
  1075. }
  1076. }
  1077. static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
  1078. EbmlList *seekhead_list = &matroska->seekhead;
  1079. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1080. EbmlList *index_list;
  1081. MatroskaIndex *index;
  1082. int index_scale = 1;
  1083. int i, j;
  1084. for (i = 0; i < seekhead_list->nb_elem; i++)
  1085. if (seekhead[i].id == MATROSKA_ID_CUES)
  1086. break;
  1087. assert(i <= seekhead_list->nb_elem);
  1088. matroska_parse_seekhead_entry(matroska, i);
  1089. index_list = &matroska->index;
  1090. index = index_list->elem;
  1091. if (index_list->nb_elem
  1092. && index[0].time > 1E14/matroska->time_scale) {
  1093. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1094. index_scale = matroska->time_scale;
  1095. }
  1096. for (i = 0; i < index_list->nb_elem; i++) {
  1097. EbmlList *pos_list = &index[i].pos;
  1098. MatroskaIndexPos *pos = pos_list->elem;
  1099. for (j = 0; j < pos_list->nb_elem; j++) {
  1100. MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
  1101. if (track && track->stream)
  1102. av_add_index_entry(track->stream,
  1103. pos[j].pos + matroska->segment_start,
  1104. index[i].time/index_scale, 0, 0,
  1105. AVINDEX_KEYFRAME);
  1106. }
  1107. }
  1108. }
  1109. static int matroska_aac_profile(char *codec_id)
  1110. {
  1111. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  1112. int profile;
  1113. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  1114. if (strstr(codec_id, aac_profiles[profile]))
  1115. break;
  1116. return profile + 1;
  1117. }
  1118. static int matroska_aac_sri(int samplerate)
  1119. {
  1120. int sri;
  1121. for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
  1122. if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
  1123. break;
  1124. return sri;
  1125. }
  1126. static int matroska_read_header(AVFormatContext *s)
  1127. {
  1128. MatroskaDemuxContext *matroska = s->priv_data;
  1129. EbmlList *attachements_list = &matroska->attachments;
  1130. MatroskaAttachement *attachements;
  1131. EbmlList *chapters_list = &matroska->chapters;
  1132. MatroskaChapter *chapters;
  1133. MatroskaTrack *tracks;
  1134. uint64_t max_start = 0;
  1135. Ebml ebml = { 0 };
  1136. AVStream *st;
  1137. int i, j, res;
  1138. matroska->ctx = s;
  1139. /* First read the EBML header. */
  1140. if (ebml_parse(matroska, ebml_syntax, &ebml)
  1141. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  1142. || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
  1143. av_log(matroska->ctx, AV_LOG_ERROR,
  1144. "EBML header using unsupported features\n"
  1145. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1146. ebml.version, ebml.doctype, ebml.doctype_version);
  1147. ebml_free(ebml_syntax, &ebml);
  1148. return AVERROR_PATCHWELCOME;
  1149. }
  1150. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1151. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1152. break;
  1153. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1154. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1155. }
  1156. ebml_free(ebml_syntax, &ebml);
  1157. /* The next thing is a segment. */
  1158. if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
  1159. return res;
  1160. matroska_execute_seekhead(matroska);
  1161. if (!matroska->time_scale)
  1162. matroska->time_scale = 1000000;
  1163. if (matroska->duration)
  1164. matroska->ctx->duration = matroska->duration * matroska->time_scale
  1165. * 1000 / AV_TIME_BASE;
  1166. av_dict_set(&s->metadata, "title", matroska->title, 0);
  1167. tracks = matroska->tracks.elem;
  1168. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1169. MatroskaTrack *track = &tracks[i];
  1170. enum CodecID codec_id = CODEC_ID_NONE;
  1171. EbmlList *encodings_list = &tracks->encodings;
  1172. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1173. uint8_t *extradata = NULL;
  1174. int extradata_size = 0;
  1175. int extradata_offset = 0;
  1176. AVIOContext b;
  1177. /* Apply some sanity checks. */
  1178. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1179. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1180. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1181. av_log(matroska->ctx, AV_LOG_INFO,
  1182. "Unknown or unsupported track type %"PRIu64"\n",
  1183. track->type);
  1184. continue;
  1185. }
  1186. if (track->codec_id == NULL)
  1187. continue;
  1188. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1189. if (!track->default_duration)
  1190. track->default_duration = 1000000000/track->video.frame_rate;
  1191. if (!track->video.display_width)
  1192. track->video.display_width = track->video.pixel_width;
  1193. if (!track->video.display_height)
  1194. track->video.display_height = track->video.pixel_height;
  1195. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1196. if (!track->audio.out_samplerate)
  1197. track->audio.out_samplerate = track->audio.samplerate;
  1198. }
  1199. if (encodings_list->nb_elem > 1) {
  1200. av_log(matroska->ctx, AV_LOG_ERROR,
  1201. "Multiple combined encodings not supported");
  1202. } else if (encodings_list->nb_elem == 1) {
  1203. if (encodings[0].type ||
  1204. (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
  1205. #if CONFIG_ZLIB
  1206. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1207. #endif
  1208. #if CONFIG_BZLIB
  1209. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1210. #endif
  1211. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
  1212. encodings[0].scope = 0;
  1213. av_log(matroska->ctx, AV_LOG_ERROR,
  1214. "Unsupported encoding type");
  1215. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1216. uint8_t *codec_priv = track->codec_priv.data;
  1217. int offset = matroska_decode_buffer(&track->codec_priv.data,
  1218. &track->codec_priv.size,
  1219. track);
  1220. if (offset < 0) {
  1221. track->codec_priv.data = NULL;
  1222. track->codec_priv.size = 0;
  1223. av_log(matroska->ctx, AV_LOG_ERROR,
  1224. "Failed to decode codec private data\n");
  1225. } else if (offset > 0) {
  1226. track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
  1227. memcpy(track->codec_priv.data,
  1228. encodings[0].compression.settings.data, offset);
  1229. memcpy(track->codec_priv.data+offset, codec_priv,
  1230. track->codec_priv.size);
  1231. track->codec_priv.size += offset;
  1232. }
  1233. if (codec_priv != track->codec_priv.data)
  1234. av_free(codec_priv);
  1235. }
  1236. }
  1237. for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
  1238. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1239. strlen(ff_mkv_codec_tags[j].str))){
  1240. codec_id= ff_mkv_codec_tags[j].id;
  1241. break;
  1242. }
  1243. }
  1244. st = track->stream = avformat_new_stream(s, NULL);
  1245. if (st == NULL)
  1246. return AVERROR(ENOMEM);
  1247. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1248. && track->codec_priv.size >= 40
  1249. && track->codec_priv.data != NULL) {
  1250. track->ms_compat = 1;
  1251. track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
  1252. codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
  1253. extradata_offset = 40;
  1254. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1255. && track->codec_priv.size >= 14
  1256. && track->codec_priv.data != NULL) {
  1257. int ret;
  1258. ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
  1259. AVIO_FLAG_READ, NULL, NULL, NULL, NULL);
  1260. ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1261. if (ret < 0)
  1262. return ret;
  1263. codec_id = st->codec->codec_id;
  1264. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1265. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1266. && (track->codec_priv.size >= 86)
  1267. && (track->codec_priv.data != NULL)) {
  1268. track->video.fourcc = AV_RL32(track->codec_priv.data);
  1269. codec_id=ff_codec_get_id(ff_codec_movvideo_tags, track->video.fourcc);
  1270. } else if (codec_id == CODEC_ID_PCM_S16BE) {
  1271. switch (track->audio.bitdepth) {
  1272. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1273. case 24: codec_id = CODEC_ID_PCM_S24BE; break;
  1274. case 32: codec_id = CODEC_ID_PCM_S32BE; break;
  1275. }
  1276. } else if (codec_id == CODEC_ID_PCM_S16LE) {
  1277. switch (track->audio.bitdepth) {
  1278. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1279. case 24: codec_id = CODEC_ID_PCM_S24LE; break;
  1280. case 32: codec_id = CODEC_ID_PCM_S32LE; break;
  1281. }
  1282. } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1283. codec_id = CODEC_ID_PCM_F64LE;
  1284. } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
  1285. int profile = matroska_aac_profile(track->codec_id);
  1286. int sri = matroska_aac_sri(track->audio.samplerate);
  1287. extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
  1288. if (extradata == NULL)
  1289. return AVERROR(ENOMEM);
  1290. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1291. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1292. if (strstr(track->codec_id, "SBR")) {
  1293. sri = matroska_aac_sri(track->audio.out_samplerate);
  1294. extradata[2] = 0x56;
  1295. extradata[3] = 0xE5;
  1296. extradata[4] = 0x80 | (sri<<3);
  1297. extradata_size = 5;
  1298. } else
  1299. extradata_size = 2;
  1300. } else if (codec_id == CODEC_ID_TTA) {
  1301. extradata_size = 30;
  1302. extradata = av_mallocz(extradata_size);
  1303. if (extradata == NULL)
  1304. return AVERROR(ENOMEM);
  1305. ffio_init_context(&b, extradata, extradata_size, 1,
  1306. NULL, NULL, NULL, NULL);
  1307. avio_write(&b, "TTA1", 4);
  1308. avio_wl16(&b, 1);
  1309. avio_wl16(&b, track->audio.channels);
  1310. avio_wl16(&b, track->audio.bitdepth);
  1311. avio_wl32(&b, track->audio.out_samplerate);
  1312. avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
  1313. } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
  1314. codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
  1315. extradata_offset = 26;
  1316. } else if (codec_id == CODEC_ID_RA_144) {
  1317. track->audio.out_samplerate = 8000;
  1318. track->audio.channels = 1;
  1319. } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
  1320. codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
  1321. int flavor;
  1322. ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
  1323. 0, NULL, NULL, NULL, NULL);
  1324. avio_skip(&b, 22);
  1325. flavor = avio_rb16(&b);
  1326. track->audio.coded_framesize = avio_rb32(&b);
  1327. avio_skip(&b, 12);
  1328. track->audio.sub_packet_h = avio_rb16(&b);
  1329. track->audio.frame_size = avio_rb16(&b);
  1330. track->audio.sub_packet_size = avio_rb16(&b);
  1331. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1332. if (codec_id == CODEC_ID_RA_288) {
  1333. st->codec->block_align = track->audio.coded_framesize;
  1334. track->codec_priv.size = 0;
  1335. } else {
  1336. if (codec_id == CODEC_ID_SIPR && flavor < 4) {
  1337. const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1338. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1339. st->codec->bit_rate = sipr_bit_rate[flavor];
  1340. }
  1341. st->codec->block_align = track->audio.sub_packet_size;
  1342. extradata_offset = 78;
  1343. }
  1344. }
  1345. track->codec_priv.size -= extradata_offset;
  1346. if (codec_id == CODEC_ID_NONE)
  1347. av_log(matroska->ctx, AV_LOG_INFO,
  1348. "Unknown/unsupported CodecID %s.\n", track->codec_id);
  1349. if (track->time_scale < 0.01)
  1350. track->time_scale = 1.0;
  1351. avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1352. st->codec->codec_id = codec_id;
  1353. st->start_time = 0;
  1354. if (strcmp(track->language, "und"))
  1355. av_dict_set(&st->metadata, "language", track->language, 0);
  1356. av_dict_set(&st->metadata, "title", track->name, 0);
  1357. if (track->flag_default)
  1358. st->disposition |= AV_DISPOSITION_DEFAULT;
  1359. if (track->flag_forced)
  1360. st->disposition |= AV_DISPOSITION_FORCED;
  1361. if (!st->codec->extradata) {
  1362. if(extradata){
  1363. st->codec->extradata = extradata;
  1364. st->codec->extradata_size = extradata_size;
  1365. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1366. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1367. FF_INPUT_BUFFER_PADDING_SIZE);
  1368. if(st->codec->extradata == NULL)
  1369. return AVERROR(ENOMEM);
  1370. st->codec->extradata_size = track->codec_priv.size;
  1371. memcpy(st->codec->extradata,
  1372. track->codec_priv.data + extradata_offset,
  1373. track->codec_priv.size);
  1374. }
  1375. }
  1376. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1377. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1378. st->codec->codec_tag = track->video.fourcc;
  1379. st->codec->width = track->video.pixel_width;
  1380. st->codec->height = track->video.pixel_height;
  1381. av_reduce(&st->sample_aspect_ratio.num,
  1382. &st->sample_aspect_ratio.den,
  1383. st->codec->height * track->video.display_width,
  1384. st->codec-> width * track->video.display_height,
  1385. 255);
  1386. if (st->codec->codec_id != CODEC_ID_H264)
  1387. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1388. if (track->default_duration)
  1389. st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
  1390. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1391. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1392. st->codec->sample_rate = track->audio.out_samplerate;
  1393. st->codec->channels = track->audio.channels;
  1394. if (st->codec->codec_id != CODEC_ID_AAC)
  1395. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1396. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1397. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1398. }
  1399. }
  1400. attachements = attachements_list->elem;
  1401. for (j=0; j<attachements_list->nb_elem; j++) {
  1402. if (!(attachements[j].filename && attachements[j].mime &&
  1403. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1404. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1405. } else {
  1406. AVStream *st = avformat_new_stream(s, NULL);
  1407. if (st == NULL)
  1408. break;
  1409. av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
  1410. av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
  1411. st->codec->codec_id = CODEC_ID_NONE;
  1412. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1413. st->codec->extradata = av_malloc(attachements[j].bin.size);
  1414. if(st->codec->extradata == NULL)
  1415. break;
  1416. st->codec->extradata_size = attachements[j].bin.size;
  1417. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1418. for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
  1419. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1420. strlen(ff_mkv_mime_tags[i].str))) {
  1421. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1422. break;
  1423. }
  1424. }
  1425. attachements[j].stream = st;
  1426. }
  1427. }
  1428. chapters = chapters_list->elem;
  1429. for (i=0; i<chapters_list->nb_elem; i++)
  1430. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1431. && (max_start==0 || chapters[i].start > max_start)) {
  1432. chapters[i].chapter =
  1433. avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1434. chapters[i].start, chapters[i].end,
  1435. chapters[i].title);
  1436. av_dict_set(&chapters[i].chapter->metadata,
  1437. "title", chapters[i].title, 0);
  1438. max_start = chapters[i].start;
  1439. }
  1440. matroska_convert_tags(s);
  1441. return 0;
  1442. }
  1443. /*
  1444. * Put one packet in an application-supplied AVPacket struct.
  1445. * Returns 0 on success or -1 on failure.
  1446. */
  1447. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1448. AVPacket *pkt)
  1449. {
  1450. if (matroska->num_packets > 0) {
  1451. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1452. av_free(matroska->packets[0]);
  1453. if (matroska->num_packets > 1) {
  1454. void *newpackets;
  1455. memmove(&matroska->packets[0], &matroska->packets[1],
  1456. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1457. newpackets = av_realloc(matroska->packets,
  1458. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1459. if (newpackets)
  1460. matroska->packets = newpackets;
  1461. } else {
  1462. av_freep(&matroska->packets);
  1463. }
  1464. matroska->num_packets--;
  1465. return 0;
  1466. }
  1467. return -1;
  1468. }
  1469. /*
  1470. * Free all packets in our internal queue.
  1471. */
  1472. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1473. {
  1474. if (matroska->packets) {
  1475. int n;
  1476. for (n = 0; n < matroska->num_packets; n++) {
  1477. av_free_packet(matroska->packets[n]);
  1478. av_free(matroska->packets[n]);
  1479. }
  1480. av_freep(&matroska->packets);
  1481. matroska->num_packets = 0;
  1482. }
  1483. }
  1484. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1485. int size, int64_t pos, uint64_t cluster_time,
  1486. uint64_t duration, int is_keyframe,
  1487. int64_t cluster_pos)
  1488. {
  1489. uint64_t timecode = AV_NOPTS_VALUE;
  1490. MatroskaTrack *track;
  1491. int res = 0;
  1492. AVStream *st;
  1493. AVPacket *pkt;
  1494. int16_t block_time;
  1495. uint32_t *lace_size = NULL;
  1496. int n, flags, laces = 0;
  1497. uint64_t num;
  1498. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  1499. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1500. return res;
  1501. }
  1502. data += n;
  1503. size -= n;
  1504. track = matroska_find_track_by_num(matroska, num);
  1505. if (!track || !track->stream) {
  1506. av_log(matroska->ctx, AV_LOG_INFO,
  1507. "Invalid stream %"PRIu64" or size %u\n", num, size);
  1508. return AVERROR_INVALIDDATA;
  1509. } else if (size <= 3)
  1510. return 0;
  1511. st = track->stream;
  1512. if (st->discard >= AVDISCARD_ALL)
  1513. return res;
  1514. if (duration == AV_NOPTS_VALUE)
  1515. duration = track->default_duration / matroska->time_scale;
  1516. block_time = AV_RB16(data);
  1517. data += 2;
  1518. flags = *data++;
  1519. size -= 3;
  1520. if (is_keyframe == -1)
  1521. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  1522. if (cluster_time != (uint64_t)-1
  1523. && (block_time >= 0 || cluster_time >= -block_time)) {
  1524. timecode = cluster_time + block_time;
  1525. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  1526. && timecode < track->end_timecode)
  1527. is_keyframe = 0; /* overlapping subtitles are not key frame */
  1528. if (is_keyframe)
  1529. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  1530. track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
  1531. }
  1532. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1533. if (!is_keyframe || timecode < matroska->skip_to_timecode)
  1534. return res;
  1535. matroska->skip_to_keyframe = 0;
  1536. }
  1537. switch ((flags & 0x06) >> 1) {
  1538. case 0x0: /* no lacing */
  1539. laces = 1;
  1540. lace_size = av_mallocz(sizeof(int));
  1541. lace_size[0] = size;
  1542. break;
  1543. case 0x1: /* Xiph lacing */
  1544. case 0x2: /* fixed-size lacing */
  1545. case 0x3: /* EBML lacing */
  1546. assert(size>0); // size <=3 is checked before size-=3 above
  1547. laces = (*data) + 1;
  1548. data += 1;
  1549. size -= 1;
  1550. lace_size = av_mallocz(laces * sizeof(int));
  1551. switch ((flags & 0x06) >> 1) {
  1552. case 0x1: /* Xiph lacing */ {
  1553. uint8_t temp;
  1554. uint32_t total = 0;
  1555. for (n = 0; res == 0 && n < laces - 1; n++) {
  1556. while (1) {
  1557. if (size == 0) {
  1558. res = -1;
  1559. break;
  1560. }
  1561. temp = *data;
  1562. lace_size[n] += temp;
  1563. data += 1;
  1564. size -= 1;
  1565. if (temp != 0xff)
  1566. break;
  1567. }
  1568. total += lace_size[n];
  1569. }
  1570. lace_size[n] = size - total;
  1571. break;
  1572. }
  1573. case 0x2: /* fixed-size lacing */
  1574. for (n = 0; n < laces; n++)
  1575. lace_size[n] = size / laces;
  1576. break;
  1577. case 0x3: /* EBML lacing */ {
  1578. uint32_t total;
  1579. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1580. if (n < 0) {
  1581. av_log(matroska->ctx, AV_LOG_INFO,
  1582. "EBML block data error\n");
  1583. break;
  1584. }
  1585. data += n;
  1586. size -= n;
  1587. total = lace_size[0] = num;
  1588. for (n = 1; res == 0 && n < laces - 1; n++) {
  1589. int64_t snum;
  1590. int r;
  1591. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1592. if (r < 0) {
  1593. av_log(matroska->ctx, AV_LOG_INFO,
  1594. "EBML block data error\n");
  1595. break;
  1596. }
  1597. data += r;
  1598. size -= r;
  1599. lace_size[n] = lace_size[n - 1] + snum;
  1600. total += lace_size[n];
  1601. }
  1602. lace_size[laces - 1] = size - total;
  1603. break;
  1604. }
  1605. }
  1606. break;
  1607. }
  1608. if (res == 0) {
  1609. for (n = 0; n < laces; n++) {
  1610. if ((st->codec->codec_id == CODEC_ID_RA_288 ||
  1611. st->codec->codec_id == CODEC_ID_COOK ||
  1612. st->codec->codec_id == CODEC_ID_SIPR ||
  1613. st->codec->codec_id == CODEC_ID_ATRAC3) &&
  1614. st->codec->block_align && track->audio.sub_packet_size) {
  1615. int a = st->codec->block_align;
  1616. int sps = track->audio.sub_packet_size;
  1617. int cfs = track->audio.coded_framesize;
  1618. int h = track->audio.sub_packet_h;
  1619. int y = track->audio.sub_packet_cnt;
  1620. int w = track->audio.frame_size;
  1621. int x;
  1622. if (!track->audio.pkt_cnt) {
  1623. if (track->audio.sub_packet_cnt == 0)
  1624. track->audio.buf_timecode = timecode;
  1625. if (st->codec->codec_id == CODEC_ID_RA_288) {
  1626. if (size < cfs * h / 2) {
  1627. av_log(matroska->ctx, AV_LOG_ERROR,
  1628. "Corrupt int4 RM-style audio packet size\n");
  1629. res = AVERROR_INVALIDDATA;
  1630. goto end;
  1631. }
  1632. for (x=0; x<h/2; x++)
  1633. memcpy(track->audio.buf+x*2*w+y*cfs,
  1634. data+x*cfs, cfs);
  1635. } else if (st->codec->codec_id == CODEC_ID_SIPR) {
  1636. if (size < w) {
  1637. av_log(matroska->ctx, AV_LOG_ERROR,
  1638. "Corrupt sipr RM-style audio packet size\n");
  1639. res = AVERROR_INVALIDDATA;
  1640. goto end;
  1641. }
  1642. memcpy(track->audio.buf + y*w, data, w);
  1643. } else {
  1644. if (size < sps * w / sps) {
  1645. av_log(matroska->ctx, AV_LOG_ERROR,
  1646. "Corrupt generic RM-style audio packet size\n");
  1647. res = AVERROR_INVALIDDATA;
  1648. goto end;
  1649. }
  1650. for (x=0; x<w/sps; x++)
  1651. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1652. }
  1653. if (++track->audio.sub_packet_cnt >= h) {
  1654. if (st->codec->codec_id == CODEC_ID_SIPR)
  1655. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1656. track->audio.sub_packet_cnt = 0;
  1657. track->audio.pkt_cnt = h*w / a;
  1658. }
  1659. }
  1660. while (track->audio.pkt_cnt) {
  1661. pkt = av_mallocz(sizeof(AVPacket));
  1662. av_new_packet(pkt, a);
  1663. memcpy(pkt->data, track->audio.buf
  1664. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1665. pkt->pts = track->audio.buf_timecode;
  1666. track->audio.buf_timecode = AV_NOPTS_VALUE;
  1667. pkt->pos = pos;
  1668. pkt->stream_index = st->index;
  1669. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1670. }
  1671. } else {
  1672. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1673. int offset = 0, pkt_size = lace_size[n];
  1674. uint8_t *pkt_data = data;
  1675. if (pkt_size > size) {
  1676. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
  1677. break;
  1678. }
  1679. if (encodings && encodings->scope & 1) {
  1680. offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
  1681. if (offset < 0)
  1682. continue;
  1683. }
  1684. pkt = av_mallocz(sizeof(AVPacket));
  1685. /* XXX: prevent data copy... */
  1686. if (av_new_packet(pkt, pkt_size+offset) < 0) {
  1687. av_free(pkt);
  1688. res = AVERROR(ENOMEM);
  1689. break;
  1690. }
  1691. if (offset)
  1692. memcpy (pkt->data, encodings->compression.settings.data, offset);
  1693. memcpy (pkt->data+offset, pkt_data, pkt_size);
  1694. if (pkt_data != data)
  1695. av_free(pkt_data);
  1696. if (n == 0)
  1697. pkt->flags = is_keyframe;
  1698. pkt->stream_index = st->index;
  1699. if (track->ms_compat)
  1700. pkt->dts = timecode;
  1701. else
  1702. pkt->pts = timecode;
  1703. pkt->pos = pos;
  1704. if (st->codec->codec_id == CODEC_ID_TEXT)
  1705. pkt->convergence_duration = duration;
  1706. else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
  1707. pkt->duration = duration;
  1708. if (st->codec->codec_id == CODEC_ID_SSA)
  1709. matroska_fix_ass_packet(matroska, pkt, duration);
  1710. if (matroska->prev_pkt &&
  1711. timecode != AV_NOPTS_VALUE &&
  1712. matroska->prev_pkt->pts == timecode &&
  1713. matroska->prev_pkt->stream_index == st->index &&
  1714. st->codec->codec_id == CODEC_ID_SSA)
  1715. matroska_merge_packets(matroska->prev_pkt, pkt);
  1716. else {
  1717. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1718. matroska->prev_pkt = pkt;
  1719. }
  1720. }
  1721. if (timecode != AV_NOPTS_VALUE)
  1722. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  1723. data += lace_size[n];
  1724. size -= lace_size[n];
  1725. }
  1726. }
  1727. end:
  1728. av_free(lace_size);
  1729. return res;
  1730. }
  1731. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  1732. {
  1733. MatroskaCluster cluster = { 0 };
  1734. EbmlList *blocks_list;
  1735. MatroskaBlock *blocks;
  1736. int i, res;
  1737. int64_t pos = avio_tell(matroska->ctx->pb);
  1738. matroska->prev_pkt = NULL;
  1739. if (matroska->current_id)
  1740. pos -= 4; /* sizeof the ID which was already read */
  1741. res = ebml_parse(matroska, matroska_clusters, &cluster);
  1742. blocks_list = &cluster.blocks;
  1743. blocks = blocks_list->elem;
  1744. for (i=0; i<blocks_list->nb_elem && !res; i++)
  1745. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  1746. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  1747. if (!blocks[i].non_simple)
  1748. blocks[i].duration = AV_NOPTS_VALUE;
  1749. res=matroska_parse_block(matroska,
  1750. blocks[i].bin.data, blocks[i].bin.size,
  1751. blocks[i].bin.pos, cluster.timecode,
  1752. blocks[i].duration, is_keyframe,
  1753. pos);
  1754. }
  1755. ebml_free(matroska_cluster, &cluster);
  1756. if (res < 0) matroska->done = 1;
  1757. return res;
  1758. }
  1759. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  1760. {
  1761. MatroskaDemuxContext *matroska = s->priv_data;
  1762. int ret = 0;
  1763. while (!ret && matroska_deliver_packet(matroska, pkt)) {
  1764. if (matroska->done)
  1765. return AVERROR_EOF;
  1766. ret = matroska_parse_cluster(matroska);
  1767. }
  1768. return ret;
  1769. }
  1770. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  1771. int64_t timestamp, int flags)
  1772. {
  1773. MatroskaDemuxContext *matroska = s->priv_data;
  1774. MatroskaTrack *tracks = matroska->tracks.elem;
  1775. AVStream *st = s->streams[stream_index];
  1776. int i, index, index_sub, index_min;
  1777. /* Parse the CUES now since we need the index data to seek. */
  1778. if (matroska->cues_parsing_deferred) {
  1779. matroska_parse_cues(matroska);
  1780. matroska->cues_parsing_deferred = 0;
  1781. }
  1782. if (!st->nb_index_entries)
  1783. return 0;
  1784. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  1785. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1786. avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  1787. matroska->current_id = 0;
  1788. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1789. matroska_clear_queue(matroska);
  1790. if (matroska_parse_cluster(matroska) < 0)
  1791. break;
  1792. }
  1793. }
  1794. matroska_clear_queue(matroska);
  1795. if (index < 0)
  1796. return 0;
  1797. index_min = index;
  1798. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1799. tracks[i].audio.pkt_cnt = 0;
  1800. tracks[i].audio.sub_packet_cnt = 0;
  1801. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  1802. tracks[i].end_timecode = 0;
  1803. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  1804. && !tracks[i].stream->discard != AVDISCARD_ALL) {
  1805. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  1806. if (index_sub >= 0
  1807. && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
  1808. && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  1809. index_min = index_sub;
  1810. }
  1811. }
  1812. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  1813. matroska->current_id = 0;
  1814. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  1815. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  1816. matroska->done = 0;
  1817. ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
  1818. return 0;
  1819. }
  1820. static int matroska_read_close(AVFormatContext *s)
  1821. {
  1822. MatroskaDemuxContext *matroska = s->priv_data;
  1823. MatroskaTrack *tracks = matroska->tracks.elem;
  1824. int n;
  1825. matroska_clear_queue(matroska);
  1826. for (n=0; n < matroska->tracks.nb_elem; n++)
  1827. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  1828. av_free(tracks[n].audio.buf);
  1829. ebml_free(matroska_segment, matroska);
  1830. return 0;
  1831. }
  1832. AVInputFormat ff_matroska_demuxer = {
  1833. .name = "matroska,webm",
  1834. .long_name = NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
  1835. .priv_data_size = sizeof(MatroskaDemuxContext),
  1836. .read_probe = matroska_probe,
  1837. .read_header = matroska_read_header,
  1838. .read_packet = matroska_read_packet,
  1839. .read_close = matroska_read_close,
  1840. .read_seek = matroska_read_seek,
  1841. };