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.

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