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.

2019 lines
73KB

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