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.

1970 lines
70KB

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