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.

1959 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), {.u=AV_NOPTS_VALUE} },
  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_seek(pb,length,SEEK_CUR)<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. matroska_convert_tag(s, &tags[i].tag,
  963. &attachment[j].stream->metadata, NULL);
  964. } else if (tags[i].target.chapteruid) {
  965. MatroskaChapter *chapter = matroska->chapters.elem;
  966. for (j=0; j<matroska->chapters.nb_elem; j++)
  967. if (chapter[j].uid == tags[i].target.chapteruid)
  968. matroska_convert_tag(s, &tags[i].tag,
  969. &chapter[j].chapter->metadata, NULL);
  970. } else if (tags[i].target.trackuid) {
  971. MatroskaTrack *track = matroska->tracks.elem;
  972. for (j=0; j<matroska->tracks.nb_elem; j++)
  973. if (track[j].uid == tags[i].target.trackuid)
  974. matroska_convert_tag(s, &tags[i].tag,
  975. &track[j].stream->metadata, NULL);
  976. } else {
  977. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  978. tags[i].target.type);
  979. }
  980. }
  981. }
  982. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  983. {
  984. EbmlList *seekhead_list = &matroska->seekhead;
  985. MatroskaSeekhead *seekhead = seekhead_list->elem;
  986. uint32_t level_up = matroska->level_up;
  987. int64_t before_pos = avio_tell(matroska->ctx->pb);
  988. uint32_t saved_id = matroska->current_id;
  989. MatroskaLevel level;
  990. int i;
  991. // we should not do any seeking in the streaming case
  992. if (url_is_streamed(matroska->ctx->pb) ||
  993. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  994. return;
  995. for (i=0; i<seekhead_list->nb_elem; i++) {
  996. int64_t offset = seekhead[i].pos + matroska->segment_start;
  997. if (seekhead[i].pos <= before_pos
  998. || seekhead[i].id == MATROSKA_ID_SEEKHEAD
  999. || seekhead[i].id == MATROSKA_ID_CLUSTER)
  1000. continue;
  1001. /* seek */
  1002. if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) != offset)
  1003. continue;
  1004. /* We don't want to lose our seekhead level, so we add
  1005. * a dummy. This is a crude hack. */
  1006. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1007. av_log(matroska->ctx, AV_LOG_INFO,
  1008. "Max EBML element depth (%d) reached, "
  1009. "cannot parse further.\n", EBML_MAX_DEPTH);
  1010. break;
  1011. }
  1012. level.start = 0;
  1013. level.length = (uint64_t)-1;
  1014. matroska->levels[matroska->num_levels] = level;
  1015. matroska->num_levels++;
  1016. matroska->current_id = 0;
  1017. ebml_parse(matroska, matroska_segment, matroska);
  1018. /* remove dummy level */
  1019. while (matroska->num_levels) {
  1020. uint64_t length = matroska->levels[--matroska->num_levels].length;
  1021. if (length == (uint64_t)-1)
  1022. break;
  1023. }
  1024. }
  1025. /* seek back */
  1026. avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
  1027. matroska->level_up = level_up;
  1028. matroska->current_id = saved_id;
  1029. }
  1030. static int matroska_aac_profile(char *codec_id)
  1031. {
  1032. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  1033. int profile;
  1034. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  1035. if (strstr(codec_id, aac_profiles[profile]))
  1036. break;
  1037. return profile + 1;
  1038. }
  1039. static int matroska_aac_sri(int samplerate)
  1040. {
  1041. int sri;
  1042. for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
  1043. if (ff_mpeg4audio_sample_rates[sri] == samplerate)
  1044. break;
  1045. return sri;
  1046. }
  1047. static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1048. {
  1049. MatroskaDemuxContext *matroska = s->priv_data;
  1050. EbmlList *attachements_list = &matroska->attachments;
  1051. MatroskaAttachement *attachements;
  1052. EbmlList *chapters_list = &matroska->chapters;
  1053. MatroskaChapter *chapters;
  1054. MatroskaTrack *tracks;
  1055. EbmlList *index_list;
  1056. MatroskaIndex *index;
  1057. int index_scale = 1;
  1058. uint64_t max_start = 0;
  1059. Ebml ebml = { 0 };
  1060. AVStream *st;
  1061. int i, j, res;
  1062. matroska->ctx = s;
  1063. /* First read the EBML header. */
  1064. if (ebml_parse(matroska, ebml_syntax, &ebml)
  1065. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  1066. || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
  1067. av_log(matroska->ctx, AV_LOG_ERROR,
  1068. "EBML header using unsupported features\n"
  1069. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1070. ebml.version, ebml.doctype, ebml.doctype_version);
  1071. ebml_free(ebml_syntax, &ebml);
  1072. return AVERROR_PATCHWELCOME;
  1073. }
  1074. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1075. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1076. break;
  1077. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1078. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1079. }
  1080. ebml_free(ebml_syntax, &ebml);
  1081. /* The next thing is a segment. */
  1082. if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
  1083. return res;
  1084. matroska_execute_seekhead(matroska);
  1085. if (!matroska->time_scale)
  1086. matroska->time_scale = 1000000;
  1087. if (matroska->duration)
  1088. matroska->ctx->duration = matroska->duration * matroska->time_scale
  1089. * 1000 / AV_TIME_BASE;
  1090. av_metadata_set2(&s->metadata, "title", matroska->title, 0);
  1091. tracks = matroska->tracks.elem;
  1092. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1093. MatroskaTrack *track = &tracks[i];
  1094. enum CodecID codec_id = CODEC_ID_NONE;
  1095. EbmlList *encodings_list = &tracks->encodings;
  1096. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1097. uint8_t *extradata = NULL;
  1098. int extradata_size = 0;
  1099. int extradata_offset = 0;
  1100. AVIOContext b;
  1101. /* Apply some sanity checks. */
  1102. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1103. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1104. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1105. av_log(matroska->ctx, AV_LOG_INFO,
  1106. "Unknown or unsupported track type %"PRIu64"\n",
  1107. track->type);
  1108. continue;
  1109. }
  1110. if (track->codec_id == NULL)
  1111. continue;
  1112. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1113. if (!track->default_duration)
  1114. track->default_duration = 1000000000/track->video.frame_rate;
  1115. if (!track->video.display_width)
  1116. track->video.display_width = track->video.pixel_width;
  1117. if (!track->video.display_height)
  1118. track->video.display_height = track->video.pixel_height;
  1119. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1120. if (!track->audio.out_samplerate)
  1121. track->audio.out_samplerate = track->audio.samplerate;
  1122. }
  1123. if (encodings_list->nb_elem > 1) {
  1124. av_log(matroska->ctx, AV_LOG_ERROR,
  1125. "Multiple combined encodings no supported");
  1126. } else if (encodings_list->nb_elem == 1) {
  1127. if (encodings[0].type ||
  1128. (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
  1129. #if CONFIG_ZLIB
  1130. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1131. #endif
  1132. #if CONFIG_BZLIB
  1133. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1134. #endif
  1135. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
  1136. encodings[0].scope = 0;
  1137. av_log(matroska->ctx, AV_LOG_ERROR,
  1138. "Unsupported encoding type");
  1139. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1140. uint8_t *codec_priv = track->codec_priv.data;
  1141. int offset = matroska_decode_buffer(&track->codec_priv.data,
  1142. &track->codec_priv.size,
  1143. track);
  1144. if (offset < 0) {
  1145. track->codec_priv.data = NULL;
  1146. track->codec_priv.size = 0;
  1147. av_log(matroska->ctx, AV_LOG_ERROR,
  1148. "Failed to decode codec private data\n");
  1149. } else if (offset > 0) {
  1150. track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
  1151. memcpy(track->codec_priv.data,
  1152. encodings[0].compression.settings.data, offset);
  1153. memcpy(track->codec_priv.data+offset, codec_priv,
  1154. track->codec_priv.size);
  1155. track->codec_priv.size += offset;
  1156. }
  1157. if (codec_priv != track->codec_priv.data)
  1158. av_free(codec_priv);
  1159. }
  1160. }
  1161. for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
  1162. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1163. strlen(ff_mkv_codec_tags[j].str))){
  1164. codec_id= ff_mkv_codec_tags[j].id;
  1165. break;
  1166. }
  1167. }
  1168. st = track->stream = av_new_stream(s, 0);
  1169. if (st == NULL)
  1170. return AVERROR(ENOMEM);
  1171. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1172. && track->codec_priv.size >= 40
  1173. && track->codec_priv.data != NULL) {
  1174. track->ms_compat = 1;
  1175. track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
  1176. codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
  1177. extradata_offset = 40;
  1178. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1179. && track->codec_priv.size >= 14
  1180. && track->codec_priv.data != NULL) {
  1181. ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
  1182. URL_RDONLY, NULL, NULL, NULL, NULL);
  1183. ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1184. codec_id = st->codec->codec_id;
  1185. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1186. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1187. && (track->codec_priv.size >= 86)
  1188. && (track->codec_priv.data != NULL)) {
  1189. track->video.fourcc = AV_RL32(track->codec_priv.data);
  1190. codec_id=ff_codec_get_id(codec_movvideo_tags, track->video.fourcc);
  1191. } else if (codec_id == CODEC_ID_PCM_S16BE) {
  1192. switch (track->audio.bitdepth) {
  1193. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1194. case 24: codec_id = CODEC_ID_PCM_S24BE; break;
  1195. case 32: codec_id = CODEC_ID_PCM_S32BE; break;
  1196. }
  1197. } else if (codec_id == CODEC_ID_PCM_S16LE) {
  1198. switch (track->audio.bitdepth) {
  1199. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1200. case 24: codec_id = CODEC_ID_PCM_S24LE; break;
  1201. case 32: codec_id = CODEC_ID_PCM_S32LE; break;
  1202. }
  1203. } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1204. codec_id = CODEC_ID_PCM_F64LE;
  1205. } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
  1206. int profile = matroska_aac_profile(track->codec_id);
  1207. int sri = matroska_aac_sri(track->audio.samplerate);
  1208. extradata = av_malloc(5);
  1209. if (extradata == NULL)
  1210. return AVERROR(ENOMEM);
  1211. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1212. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1213. if (strstr(track->codec_id, "SBR")) {
  1214. sri = matroska_aac_sri(track->audio.out_samplerate);
  1215. extradata[2] = 0x56;
  1216. extradata[3] = 0xE5;
  1217. extradata[4] = 0x80 | (sri<<3);
  1218. extradata_size = 5;
  1219. } else
  1220. extradata_size = 2;
  1221. } else if (codec_id == CODEC_ID_TTA) {
  1222. extradata_size = 30;
  1223. extradata = av_mallocz(extradata_size);
  1224. if (extradata == NULL)
  1225. return AVERROR(ENOMEM);
  1226. ffio_init_context(&b, extradata, extradata_size, 1,
  1227. NULL, NULL, NULL, NULL);
  1228. avio_write(&b, "TTA1", 4);
  1229. avio_wl16(&b, 1);
  1230. avio_wl16(&b, track->audio.channels);
  1231. avio_wl16(&b, track->audio.bitdepth);
  1232. avio_wl32(&b, track->audio.out_samplerate);
  1233. avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
  1234. } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
  1235. codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
  1236. extradata_offset = 26;
  1237. } else if (codec_id == CODEC_ID_RA_144) {
  1238. track->audio.out_samplerate = 8000;
  1239. track->audio.channels = 1;
  1240. } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
  1241. codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
  1242. int flavor;
  1243. ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
  1244. 0, NULL, NULL, NULL, NULL);
  1245. avio_seek(&b, 22, SEEK_CUR);
  1246. flavor = avio_rb16(&b);
  1247. track->audio.coded_framesize = avio_rb32(&b);
  1248. avio_seek(&b, 12, SEEK_CUR);
  1249. track->audio.sub_packet_h = avio_rb16(&b);
  1250. track->audio.frame_size = avio_rb16(&b);
  1251. track->audio.sub_packet_size = avio_rb16(&b);
  1252. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1253. if (codec_id == CODEC_ID_RA_288) {
  1254. st->codec->block_align = track->audio.coded_framesize;
  1255. track->codec_priv.size = 0;
  1256. } else {
  1257. if (codec_id == CODEC_ID_SIPR && flavor < 4) {
  1258. const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1259. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1260. st->codec->bit_rate = sipr_bit_rate[flavor];
  1261. }
  1262. st->codec->block_align = track->audio.sub_packet_size;
  1263. extradata_offset = 78;
  1264. }
  1265. }
  1266. track->codec_priv.size -= extradata_offset;
  1267. if (codec_id == CODEC_ID_NONE)
  1268. av_log(matroska->ctx, AV_LOG_INFO,
  1269. "Unknown/unsupported CodecID %s.\n", track->codec_id);
  1270. if (track->time_scale < 0.01)
  1271. track->time_scale = 1.0;
  1272. av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1273. st->codec->codec_id = codec_id;
  1274. st->start_time = 0;
  1275. if (strcmp(track->language, "und"))
  1276. av_metadata_set2(&st->metadata, "language", track->language, 0);
  1277. av_metadata_set2(&st->metadata, "title", track->name, 0);
  1278. if (track->flag_default)
  1279. st->disposition |= AV_DISPOSITION_DEFAULT;
  1280. if (track->flag_forced)
  1281. st->disposition |= AV_DISPOSITION_FORCED;
  1282. if (track->default_duration)
  1283. av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
  1284. track->default_duration, 1000000000, 30000);
  1285. if (!st->codec->extradata) {
  1286. if(extradata){
  1287. st->codec->extradata = extradata;
  1288. st->codec->extradata_size = extradata_size;
  1289. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1290. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1291. FF_INPUT_BUFFER_PADDING_SIZE);
  1292. if(st->codec->extradata == NULL)
  1293. return AVERROR(ENOMEM);
  1294. st->codec->extradata_size = track->codec_priv.size;
  1295. memcpy(st->codec->extradata,
  1296. track->codec_priv.data + extradata_offset,
  1297. track->codec_priv.size);
  1298. }
  1299. }
  1300. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1301. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1302. st->codec->codec_tag = track->video.fourcc;
  1303. st->codec->width = track->video.pixel_width;
  1304. st->codec->height = track->video.pixel_height;
  1305. av_reduce(&st->sample_aspect_ratio.num,
  1306. &st->sample_aspect_ratio.den,
  1307. st->codec->height * track->video.display_width,
  1308. st->codec-> width * track->video.display_height,
  1309. 255);
  1310. if (st->codec->codec_id != CODEC_ID_H264)
  1311. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1312. if (track->default_duration)
  1313. st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
  1314. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1315. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1316. st->codec->sample_rate = track->audio.out_samplerate;
  1317. st->codec->channels = track->audio.channels;
  1318. if (st->codec->codec_id != CODEC_ID_AAC)
  1319. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1320. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1321. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1322. }
  1323. }
  1324. attachements = attachements_list->elem;
  1325. for (j=0; j<attachements_list->nb_elem; j++) {
  1326. if (!(attachements[j].filename && attachements[j].mime &&
  1327. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1328. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1329. } else {
  1330. AVStream *st = av_new_stream(s, 0);
  1331. if (st == NULL)
  1332. break;
  1333. av_metadata_set2(&st->metadata, "filename",attachements[j].filename, 0);
  1334. st->codec->codec_id = CODEC_ID_NONE;
  1335. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1336. st->codec->extradata = av_malloc(attachements[j].bin.size);
  1337. if(st->codec->extradata == NULL)
  1338. break;
  1339. st->codec->extradata_size = attachements[j].bin.size;
  1340. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1341. for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
  1342. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1343. strlen(ff_mkv_mime_tags[i].str))) {
  1344. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1345. break;
  1346. }
  1347. }
  1348. attachements[j].stream = st;
  1349. }
  1350. }
  1351. chapters = chapters_list->elem;
  1352. for (i=0; i<chapters_list->nb_elem; i++)
  1353. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1354. && (max_start==0 || chapters[i].start > max_start)) {
  1355. chapters[i].chapter =
  1356. ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1357. chapters[i].start, chapters[i].end,
  1358. chapters[i].title);
  1359. av_metadata_set2(&chapters[i].chapter->metadata,
  1360. "title", chapters[i].title, 0);
  1361. max_start = chapters[i].start;
  1362. }
  1363. index_list = &matroska->index;
  1364. index = index_list->elem;
  1365. if (index_list->nb_elem
  1366. && index[0].time > 100000000000000/matroska->time_scale) {
  1367. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1368. index_scale = matroska->time_scale;
  1369. }
  1370. for (i=0; i<index_list->nb_elem; i++) {
  1371. EbmlList *pos_list = &index[i].pos;
  1372. MatroskaIndexPos *pos = pos_list->elem;
  1373. for (j=0; j<pos_list->nb_elem; j++) {
  1374. MatroskaTrack *track = matroska_find_track_by_num(matroska,
  1375. pos[j].track);
  1376. if (track && track->stream)
  1377. av_add_index_entry(track->stream,
  1378. pos[j].pos + matroska->segment_start,
  1379. index[i].time/index_scale, 0, 0,
  1380. AVINDEX_KEYFRAME);
  1381. }
  1382. }
  1383. matroska_convert_tags(s);
  1384. return 0;
  1385. }
  1386. /*
  1387. * Put one packet in an application-supplied AVPacket struct.
  1388. * Returns 0 on success or -1 on failure.
  1389. */
  1390. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1391. AVPacket *pkt)
  1392. {
  1393. if (matroska->num_packets > 0) {
  1394. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1395. av_free(matroska->packets[0]);
  1396. if (matroska->num_packets > 1) {
  1397. memmove(&matroska->packets[0], &matroska->packets[1],
  1398. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1399. matroska->packets =
  1400. av_realloc(matroska->packets, (matroska->num_packets - 1) *
  1401. sizeof(AVPacket *));
  1402. } else {
  1403. av_freep(&matroska->packets);
  1404. }
  1405. matroska->num_packets--;
  1406. return 0;
  1407. }
  1408. return -1;
  1409. }
  1410. /*
  1411. * Free all packets in our internal queue.
  1412. */
  1413. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1414. {
  1415. if (matroska->packets) {
  1416. int n;
  1417. for (n = 0; n < matroska->num_packets; n++) {
  1418. av_free_packet(matroska->packets[n]);
  1419. av_free(matroska->packets[n]);
  1420. }
  1421. av_freep(&matroska->packets);
  1422. matroska->num_packets = 0;
  1423. }
  1424. }
  1425. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1426. int size, int64_t pos, uint64_t cluster_time,
  1427. uint64_t duration, int is_keyframe,
  1428. int64_t cluster_pos)
  1429. {
  1430. uint64_t timecode = AV_NOPTS_VALUE;
  1431. MatroskaTrack *track;
  1432. int res = 0;
  1433. AVStream *st;
  1434. AVPacket *pkt;
  1435. int16_t block_time;
  1436. uint32_t *lace_size = NULL;
  1437. int n, flags, laces = 0;
  1438. uint64_t num;
  1439. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  1440. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1441. return res;
  1442. }
  1443. data += n;
  1444. size -= n;
  1445. track = matroska_find_track_by_num(matroska, num);
  1446. if (size <= 3 || !track || !track->stream) {
  1447. av_log(matroska->ctx, AV_LOG_INFO,
  1448. "Invalid stream %"PRIu64" or size %u\n", num, size);
  1449. return res;
  1450. }
  1451. st = track->stream;
  1452. if (st->discard >= AVDISCARD_ALL)
  1453. return res;
  1454. if (duration == AV_NOPTS_VALUE)
  1455. duration = track->default_duration / matroska->time_scale;
  1456. block_time = AV_RB16(data);
  1457. data += 2;
  1458. flags = *data++;
  1459. size -= 3;
  1460. if (is_keyframe == -1)
  1461. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  1462. if (cluster_time != (uint64_t)-1
  1463. && (block_time >= 0 || cluster_time >= -block_time)) {
  1464. timecode = cluster_time + block_time;
  1465. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  1466. && timecode < track->end_timecode)
  1467. is_keyframe = 0; /* overlapping subtitles are not key frame */
  1468. if (is_keyframe)
  1469. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  1470. track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
  1471. }
  1472. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1473. if (!is_keyframe || timecode < matroska->skip_to_timecode)
  1474. return res;
  1475. matroska->skip_to_keyframe = 0;
  1476. }
  1477. switch ((flags & 0x06) >> 1) {
  1478. case 0x0: /* no lacing */
  1479. laces = 1;
  1480. lace_size = av_mallocz(sizeof(int));
  1481. lace_size[0] = size;
  1482. break;
  1483. case 0x1: /* Xiph lacing */
  1484. case 0x2: /* fixed-size lacing */
  1485. case 0x3: /* EBML lacing */
  1486. assert(size>0); // size <=3 is checked before size-=3 above
  1487. laces = (*data) + 1;
  1488. data += 1;
  1489. size -= 1;
  1490. lace_size = av_mallocz(laces * sizeof(int));
  1491. switch ((flags & 0x06) >> 1) {
  1492. case 0x1: /* Xiph lacing */ {
  1493. uint8_t temp;
  1494. uint32_t total = 0;
  1495. for (n = 0; res == 0 && n < laces - 1; n++) {
  1496. while (1) {
  1497. if (size == 0) {
  1498. res = -1;
  1499. break;
  1500. }
  1501. temp = *data;
  1502. lace_size[n] += temp;
  1503. data += 1;
  1504. size -= 1;
  1505. if (temp != 0xff)
  1506. break;
  1507. }
  1508. total += lace_size[n];
  1509. }
  1510. lace_size[n] = size - total;
  1511. break;
  1512. }
  1513. case 0x2: /* fixed-size lacing */
  1514. for (n = 0; n < laces; n++)
  1515. lace_size[n] = size / laces;
  1516. break;
  1517. case 0x3: /* EBML lacing */ {
  1518. uint32_t total;
  1519. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1520. if (n < 0) {
  1521. av_log(matroska->ctx, AV_LOG_INFO,
  1522. "EBML block data error\n");
  1523. break;
  1524. }
  1525. data += n;
  1526. size -= n;
  1527. total = lace_size[0] = num;
  1528. for (n = 1; res == 0 && n < laces - 1; n++) {
  1529. int64_t snum;
  1530. int r;
  1531. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1532. if (r < 0) {
  1533. av_log(matroska->ctx, AV_LOG_INFO,
  1534. "EBML block data error\n");
  1535. break;
  1536. }
  1537. data += r;
  1538. size -= r;
  1539. lace_size[n] = lace_size[n - 1] + snum;
  1540. total += lace_size[n];
  1541. }
  1542. lace_size[n] = size - total;
  1543. break;
  1544. }
  1545. }
  1546. break;
  1547. }
  1548. if (res == 0) {
  1549. for (n = 0; n < laces; n++) {
  1550. if ((st->codec->codec_id == CODEC_ID_RA_288 ||
  1551. st->codec->codec_id == CODEC_ID_COOK ||
  1552. st->codec->codec_id == CODEC_ID_SIPR ||
  1553. st->codec->codec_id == CODEC_ID_ATRAC3) &&
  1554. st->codec->block_align && track->audio.sub_packet_size) {
  1555. int a = st->codec->block_align;
  1556. int sps = track->audio.sub_packet_size;
  1557. int cfs = track->audio.coded_framesize;
  1558. int h = track->audio.sub_packet_h;
  1559. int y = track->audio.sub_packet_cnt;
  1560. int w = track->audio.frame_size;
  1561. int x;
  1562. if (!track->audio.pkt_cnt) {
  1563. if (track->audio.sub_packet_cnt == 0)
  1564. track->audio.buf_timecode = timecode;
  1565. if (st->codec->codec_id == CODEC_ID_RA_288)
  1566. for (x=0; x<h/2; x++)
  1567. memcpy(track->audio.buf+x*2*w+y*cfs,
  1568. data+x*cfs, cfs);
  1569. else if (st->codec->codec_id == CODEC_ID_SIPR)
  1570. memcpy(track->audio.buf + y*w, data, w);
  1571. else
  1572. for (x=0; x<w/sps; x++)
  1573. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1574. if (++track->audio.sub_packet_cnt >= h) {
  1575. if (st->codec->codec_id == CODEC_ID_SIPR)
  1576. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1577. track->audio.sub_packet_cnt = 0;
  1578. track->audio.pkt_cnt = h*w / a;
  1579. }
  1580. }
  1581. while (track->audio.pkt_cnt) {
  1582. pkt = av_mallocz(sizeof(AVPacket));
  1583. av_new_packet(pkt, a);
  1584. memcpy(pkt->data, track->audio.buf
  1585. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1586. pkt->pts = track->audio.buf_timecode;
  1587. track->audio.buf_timecode = AV_NOPTS_VALUE;
  1588. pkt->pos = pos;
  1589. pkt->stream_index = st->index;
  1590. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1591. }
  1592. } else {
  1593. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1594. int offset = 0, pkt_size = lace_size[n];
  1595. uint8_t *pkt_data = data;
  1596. if (pkt_size > size) {
  1597. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
  1598. break;
  1599. }
  1600. if (encodings && encodings->scope & 1) {
  1601. offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
  1602. if (offset < 0)
  1603. continue;
  1604. }
  1605. pkt = av_mallocz(sizeof(AVPacket));
  1606. /* XXX: prevent data copy... */
  1607. if (av_new_packet(pkt, pkt_size+offset) < 0) {
  1608. av_free(pkt);
  1609. res = AVERROR(ENOMEM);
  1610. break;
  1611. }
  1612. if (offset)
  1613. memcpy (pkt->data, encodings->compression.settings.data, offset);
  1614. memcpy (pkt->data+offset, pkt_data, pkt_size);
  1615. if (pkt_data != data)
  1616. av_free(pkt_data);
  1617. if (n == 0)
  1618. pkt->flags = is_keyframe;
  1619. pkt->stream_index = st->index;
  1620. if (track->ms_compat)
  1621. pkt->dts = timecode;
  1622. else
  1623. pkt->pts = timecode;
  1624. pkt->pos = pos;
  1625. if (st->codec->codec_id == CODEC_ID_TEXT)
  1626. pkt->convergence_duration = duration;
  1627. else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
  1628. pkt->duration = duration;
  1629. if (st->codec->codec_id == CODEC_ID_SSA)
  1630. matroska_fix_ass_packet(matroska, pkt, duration);
  1631. if (matroska->prev_pkt &&
  1632. timecode != AV_NOPTS_VALUE &&
  1633. matroska->prev_pkt->pts == timecode &&
  1634. matroska->prev_pkt->stream_index == st->index &&
  1635. st->codec->codec_id == CODEC_ID_SSA)
  1636. matroska_merge_packets(matroska->prev_pkt, pkt);
  1637. else {
  1638. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1639. matroska->prev_pkt = pkt;
  1640. }
  1641. }
  1642. if (timecode != AV_NOPTS_VALUE)
  1643. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  1644. data += lace_size[n];
  1645. size -= lace_size[n];
  1646. }
  1647. }
  1648. av_free(lace_size);
  1649. return res;
  1650. }
  1651. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  1652. {
  1653. MatroskaCluster cluster = { 0 };
  1654. EbmlList *blocks_list;
  1655. MatroskaBlock *blocks;
  1656. int i, res;
  1657. int64_t pos = avio_tell(matroska->ctx->pb);
  1658. matroska->prev_pkt = NULL;
  1659. if (matroska->current_id)
  1660. pos -= 4; /* sizeof the ID which was already read */
  1661. res = ebml_parse(matroska, matroska_clusters, &cluster);
  1662. blocks_list = &cluster.blocks;
  1663. blocks = blocks_list->elem;
  1664. for (i=0; i<blocks_list->nb_elem; i++)
  1665. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  1666. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  1667. res=matroska_parse_block(matroska,
  1668. blocks[i].bin.data, blocks[i].bin.size,
  1669. blocks[i].bin.pos, cluster.timecode,
  1670. blocks[i].duration, is_keyframe,
  1671. pos);
  1672. }
  1673. ebml_free(matroska_cluster, &cluster);
  1674. if (res < 0) matroska->done = 1;
  1675. return res;
  1676. }
  1677. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  1678. {
  1679. MatroskaDemuxContext *matroska = s->priv_data;
  1680. while (matroska_deliver_packet(matroska, pkt)) {
  1681. if (matroska->done)
  1682. return AVERROR_EOF;
  1683. matroska_parse_cluster(matroska);
  1684. }
  1685. return 0;
  1686. }
  1687. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  1688. int64_t timestamp, int flags)
  1689. {
  1690. MatroskaDemuxContext *matroska = s->priv_data;
  1691. MatroskaTrack *tracks = matroska->tracks.elem;
  1692. AVStream *st = s->streams[stream_index];
  1693. int i, index, index_sub, index_min;
  1694. if (!st->nb_index_entries)
  1695. return 0;
  1696. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  1697. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1698. avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  1699. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1700. matroska_clear_queue(matroska);
  1701. if (matroska_parse_cluster(matroska) < 0)
  1702. break;
  1703. }
  1704. }
  1705. matroska_clear_queue(matroska);
  1706. if (index < 0)
  1707. return 0;
  1708. index_min = index;
  1709. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1710. tracks[i].audio.pkt_cnt = 0;
  1711. tracks[i].audio.sub_packet_cnt = 0;
  1712. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  1713. tracks[i].end_timecode = 0;
  1714. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  1715. && !tracks[i].stream->discard != AVDISCARD_ALL) {
  1716. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  1717. if (index_sub >= 0
  1718. && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
  1719. && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  1720. index_min = index_sub;
  1721. }
  1722. }
  1723. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  1724. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  1725. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  1726. matroska->done = 0;
  1727. av_update_cur_dts(s, st, st->index_entries[index].timestamp);
  1728. return 0;
  1729. }
  1730. static int matroska_read_close(AVFormatContext *s)
  1731. {
  1732. MatroskaDemuxContext *matroska = s->priv_data;
  1733. MatroskaTrack *tracks = matroska->tracks.elem;
  1734. int n;
  1735. matroska_clear_queue(matroska);
  1736. for (n=0; n < matroska->tracks.nb_elem; n++)
  1737. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  1738. av_free(tracks[n].audio.buf);
  1739. ebml_free(matroska_segment, matroska);
  1740. return 0;
  1741. }
  1742. AVInputFormat ff_matroska_demuxer = {
  1743. "matroska,webm",
  1744. NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
  1745. sizeof(MatroskaDemuxContext),
  1746. matroska_probe,
  1747. matroska_read_header,
  1748. matroska_read_packet,
  1749. matroska_read_close,
  1750. matroska_read_seek,
  1751. };