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.

1875 lines
67KB

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