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.

1961 lines
70KB

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