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.

2013 lines
72KB

  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. * by Ronald Bultje <rbultje@ronald.bitfreak.net>
  25. * with a little help from Moritz Bunkus <moritz@bunkus.org>
  26. * totally reworked by Aurelien Jacobs <aurel@gnuage.org>
  27. * 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_readwrite.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 *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_int2flt(avio_rb32(pb));
  548. } else if(size==8){
  549. *num= av_int2dbl(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. av_free(*str);
  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 (!(*str = av_malloc(size + 1)))
  564. return AVERROR(ENOMEM);
  565. if (avio_read(pb, (uint8_t *) *str, size) != size) {
  566. av_freep(str);
  567. return AVERROR(EIO);
  568. }
  569. (*str)[size] = '\0';
  570. return 0;
  571. }
  572. /*
  573. * Read the next element as binary data.
  574. * 0 is success, < 0 is failure.
  575. */
  576. static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
  577. {
  578. av_free(bin->data);
  579. if (!(bin->data = av_malloc(length)))
  580. return AVERROR(ENOMEM);
  581. bin->size = length;
  582. bin->pos = avio_tell(pb);
  583. if (avio_read(pb, bin->data, length) != length) {
  584. av_freep(&bin->data);
  585. return AVERROR(EIO);
  586. }
  587. return 0;
  588. }
  589. /*
  590. * Read the next element, but only the header. The contents
  591. * are supposed to be sub-elements which can be read separately.
  592. * 0 is success, < 0 is failure.
  593. */
  594. static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
  595. {
  596. AVIOContext *pb = matroska->ctx->pb;
  597. MatroskaLevel *level;
  598. if (matroska->num_levels >= EBML_MAX_DEPTH) {
  599. av_log(matroska->ctx, AV_LOG_ERROR,
  600. "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  601. return AVERROR(ENOSYS);
  602. }
  603. level = &matroska->levels[matroska->num_levels++];
  604. level->start = avio_tell(pb);
  605. level->length = length;
  606. return 0;
  607. }
  608. /*
  609. * Read signed/unsigned "EBML" numbers.
  610. * Return: number of bytes processed, < 0 on error
  611. */
  612. static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
  613. uint8_t *data, uint32_t size, uint64_t *num)
  614. {
  615. AVIOContext pb;
  616. ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
  617. return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
  618. }
  619. /*
  620. * Same as above, but signed.
  621. */
  622. static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
  623. uint8_t *data, uint32_t size, int64_t *num)
  624. {
  625. uint64_t unum;
  626. int res;
  627. /* read as unsigned number first */
  628. if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
  629. return res;
  630. /* make signed (weird way) */
  631. *num = unum - ((1LL << (7*res - 1)) - 1);
  632. return res;
  633. }
  634. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  635. EbmlSyntax *syntax, void *data);
  636. static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  637. uint32_t id, void *data)
  638. {
  639. int i;
  640. for (i=0; syntax[i].id; i++)
  641. if (id == syntax[i].id)
  642. break;
  643. if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
  644. matroska->num_levels > 0 &&
  645. matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
  646. return 0; // we reached the end of an unknown size cluster
  647. if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
  648. av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
  649. return ebml_parse_elem(matroska, &syntax[i], data);
  650. }
  651. static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  652. void *data)
  653. {
  654. if (!matroska->current_id) {
  655. uint64_t id;
  656. int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
  657. if (res < 0)
  658. return res;
  659. matroska->current_id = id | 1 << 7*res;
  660. }
  661. return ebml_parse_id(matroska, syntax, matroska->current_id, data);
  662. }
  663. static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  664. void *data)
  665. {
  666. int i, res = 0;
  667. for (i=0; syntax[i].id; i++)
  668. switch (syntax[i].type) {
  669. case EBML_UINT:
  670. *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
  671. break;
  672. case EBML_FLOAT:
  673. *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
  674. break;
  675. case EBML_STR:
  676. case EBML_UTF8:
  677. *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
  678. break;
  679. }
  680. while (!res && !ebml_level_end(matroska))
  681. res = ebml_parse(matroska, syntax, data);
  682. return res;
  683. }
  684. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  685. EbmlSyntax *syntax, void *data)
  686. {
  687. static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
  688. [EBML_UINT] = 8,
  689. [EBML_FLOAT] = 8,
  690. // max. 16 MB for strings
  691. [EBML_STR] = 0x1000000,
  692. [EBML_UTF8] = 0x1000000,
  693. // max. 256 MB for binary data
  694. [EBML_BIN] = 0x10000000,
  695. // no limits for anything else
  696. };
  697. AVIOContext *pb = matroska->ctx->pb;
  698. uint32_t id = syntax->id;
  699. uint64_t length;
  700. int res;
  701. data = (char *)data + syntax->data_offset;
  702. if (syntax->list_elem_size) {
  703. EbmlList *list = data;
  704. list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
  705. data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
  706. memset(data, 0, syntax->list_elem_size);
  707. list->nb_elem++;
  708. }
  709. if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
  710. matroska->current_id = 0;
  711. if ((res = ebml_read_length(matroska, pb, &length)) < 0)
  712. return res;
  713. if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
  714. av_log(matroska->ctx, AV_LOG_ERROR,
  715. "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
  716. length, max_lengths[syntax->type], syntax->type);
  717. return AVERROR_INVALIDDATA;
  718. }
  719. }
  720. switch (syntax->type) {
  721. case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
  722. case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
  723. case EBML_STR:
  724. case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
  725. case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
  726. case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
  727. return res;
  728. if (id == MATROSKA_ID_SEGMENT)
  729. matroska->segment_start = avio_tell(matroska->ctx->pb);
  730. return ebml_parse_nest(matroska, syntax->def.n, data);
  731. case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
  732. case EBML_STOP: return 1;
  733. default: return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
  734. }
  735. if (res == AVERROR_INVALIDDATA)
  736. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  737. else if (res == AVERROR(EIO))
  738. av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  739. return res;
  740. }
  741. static void ebml_free(EbmlSyntax *syntax, void *data)
  742. {
  743. int i, j;
  744. for (i=0; syntax[i].id; i++) {
  745. void *data_off = (char *)data + syntax[i].data_offset;
  746. switch (syntax[i].type) {
  747. case EBML_STR:
  748. case EBML_UTF8: av_freep(data_off); break;
  749. case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
  750. case EBML_NEST:
  751. if (syntax[i].list_elem_size) {
  752. EbmlList *list = data_off;
  753. char *ptr = list->elem;
  754. for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
  755. ebml_free(syntax[i].def.n, ptr);
  756. av_free(list->elem);
  757. } else
  758. ebml_free(syntax[i].def.n, data_off);
  759. default: break;
  760. }
  761. }
  762. }
  763. /*
  764. * Autodetecting...
  765. */
  766. static int matroska_probe(AVProbeData *p)
  767. {
  768. uint64_t total = 0;
  769. int len_mask = 0x80, size = 1, n = 1, i;
  770. /* EBML header? */
  771. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  772. return 0;
  773. /* length of header */
  774. total = p->buf[4];
  775. while (size <= 8 && !(total & len_mask)) {
  776. size++;
  777. len_mask >>= 1;
  778. }
  779. if (size > 8)
  780. return 0;
  781. total &= (len_mask - 1);
  782. while (n < size)
  783. total = (total << 8) | p->buf[4 + n++];
  784. /* Does the probe data contain the whole header? */
  785. if (p->buf_size < 4 + size + total)
  786. return 0;
  787. /* The header should contain a known document type. For now,
  788. * we don't parse the whole header but simply check for the
  789. * availability of that array of characters inside the header.
  790. * Not fully fool-proof, but good enough. */
  791. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
  792. int probelen = strlen(matroska_doctypes[i]);
  793. if (total < probelen)
  794. continue;
  795. for (n = 4+size; n <= 4+size+total-probelen; n++)
  796. if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
  797. return AVPROBE_SCORE_MAX;
  798. }
  799. // probably valid EBML header but no recognized doctype
  800. return AVPROBE_SCORE_MAX/2;
  801. }
  802. static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
  803. int num)
  804. {
  805. MatroskaTrack *tracks = matroska->tracks.elem;
  806. int i;
  807. for (i=0; i < matroska->tracks.nb_elem; i++)
  808. if (tracks[i].num == num)
  809. return &tracks[i];
  810. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
  811. return NULL;
  812. }
  813. static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
  814. MatroskaTrack *track)
  815. {
  816. MatroskaTrackEncoding *encodings = track->encodings.elem;
  817. uint8_t* data = *buf;
  818. int isize = *buf_size;
  819. uint8_t* pkt_data = NULL;
  820. int pkt_size = isize;
  821. int result = 0;
  822. int olen;
  823. if (pkt_size >= 10000000)
  824. return -1;
  825. switch (encodings[0].compression.algo) {
  826. case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
  827. return encodings[0].compression.settings.size;
  828. case MATROSKA_TRACK_ENCODING_COMP_LZO:
  829. do {
  830. olen = pkt_size *= 3;
  831. pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
  832. result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
  833. } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
  834. if (result)
  835. goto failed;
  836. pkt_size -= olen;
  837. break;
  838. #if CONFIG_ZLIB
  839. case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
  840. z_stream zstream = {0};
  841. if (inflateInit(&zstream) != Z_OK)
  842. return -1;
  843. zstream.next_in = data;
  844. zstream.avail_in = isize;
  845. do {
  846. pkt_size *= 3;
  847. pkt_data = av_realloc(pkt_data, pkt_size);
  848. zstream.avail_out = pkt_size - zstream.total_out;
  849. zstream.next_out = pkt_data + zstream.total_out;
  850. result = inflate(&zstream, Z_NO_FLUSH);
  851. } while (result==Z_OK && pkt_size<10000000);
  852. pkt_size = zstream.total_out;
  853. inflateEnd(&zstream);
  854. if (result != Z_STREAM_END)
  855. goto failed;
  856. break;
  857. }
  858. #endif
  859. #if CONFIG_BZLIB
  860. case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
  861. bz_stream bzstream = {0};
  862. if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
  863. return -1;
  864. bzstream.next_in = data;
  865. bzstream.avail_in = isize;
  866. do {
  867. pkt_size *= 3;
  868. pkt_data = av_realloc(pkt_data, pkt_size);
  869. bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
  870. bzstream.next_out = pkt_data + bzstream.total_out_lo32;
  871. result = BZ2_bzDecompress(&bzstream);
  872. } while (result==BZ_OK && pkt_size<10000000);
  873. pkt_size = bzstream.total_out_lo32;
  874. BZ2_bzDecompressEnd(&bzstream);
  875. if (result != BZ_STREAM_END)
  876. goto failed;
  877. break;
  878. }
  879. #endif
  880. default:
  881. return -1;
  882. }
  883. *buf = pkt_data;
  884. *buf_size = pkt_size;
  885. return 0;
  886. failed:
  887. av_free(pkt_data);
  888. return -1;
  889. }
  890. static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
  891. AVPacket *pkt, uint64_t display_duration)
  892. {
  893. char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
  894. for (; *ptr!=',' && ptr<end-1; ptr++);
  895. if (*ptr == ',')
  896. layer = ++ptr;
  897. for (; *ptr!=',' && ptr<end-1; ptr++);
  898. if (*ptr == ',') {
  899. int64_t end_pts = pkt->pts + display_duration;
  900. int sc = matroska->time_scale * pkt->pts / 10000000;
  901. int ec = matroska->time_scale * end_pts / 10000000;
  902. int sh, sm, ss, eh, em, es, len;
  903. sh = sc/360000; sc -= 360000*sh;
  904. sm = sc/ 6000; sc -= 6000*sm;
  905. ss = sc/ 100; sc -= 100*ss;
  906. eh = ec/360000; ec -= 360000*eh;
  907. em = ec/ 6000; ec -= 6000*em;
  908. es = ec/ 100; ec -= 100*es;
  909. *ptr++ = '\0';
  910. len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
  911. if (!(line = av_malloc(len)))
  912. return;
  913. snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
  914. layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
  915. av_free(pkt->data);
  916. pkt->data = line;
  917. pkt->size = strlen(line);
  918. }
  919. }
  920. static void matroska_merge_packets(AVPacket *out, AVPacket *in)
  921. {
  922. out->data = av_realloc(out->data, out->size+in->size);
  923. memcpy(out->data+out->size, in->data, in->size);
  924. out->size += in->size;
  925. av_destruct_packet(in);
  926. av_free(in);
  927. }
  928. static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
  929. AVDictionary **metadata, char *prefix)
  930. {
  931. MatroskaTag *tags = list->elem;
  932. char key[1024];
  933. int i;
  934. for (i=0; i < list->nb_elem; i++) {
  935. const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
  936. if (!tags[i].name) {
  937. av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
  938. continue;
  939. }
  940. if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  941. else av_strlcpy(key, tags[i].name, sizeof(key));
  942. if (tags[i].def || !lang) {
  943. av_dict_set(metadata, key, tags[i].string, 0);
  944. if (tags[i].sub.nb_elem)
  945. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  946. }
  947. if (lang) {
  948. av_strlcat(key, "-", sizeof(key));
  949. av_strlcat(key, lang, sizeof(key));
  950. av_dict_set(metadata, key, tags[i].string, 0);
  951. if (tags[i].sub.nb_elem)
  952. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  953. }
  954. }
  955. ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
  956. }
  957. static void matroska_convert_tags(AVFormatContext *s)
  958. {
  959. MatroskaDemuxContext *matroska = s->priv_data;
  960. MatroskaTags *tags = matroska->tags.elem;
  961. int i, j;
  962. for (i=0; i < matroska->tags.nb_elem; i++) {
  963. if (tags[i].target.attachuid) {
  964. MatroskaAttachement *attachment = matroska->attachments.elem;
  965. for (j=0; j<matroska->attachments.nb_elem; j++)
  966. if (attachment[j].uid == tags[i].target.attachuid
  967. && attachment[j].stream)
  968. matroska_convert_tag(s, &tags[i].tag,
  969. &attachment[j].stream->metadata, NULL);
  970. } else if (tags[i].target.chapteruid) {
  971. MatroskaChapter *chapter = matroska->chapters.elem;
  972. for (j=0; j<matroska->chapters.nb_elem; j++)
  973. if (chapter[j].uid == tags[i].target.chapteruid
  974. && chapter[j].chapter)
  975. matroska_convert_tag(s, &tags[i].tag,
  976. &chapter[j].chapter->metadata, NULL);
  977. } else if (tags[i].target.trackuid) {
  978. MatroskaTrack *track = matroska->tracks.elem;
  979. for (j=0; j<matroska->tracks.nb_elem; j++)
  980. if (track[j].uid == tags[i].target.trackuid && track[j].stream)
  981. matroska_convert_tag(s, &tags[i].tag,
  982. &track[j].stream->metadata, NULL);
  983. } else {
  984. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  985. tags[i].target.type);
  986. }
  987. }
  988. }
  989. static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
  990. {
  991. EbmlList *seekhead_list = &matroska->seekhead;
  992. MatroskaSeekhead *seekhead = seekhead_list->elem;
  993. uint32_t level_up = matroska->level_up;
  994. int64_t before_pos = avio_tell(matroska->ctx->pb);
  995. uint32_t saved_id = matroska->current_id;
  996. MatroskaLevel level;
  997. int64_t offset;
  998. int ret = 0;
  999. if (idx >= seekhead_list->nb_elem
  1000. || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
  1001. || seekhead[idx].id == MATROSKA_ID_CLUSTER)
  1002. return 0;
  1003. /* seek */
  1004. offset = seekhead[idx].pos + matroska->segment_start;
  1005. if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
  1006. /* We don't want to lose our seekhead level, so we add
  1007. * a dummy. This is a crude hack. */
  1008. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1009. av_log(matroska->ctx, AV_LOG_INFO,
  1010. "Max EBML element depth (%d) reached, "
  1011. "cannot parse further.\n", EBML_MAX_DEPTH);
  1012. ret = AVERROR_INVALIDDATA;
  1013. } else {
  1014. level.start = 0;
  1015. level.length = (uint64_t)-1;
  1016. matroska->levels[matroska->num_levels] = level;
  1017. matroska->num_levels++;
  1018. matroska->current_id = 0;
  1019. ebml_parse(matroska, matroska_segment, matroska);
  1020. /* remove dummy level */
  1021. while (matroska->num_levels) {
  1022. uint64_t length = matroska->levels[--matroska->num_levels].length;
  1023. if (length == (uint64_t)-1)
  1024. break;
  1025. }
  1026. }
  1027. }
  1028. /* seek back */
  1029. avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
  1030. matroska->level_up = level_up;
  1031. matroska->current_id = saved_id;
  1032. return ret;
  1033. }
  1034. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  1035. {
  1036. EbmlList *seekhead_list = &matroska->seekhead;
  1037. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1038. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1039. int i;
  1040. // we should not do any seeking in the streaming case
  1041. if (!matroska->ctx->pb->seekable ||
  1042. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  1043. return;
  1044. for (i = 0; i < seekhead_list->nb_elem; i++) {
  1045. if (seekhead[i].pos <= before_pos)
  1046. continue;
  1047. // defer cues parsing until we actually need cue data.
  1048. if (seekhead[i].id == MATROSKA_ID_CUES) {
  1049. matroska->cues_parsing_deferred = 1;
  1050. continue;
  1051. }
  1052. if (matroska_parse_seekhead_entry(matroska, i) < 0)
  1053. break;
  1054. }
  1055. }
  1056. static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
  1057. EbmlList *seekhead_list = &matroska->seekhead;
  1058. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1059. EbmlList *index_list;
  1060. MatroskaIndex *index;
  1061. int index_scale = 1;
  1062. int i, j;
  1063. for (i = 0; i < seekhead_list->nb_elem; i++)
  1064. if (seekhead[i].id == MATROSKA_ID_CUES)
  1065. break;
  1066. assert(i <= seekhead_list->nb_elem);
  1067. matroska_parse_seekhead_entry(matroska, i);
  1068. index_list = &matroska->index;
  1069. index = index_list->elem;
  1070. if (index_list->nb_elem
  1071. && index[0].time > 1E14/matroska->time_scale) {
  1072. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1073. index_scale = matroska->time_scale;
  1074. }
  1075. for (i = 0; i < index_list->nb_elem; i++) {
  1076. EbmlList *pos_list = &index[i].pos;
  1077. MatroskaIndexPos *pos = pos_list->elem;
  1078. for (j = 0; j < pos_list->nb_elem; j++) {
  1079. MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
  1080. if (track && track->stream)
  1081. av_add_index_entry(track->stream,
  1082. pos[j].pos + matroska->segment_start,
  1083. index[i].time/index_scale, 0, 0,
  1084. AVINDEX_KEYFRAME);
  1085. }
  1086. }
  1087. }
  1088. static int matroska_aac_profile(char *codec_id)
  1089. {
  1090. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  1091. int profile;
  1092. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  1093. if (strstr(codec_id, aac_profiles[profile]))
  1094. break;
  1095. return profile + 1;
  1096. }
  1097. static int matroska_aac_sri(int samplerate)
  1098. {
  1099. int sri;
  1100. for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
  1101. if (ff_mpeg4audio_sample_rates[sri] == samplerate)
  1102. break;
  1103. return sri;
  1104. }
  1105. static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1106. {
  1107. MatroskaDemuxContext *matroska = s->priv_data;
  1108. EbmlList *attachements_list = &matroska->attachments;
  1109. MatroskaAttachement *attachements;
  1110. EbmlList *chapters_list = &matroska->chapters;
  1111. MatroskaChapter *chapters;
  1112. MatroskaTrack *tracks;
  1113. uint64_t max_start = 0;
  1114. Ebml ebml = { 0 };
  1115. AVStream *st;
  1116. int i, j, res;
  1117. matroska->ctx = s;
  1118. /* First read the EBML header. */
  1119. if (ebml_parse(matroska, ebml_syntax, &ebml)
  1120. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  1121. || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
  1122. av_log(matroska->ctx, AV_LOG_ERROR,
  1123. "EBML header using unsupported features\n"
  1124. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1125. ebml.version, ebml.doctype, ebml.doctype_version);
  1126. ebml_free(ebml_syntax, &ebml);
  1127. return AVERROR_PATCHWELCOME;
  1128. }
  1129. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1130. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1131. break;
  1132. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1133. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1134. }
  1135. ebml_free(ebml_syntax, &ebml);
  1136. /* The next thing is a segment. */
  1137. if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
  1138. return res;
  1139. matroska_execute_seekhead(matroska);
  1140. if (!matroska->time_scale)
  1141. matroska->time_scale = 1000000;
  1142. if (matroska->duration)
  1143. matroska->ctx->duration = matroska->duration * matroska->time_scale
  1144. * 1000 / AV_TIME_BASE;
  1145. av_dict_set(&s->metadata, "title", matroska->title, 0);
  1146. tracks = matroska->tracks.elem;
  1147. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1148. MatroskaTrack *track = &tracks[i];
  1149. enum CodecID codec_id = CODEC_ID_NONE;
  1150. EbmlList *encodings_list = &tracks->encodings;
  1151. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1152. uint8_t *extradata = NULL;
  1153. int extradata_size = 0;
  1154. int extradata_offset = 0;
  1155. AVIOContext b;
  1156. /* Apply some sanity checks. */
  1157. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1158. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1159. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1160. av_log(matroska->ctx, AV_LOG_INFO,
  1161. "Unknown or unsupported track type %"PRIu64"\n",
  1162. track->type);
  1163. continue;
  1164. }
  1165. if (track->codec_id == NULL)
  1166. continue;
  1167. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1168. if (!track->default_duration)
  1169. track->default_duration = 1000000000/track->video.frame_rate;
  1170. if (!track->video.display_width)
  1171. track->video.display_width = track->video.pixel_width;
  1172. if (!track->video.display_height)
  1173. track->video.display_height = track->video.pixel_height;
  1174. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1175. if (!track->audio.out_samplerate)
  1176. track->audio.out_samplerate = track->audio.samplerate;
  1177. }
  1178. if (encodings_list->nb_elem > 1) {
  1179. av_log(matroska->ctx, AV_LOG_ERROR,
  1180. "Multiple combined encodings no supported");
  1181. } else if (encodings_list->nb_elem == 1) {
  1182. if (encodings[0].type ||
  1183. (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
  1184. #if CONFIG_ZLIB
  1185. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1186. #endif
  1187. #if CONFIG_BZLIB
  1188. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1189. #endif
  1190. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
  1191. encodings[0].scope = 0;
  1192. av_log(matroska->ctx, AV_LOG_ERROR,
  1193. "Unsupported encoding type");
  1194. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1195. uint8_t *codec_priv = track->codec_priv.data;
  1196. int offset = matroska_decode_buffer(&track->codec_priv.data,
  1197. &track->codec_priv.size,
  1198. track);
  1199. if (offset < 0) {
  1200. track->codec_priv.data = NULL;
  1201. track->codec_priv.size = 0;
  1202. av_log(matroska->ctx, AV_LOG_ERROR,
  1203. "Failed to decode codec private data\n");
  1204. } else if (offset > 0) {
  1205. track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
  1206. memcpy(track->codec_priv.data,
  1207. encodings[0].compression.settings.data, offset);
  1208. memcpy(track->codec_priv.data+offset, codec_priv,
  1209. track->codec_priv.size);
  1210. track->codec_priv.size += offset;
  1211. }
  1212. if (codec_priv != track->codec_priv.data)
  1213. av_free(codec_priv);
  1214. }
  1215. }
  1216. for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
  1217. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1218. strlen(ff_mkv_codec_tags[j].str))){
  1219. codec_id= ff_mkv_codec_tags[j].id;
  1220. break;
  1221. }
  1222. }
  1223. st = track->stream = av_new_stream(s, 0);
  1224. if (st == NULL)
  1225. return AVERROR(ENOMEM);
  1226. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1227. && track->codec_priv.size >= 40
  1228. && track->codec_priv.data != NULL) {
  1229. track->ms_compat = 1;
  1230. track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
  1231. codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
  1232. extradata_offset = 40;
  1233. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1234. && track->codec_priv.size >= 14
  1235. && track->codec_priv.data != NULL) {
  1236. int ret;
  1237. ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
  1238. AVIO_FLAG_READ, NULL, NULL, NULL, NULL);
  1239. ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1240. if (ret < 0)
  1241. return ret;
  1242. codec_id = st->codec->codec_id;
  1243. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1244. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1245. && (track->codec_priv.size >= 86)
  1246. && (track->codec_priv.data != NULL)) {
  1247. track->video.fourcc = AV_RL32(track->codec_priv.data);
  1248. codec_id=ff_codec_get_id(codec_movvideo_tags, track->video.fourcc);
  1249. } else if (codec_id == CODEC_ID_PCM_S16BE) {
  1250. switch (track->audio.bitdepth) {
  1251. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1252. case 24: codec_id = CODEC_ID_PCM_S24BE; break;
  1253. case 32: codec_id = CODEC_ID_PCM_S32BE; break;
  1254. }
  1255. } else if (codec_id == CODEC_ID_PCM_S16LE) {
  1256. switch (track->audio.bitdepth) {
  1257. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1258. case 24: codec_id = CODEC_ID_PCM_S24LE; break;
  1259. case 32: codec_id = CODEC_ID_PCM_S32LE; break;
  1260. }
  1261. } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1262. codec_id = CODEC_ID_PCM_F64LE;
  1263. } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
  1264. int profile = matroska_aac_profile(track->codec_id);
  1265. int sri = matroska_aac_sri(track->audio.samplerate);
  1266. extradata = av_malloc(5);
  1267. if (extradata == NULL)
  1268. return AVERROR(ENOMEM);
  1269. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1270. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1271. if (strstr(track->codec_id, "SBR")) {
  1272. sri = matroska_aac_sri(track->audio.out_samplerate);
  1273. extradata[2] = 0x56;
  1274. extradata[3] = 0xE5;
  1275. extradata[4] = 0x80 | (sri<<3);
  1276. extradata_size = 5;
  1277. } else
  1278. extradata_size = 2;
  1279. } else if (codec_id == CODEC_ID_TTA) {
  1280. extradata_size = 30;
  1281. extradata = av_mallocz(extradata_size);
  1282. if (extradata == NULL)
  1283. return AVERROR(ENOMEM);
  1284. ffio_init_context(&b, extradata, extradata_size, 1,
  1285. NULL, NULL, NULL, NULL);
  1286. avio_write(&b, "TTA1", 4);
  1287. avio_wl16(&b, 1);
  1288. avio_wl16(&b, track->audio.channels);
  1289. avio_wl16(&b, track->audio.bitdepth);
  1290. avio_wl32(&b, track->audio.out_samplerate);
  1291. avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
  1292. } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
  1293. codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
  1294. extradata_offset = 26;
  1295. } else if (codec_id == CODEC_ID_RA_144) {
  1296. track->audio.out_samplerate = 8000;
  1297. track->audio.channels = 1;
  1298. } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
  1299. codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
  1300. int flavor;
  1301. ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
  1302. 0, NULL, NULL, NULL, NULL);
  1303. avio_skip(&b, 22);
  1304. flavor = avio_rb16(&b);
  1305. track->audio.coded_framesize = avio_rb32(&b);
  1306. avio_skip(&b, 12);
  1307. track->audio.sub_packet_h = avio_rb16(&b);
  1308. track->audio.frame_size = avio_rb16(&b);
  1309. track->audio.sub_packet_size = avio_rb16(&b);
  1310. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1311. if (codec_id == CODEC_ID_RA_288) {
  1312. st->codec->block_align = track->audio.coded_framesize;
  1313. track->codec_priv.size = 0;
  1314. } else {
  1315. if (codec_id == CODEC_ID_SIPR && flavor < 4) {
  1316. const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1317. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1318. st->codec->bit_rate = sipr_bit_rate[flavor];
  1319. }
  1320. st->codec->block_align = track->audio.sub_packet_size;
  1321. extradata_offset = 78;
  1322. }
  1323. }
  1324. track->codec_priv.size -= extradata_offset;
  1325. if (codec_id == CODEC_ID_NONE)
  1326. av_log(matroska->ctx, AV_LOG_INFO,
  1327. "Unknown/unsupported CodecID %s.\n", track->codec_id);
  1328. if (track->time_scale < 0.01)
  1329. track->time_scale = 1.0;
  1330. av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1331. st->codec->codec_id = codec_id;
  1332. st->start_time = 0;
  1333. if (strcmp(track->language, "und"))
  1334. av_dict_set(&st->metadata, "language", track->language, 0);
  1335. av_dict_set(&st->metadata, "title", track->name, 0);
  1336. if (track->flag_default)
  1337. st->disposition |= AV_DISPOSITION_DEFAULT;
  1338. if (track->flag_forced)
  1339. st->disposition |= AV_DISPOSITION_FORCED;
  1340. if (track->default_duration)
  1341. av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
  1342. track->default_duration, 1000000000, 30000);
  1343. if (!st->codec->extradata) {
  1344. if(extradata){
  1345. st->codec->extradata = extradata;
  1346. st->codec->extradata_size = extradata_size;
  1347. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1348. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1349. FF_INPUT_BUFFER_PADDING_SIZE);
  1350. if(st->codec->extradata == NULL)
  1351. return AVERROR(ENOMEM);
  1352. st->codec->extradata_size = track->codec_priv.size;
  1353. memcpy(st->codec->extradata,
  1354. track->codec_priv.data + extradata_offset,
  1355. track->codec_priv.size);
  1356. }
  1357. }
  1358. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1359. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1360. st->codec->codec_tag = track->video.fourcc;
  1361. st->codec->width = track->video.pixel_width;
  1362. st->codec->height = track->video.pixel_height;
  1363. av_reduce(&st->sample_aspect_ratio.num,
  1364. &st->sample_aspect_ratio.den,
  1365. st->codec->height * track->video.display_width,
  1366. st->codec-> width * track->video.display_height,
  1367. 255);
  1368. if (st->codec->codec_id != CODEC_ID_H264)
  1369. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1370. if (track->default_duration)
  1371. st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
  1372. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1373. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1374. st->codec->sample_rate = track->audio.out_samplerate;
  1375. st->codec->channels = track->audio.channels;
  1376. if (st->codec->codec_id != CODEC_ID_AAC)
  1377. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1378. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1379. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1380. }
  1381. }
  1382. attachements = attachements_list->elem;
  1383. for (j=0; j<attachements_list->nb_elem; j++) {
  1384. if (!(attachements[j].filename && attachements[j].mime &&
  1385. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1386. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1387. } else {
  1388. AVStream *st = av_new_stream(s, 0);
  1389. if (st == NULL)
  1390. break;
  1391. av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
  1392. st->codec->codec_id = CODEC_ID_NONE;
  1393. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1394. st->codec->extradata = av_malloc(attachements[j].bin.size);
  1395. if(st->codec->extradata == NULL)
  1396. break;
  1397. st->codec->extradata_size = attachements[j].bin.size;
  1398. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1399. for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
  1400. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1401. strlen(ff_mkv_mime_tags[i].str))) {
  1402. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1403. break;
  1404. }
  1405. }
  1406. attachements[j].stream = st;
  1407. }
  1408. }
  1409. chapters = chapters_list->elem;
  1410. for (i=0; i<chapters_list->nb_elem; i++)
  1411. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1412. && (max_start==0 || chapters[i].start > max_start)) {
  1413. chapters[i].chapter =
  1414. ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1415. chapters[i].start, chapters[i].end,
  1416. chapters[i].title);
  1417. av_dict_set(&chapters[i].chapter->metadata,
  1418. "title", chapters[i].title, 0);
  1419. max_start = chapters[i].start;
  1420. }
  1421. matroska_convert_tags(s);
  1422. return 0;
  1423. }
  1424. /*
  1425. * Put one packet in an application-supplied AVPacket struct.
  1426. * Returns 0 on success or -1 on failure.
  1427. */
  1428. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1429. AVPacket *pkt)
  1430. {
  1431. if (matroska->num_packets > 0) {
  1432. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1433. av_free(matroska->packets[0]);
  1434. if (matroska->num_packets > 1) {
  1435. memmove(&matroska->packets[0], &matroska->packets[1],
  1436. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1437. matroska->packets =
  1438. av_realloc(matroska->packets, (matroska->num_packets - 1) *
  1439. sizeof(AVPacket *));
  1440. } else {
  1441. av_freep(&matroska->packets);
  1442. }
  1443. matroska->num_packets--;
  1444. return 0;
  1445. }
  1446. return -1;
  1447. }
  1448. /*
  1449. * Free all packets in our internal queue.
  1450. */
  1451. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1452. {
  1453. if (matroska->packets) {
  1454. int n;
  1455. for (n = 0; n < matroska->num_packets; n++) {
  1456. av_free_packet(matroska->packets[n]);
  1457. av_free(matroska->packets[n]);
  1458. }
  1459. av_freep(&matroska->packets);
  1460. matroska->num_packets = 0;
  1461. }
  1462. }
  1463. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1464. int size, int64_t pos, uint64_t cluster_time,
  1465. uint64_t duration, int is_keyframe,
  1466. int64_t cluster_pos)
  1467. {
  1468. uint64_t timecode = AV_NOPTS_VALUE;
  1469. MatroskaTrack *track;
  1470. int res = 0;
  1471. AVStream *st;
  1472. AVPacket *pkt;
  1473. int16_t block_time;
  1474. uint32_t *lace_size = NULL;
  1475. int n, flags, laces = 0;
  1476. uint64_t num;
  1477. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  1478. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1479. return res;
  1480. }
  1481. data += n;
  1482. size -= n;
  1483. track = matroska_find_track_by_num(matroska, num);
  1484. if (size <= 3 || !track || !track->stream) {
  1485. av_log(matroska->ctx, AV_LOG_INFO,
  1486. "Invalid stream %"PRIu64" or size %u\n", num, size);
  1487. return AVERROR_INVALIDDATA;
  1488. }
  1489. st = track->stream;
  1490. if (st->discard >= AVDISCARD_ALL)
  1491. return res;
  1492. if (duration == AV_NOPTS_VALUE)
  1493. duration = track->default_duration / matroska->time_scale;
  1494. block_time = AV_RB16(data);
  1495. data += 2;
  1496. flags = *data++;
  1497. size -= 3;
  1498. if (is_keyframe == -1)
  1499. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  1500. if (cluster_time != (uint64_t)-1
  1501. && (block_time >= 0 || cluster_time >= -block_time)) {
  1502. timecode = cluster_time + block_time;
  1503. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  1504. && timecode < track->end_timecode)
  1505. is_keyframe = 0; /* overlapping subtitles are not key frame */
  1506. if (is_keyframe)
  1507. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  1508. track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
  1509. }
  1510. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1511. if (!is_keyframe || timecode < matroska->skip_to_timecode)
  1512. return res;
  1513. matroska->skip_to_keyframe = 0;
  1514. }
  1515. switch ((flags & 0x06) >> 1) {
  1516. case 0x0: /* no lacing */
  1517. laces = 1;
  1518. lace_size = av_mallocz(sizeof(int));
  1519. lace_size[0] = size;
  1520. break;
  1521. case 0x1: /* Xiph lacing */
  1522. case 0x2: /* fixed-size lacing */
  1523. case 0x3: /* EBML lacing */
  1524. assert(size>0); // size <=3 is checked before size-=3 above
  1525. laces = (*data) + 1;
  1526. data += 1;
  1527. size -= 1;
  1528. lace_size = av_mallocz(laces * sizeof(int));
  1529. switch ((flags & 0x06) >> 1) {
  1530. case 0x1: /* Xiph lacing */ {
  1531. uint8_t temp;
  1532. uint32_t total = 0;
  1533. for (n = 0; res == 0 && n < laces - 1; n++) {
  1534. while (1) {
  1535. if (size == 0) {
  1536. res = -1;
  1537. break;
  1538. }
  1539. temp = *data;
  1540. lace_size[n] += temp;
  1541. data += 1;
  1542. size -= 1;
  1543. if (temp != 0xff)
  1544. break;
  1545. }
  1546. total += lace_size[n];
  1547. }
  1548. lace_size[n] = size - total;
  1549. break;
  1550. }
  1551. case 0x2: /* fixed-size lacing */
  1552. for (n = 0; n < laces; n++)
  1553. lace_size[n] = size / laces;
  1554. break;
  1555. case 0x3: /* EBML lacing */ {
  1556. uint32_t total;
  1557. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1558. if (n < 0) {
  1559. av_log(matroska->ctx, AV_LOG_INFO,
  1560. "EBML block data error\n");
  1561. break;
  1562. }
  1563. data += n;
  1564. size -= n;
  1565. total = lace_size[0] = num;
  1566. for (n = 1; res == 0 && n < laces - 1; n++) {
  1567. int64_t snum;
  1568. int r;
  1569. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1570. if (r < 0) {
  1571. av_log(matroska->ctx, AV_LOG_INFO,
  1572. "EBML block data error\n");
  1573. break;
  1574. }
  1575. data += r;
  1576. size -= r;
  1577. lace_size[n] = lace_size[n - 1] + snum;
  1578. total += lace_size[n];
  1579. }
  1580. lace_size[n] = size - total;
  1581. break;
  1582. }
  1583. }
  1584. break;
  1585. }
  1586. if (res == 0) {
  1587. for (n = 0; n < laces; n++) {
  1588. if ((st->codec->codec_id == CODEC_ID_RA_288 ||
  1589. st->codec->codec_id == CODEC_ID_COOK ||
  1590. st->codec->codec_id == CODEC_ID_SIPR ||
  1591. st->codec->codec_id == CODEC_ID_ATRAC3) &&
  1592. st->codec->block_align && track->audio.sub_packet_size) {
  1593. int a = st->codec->block_align;
  1594. int sps = track->audio.sub_packet_size;
  1595. int cfs = track->audio.coded_framesize;
  1596. int h = track->audio.sub_packet_h;
  1597. int y = track->audio.sub_packet_cnt;
  1598. int w = track->audio.frame_size;
  1599. int x;
  1600. if (!track->audio.pkt_cnt) {
  1601. if (track->audio.sub_packet_cnt == 0)
  1602. track->audio.buf_timecode = timecode;
  1603. if (st->codec->codec_id == CODEC_ID_RA_288)
  1604. for (x=0; x<h/2; x++)
  1605. memcpy(track->audio.buf+x*2*w+y*cfs,
  1606. data+x*cfs, cfs);
  1607. else if (st->codec->codec_id == CODEC_ID_SIPR)
  1608. memcpy(track->audio.buf + y*w, data, w);
  1609. else
  1610. for (x=0; x<w/sps; x++)
  1611. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1612. if (++track->audio.sub_packet_cnt >= h) {
  1613. if (st->codec->codec_id == CODEC_ID_SIPR)
  1614. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1615. track->audio.sub_packet_cnt = 0;
  1616. track->audio.pkt_cnt = h*w / a;
  1617. }
  1618. }
  1619. while (track->audio.pkt_cnt) {
  1620. pkt = av_mallocz(sizeof(AVPacket));
  1621. av_new_packet(pkt, a);
  1622. memcpy(pkt->data, track->audio.buf
  1623. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1624. pkt->pts = track->audio.buf_timecode;
  1625. track->audio.buf_timecode = AV_NOPTS_VALUE;
  1626. pkt->pos = pos;
  1627. pkt->stream_index = st->index;
  1628. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1629. }
  1630. } else {
  1631. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1632. int offset = 0, pkt_size = lace_size[n];
  1633. uint8_t *pkt_data = data;
  1634. if (pkt_size > size) {
  1635. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
  1636. break;
  1637. }
  1638. if (encodings && encodings->scope & 1) {
  1639. offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
  1640. if (offset < 0)
  1641. continue;
  1642. }
  1643. pkt = av_mallocz(sizeof(AVPacket));
  1644. /* XXX: prevent data copy... */
  1645. if (av_new_packet(pkt, pkt_size+offset) < 0) {
  1646. av_free(pkt);
  1647. res = AVERROR(ENOMEM);
  1648. break;
  1649. }
  1650. if (offset)
  1651. memcpy (pkt->data, encodings->compression.settings.data, offset);
  1652. memcpy (pkt->data+offset, pkt_data, pkt_size);
  1653. if (pkt_data != data)
  1654. av_free(pkt_data);
  1655. if (n == 0)
  1656. pkt->flags = is_keyframe;
  1657. pkt->stream_index = st->index;
  1658. if (track->ms_compat)
  1659. pkt->dts = timecode;
  1660. else
  1661. pkt->pts = timecode;
  1662. pkt->pos = pos;
  1663. if (st->codec->codec_id == CODEC_ID_TEXT)
  1664. pkt->convergence_duration = duration;
  1665. else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
  1666. pkt->duration = duration;
  1667. if (st->codec->codec_id == CODEC_ID_SSA)
  1668. matroska_fix_ass_packet(matroska, pkt, duration);
  1669. if (matroska->prev_pkt &&
  1670. timecode != AV_NOPTS_VALUE &&
  1671. matroska->prev_pkt->pts == timecode &&
  1672. matroska->prev_pkt->stream_index == st->index &&
  1673. st->codec->codec_id == CODEC_ID_SSA)
  1674. matroska_merge_packets(matroska->prev_pkt, pkt);
  1675. else {
  1676. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1677. matroska->prev_pkt = pkt;
  1678. }
  1679. }
  1680. if (timecode != AV_NOPTS_VALUE)
  1681. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  1682. data += lace_size[n];
  1683. size -= lace_size[n];
  1684. }
  1685. }
  1686. av_free(lace_size);
  1687. return res;
  1688. }
  1689. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  1690. {
  1691. MatroskaCluster cluster = { 0 };
  1692. EbmlList *blocks_list;
  1693. MatroskaBlock *blocks;
  1694. int i, res;
  1695. int64_t pos = avio_tell(matroska->ctx->pb);
  1696. matroska->prev_pkt = NULL;
  1697. if (matroska->current_id)
  1698. pos -= 4; /* sizeof the ID which was already read */
  1699. res = ebml_parse(matroska, matroska_clusters, &cluster);
  1700. blocks_list = &cluster.blocks;
  1701. blocks = blocks_list->elem;
  1702. for (i=0; i<blocks_list->nb_elem && !res; i++)
  1703. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  1704. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  1705. if (!blocks[i].non_simple)
  1706. blocks[i].duration = AV_NOPTS_VALUE;
  1707. res=matroska_parse_block(matroska,
  1708. blocks[i].bin.data, blocks[i].bin.size,
  1709. blocks[i].bin.pos, cluster.timecode,
  1710. blocks[i].duration, is_keyframe,
  1711. pos);
  1712. }
  1713. ebml_free(matroska_cluster, &cluster);
  1714. if (res < 0) matroska->done = 1;
  1715. return res;
  1716. }
  1717. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  1718. {
  1719. MatroskaDemuxContext *matroska = s->priv_data;
  1720. int ret = 0;
  1721. while (!ret && matroska_deliver_packet(matroska, pkt)) {
  1722. if (matroska->done)
  1723. return AVERROR_EOF;
  1724. ret = matroska_parse_cluster(matroska);
  1725. }
  1726. return ret;
  1727. }
  1728. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  1729. int64_t timestamp, int flags)
  1730. {
  1731. MatroskaDemuxContext *matroska = s->priv_data;
  1732. MatroskaTrack *tracks = matroska->tracks.elem;
  1733. AVStream *st = s->streams[stream_index];
  1734. int i, index, index_sub, index_min;
  1735. /* Parse the CUES now since we need the index data to seek. */
  1736. if (matroska->cues_parsing_deferred) {
  1737. matroska_parse_cues(matroska);
  1738. matroska->cues_parsing_deferred = 0;
  1739. }
  1740. if (!st->nb_index_entries)
  1741. return 0;
  1742. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  1743. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1744. avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  1745. matroska->current_id = 0;
  1746. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1747. matroska_clear_queue(matroska);
  1748. if (matroska_parse_cluster(matroska) < 0)
  1749. break;
  1750. }
  1751. }
  1752. matroska_clear_queue(matroska);
  1753. if (index < 0)
  1754. return 0;
  1755. index_min = index;
  1756. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1757. tracks[i].audio.pkt_cnt = 0;
  1758. tracks[i].audio.sub_packet_cnt = 0;
  1759. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  1760. tracks[i].end_timecode = 0;
  1761. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  1762. && !tracks[i].stream->discard != AVDISCARD_ALL) {
  1763. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  1764. if (index_sub >= 0
  1765. && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
  1766. && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  1767. index_min = index_sub;
  1768. }
  1769. }
  1770. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  1771. matroska->current_id = 0;
  1772. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  1773. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  1774. matroska->done = 0;
  1775. av_update_cur_dts(s, st, st->index_entries[index].timestamp);
  1776. return 0;
  1777. }
  1778. static int matroska_read_close(AVFormatContext *s)
  1779. {
  1780. MatroskaDemuxContext *matroska = s->priv_data;
  1781. MatroskaTrack *tracks = matroska->tracks.elem;
  1782. int n;
  1783. matroska_clear_queue(matroska);
  1784. for (n=0; n < matroska->tracks.nb_elem; n++)
  1785. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  1786. av_free(tracks[n].audio.buf);
  1787. ebml_free(matroska_segment, matroska);
  1788. return 0;
  1789. }
  1790. AVInputFormat ff_matroska_demuxer = {
  1791. .name = "matroska,webm",
  1792. .long_name = NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
  1793. .priv_data_size = sizeof(MatroskaDemuxContext),
  1794. .read_probe = matroska_probe,
  1795. .read_header = matroska_read_header,
  1796. .read_packet = matroska_read_packet,
  1797. .read_close = matroska_read_close,
  1798. .read_seek = matroska_read_seek,
  1799. };