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.

1674 lines
58KB

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