matroskadec.c 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471
  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. * @author Ronald Bultje <rbultje@ronald.bitfreak.net>
  25. * @author with a little help from Moritz Bunkus <moritz@bunkus.org>
  26. * @author totally reworked by Aurelien Jacobs <aurel@gnuage.org>
  27. * @see 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/bytestream.h"
  39. #include "libavcodec/mpeg4audio.h"
  40. #include "libavutil/intfloat.h"
  41. #include "libavutil/intreadwrite.h"
  42. #include "libavutil/avstring.h"
  43. #include "libavutil/lzo.h"
  44. #include "libavutil/dict.h"
  45. #if CONFIG_ZLIB
  46. #include <zlib.h>
  47. #endif
  48. #if CONFIG_BZLIB
  49. #include <bzlib.h>
  50. #endif
  51. typedef enum {
  52. EBML_NONE,
  53. EBML_UINT,
  54. EBML_FLOAT,
  55. EBML_STR,
  56. EBML_UTF8,
  57. EBML_BIN,
  58. EBML_NEST,
  59. EBML_PASS,
  60. EBML_STOP,
  61. EBML_TYPE_COUNT
  62. } EbmlType;
  63. typedef const struct EbmlSyntax {
  64. uint32_t id;
  65. EbmlType type;
  66. int list_elem_size;
  67. int data_offset;
  68. union {
  69. uint64_t u;
  70. double f;
  71. const char *s;
  72. const struct EbmlSyntax *n;
  73. } def;
  74. } EbmlSyntax;
  75. typedef struct {
  76. int nb_elem;
  77. void *elem;
  78. } EbmlList;
  79. typedef struct {
  80. int size;
  81. uint8_t *data;
  82. int64_t pos;
  83. } EbmlBin;
  84. typedef struct {
  85. uint64_t version;
  86. uint64_t max_size;
  87. uint64_t id_length;
  88. char *doctype;
  89. uint64_t doctype_version;
  90. } Ebml;
  91. typedef struct {
  92. uint64_t algo;
  93. EbmlBin settings;
  94. } MatroskaTrackCompression;
  95. typedef struct {
  96. uint64_t scope;
  97. uint64_t type;
  98. MatroskaTrackCompression compression;
  99. } MatroskaTrackEncoding;
  100. typedef struct {
  101. double frame_rate;
  102. uint64_t display_width;
  103. uint64_t display_height;
  104. uint64_t pixel_width;
  105. uint64_t pixel_height;
  106. EbmlBin color_space;
  107. uint64_t stereo_mode;
  108. } MatroskaTrackVideo;
  109. typedef struct {
  110. double samplerate;
  111. double out_samplerate;
  112. uint64_t bitdepth;
  113. uint64_t channels;
  114. /* real audio header (extracted from extradata) */
  115. int coded_framesize;
  116. int sub_packet_h;
  117. int frame_size;
  118. int sub_packet_size;
  119. int sub_packet_cnt;
  120. int pkt_cnt;
  121. uint64_t buf_timecode;
  122. uint8_t *buf;
  123. } MatroskaTrackAudio;
  124. typedef struct {
  125. uint64_t uid;
  126. uint64_t type;
  127. } MatroskaTrackPlane;
  128. typedef struct {
  129. EbmlList combine_planes;
  130. } MatroskaTrackOperation;
  131. typedef struct {
  132. uint64_t num;
  133. uint64_t uid;
  134. uint64_t type;
  135. char *name;
  136. char *codec_id;
  137. EbmlBin codec_priv;
  138. char *language;
  139. double time_scale;
  140. uint64_t default_duration;
  141. uint64_t flag_default;
  142. uint64_t flag_forced;
  143. MatroskaTrackVideo video;
  144. MatroskaTrackAudio audio;
  145. MatroskaTrackOperation operation;
  146. EbmlList encodings;
  147. AVStream *stream;
  148. int64_t end_timecode;
  149. int ms_compat;
  150. } MatroskaTrack;
  151. typedef struct {
  152. uint64_t uid;
  153. char *filename;
  154. char *mime;
  155. EbmlBin bin;
  156. AVStream *stream;
  157. } MatroskaAttachement;
  158. typedef struct {
  159. uint64_t start;
  160. uint64_t end;
  161. uint64_t uid;
  162. char *title;
  163. AVChapter *chapter;
  164. } MatroskaChapter;
  165. typedef struct {
  166. uint64_t track;
  167. uint64_t pos;
  168. } MatroskaIndexPos;
  169. typedef struct {
  170. uint64_t time;
  171. EbmlList pos;
  172. } MatroskaIndex;
  173. typedef struct {
  174. char *name;
  175. char *string;
  176. char *lang;
  177. uint64_t def;
  178. EbmlList sub;
  179. } MatroskaTag;
  180. typedef struct {
  181. char *type;
  182. uint64_t typevalue;
  183. uint64_t trackuid;
  184. uint64_t chapteruid;
  185. uint64_t attachuid;
  186. } MatroskaTagTarget;
  187. typedef struct {
  188. MatroskaTagTarget target;
  189. EbmlList tag;
  190. } MatroskaTags;
  191. typedef struct {
  192. uint64_t id;
  193. uint64_t pos;
  194. } MatroskaSeekhead;
  195. typedef struct {
  196. uint64_t start;
  197. uint64_t length;
  198. } MatroskaLevel;
  199. typedef struct {
  200. uint64_t timecode;
  201. EbmlList blocks;
  202. } MatroskaCluster;
  203. typedef struct {
  204. AVFormatContext *ctx;
  205. /* EBML stuff */
  206. int num_levels;
  207. MatroskaLevel levels[EBML_MAX_DEPTH];
  208. int level_up;
  209. uint32_t current_id;
  210. uint64_t time_scale;
  211. double duration;
  212. char *title;
  213. EbmlBin date_utc;
  214. EbmlList tracks;
  215. EbmlList attachments;
  216. EbmlList chapters;
  217. EbmlList index;
  218. EbmlList tags;
  219. EbmlList seekhead;
  220. /* byte position of the segment inside the stream */
  221. int64_t segment_start;
  222. /* the packet queue */
  223. AVPacket **packets;
  224. int num_packets;
  225. AVPacket *prev_pkt;
  226. int done;
  227. /* What to skip before effectively reading a packet. */
  228. int skip_to_keyframe;
  229. uint64_t skip_to_timecode;
  230. /* File has a CUES element, but we defer parsing until it is needed. */
  231. int cues_parsing_deferred;
  232. int current_cluster_num_blocks;
  233. int64_t current_cluster_pos;
  234. MatroskaCluster current_cluster;
  235. /* File has SSA subtitles which prevent incremental cluster parsing. */
  236. int contains_ssa;
  237. } MatroskaDemuxContext;
  238. typedef struct {
  239. uint64_t duration;
  240. int64_t reference;
  241. uint64_t non_simple;
  242. EbmlBin bin;
  243. } MatroskaBlock;
  244. static EbmlSyntax ebml_header[] = {
  245. { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
  246. { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
  247. { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
  248. { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
  249. { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
  250. { EBML_ID_EBMLVERSION, EBML_NONE },
  251. { EBML_ID_DOCTYPEVERSION, EBML_NONE },
  252. { 0 }
  253. };
  254. static EbmlSyntax ebml_syntax[] = {
  255. { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
  256. { 0 }
  257. };
  258. static EbmlSyntax matroska_info[] = {
  259. { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
  260. { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
  261. { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
  262. { MATROSKA_ID_WRITINGAPP, EBML_NONE },
  263. { MATROSKA_ID_MUXINGAPP, EBML_NONE },
  264. { MATROSKA_ID_DATEUTC, EBML_BIN, 0, offsetof(MatroskaDemuxContext,date_utc) },
  265. { MATROSKA_ID_SEGMENTUID, EBML_NONE },
  266. { 0 }
  267. };
  268. static EbmlSyntax matroska_track_video[] = {
  269. { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
  270. { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
  271. { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
  272. { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
  273. { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
  274. { MATROSKA_ID_VIDEOCOLORSPACE, EBML_BIN, 0, offsetof(MatroskaTrackVideo,color_space) },
  275. { MATROSKA_ID_VIDEOSTEREOMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,stereo_mode) },
  276. { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
  277. { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
  278. { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
  279. { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
  280. { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
  281. { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
  282. { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
  283. { 0 }
  284. };
  285. static EbmlSyntax matroska_track_audio[] = {
  286. { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
  287. { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
  288. { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
  289. { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
  290. { 0 }
  291. };
  292. static EbmlSyntax matroska_track_encoding_compression[] = {
  293. { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
  294. { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
  295. { 0 }
  296. };
  297. static EbmlSyntax matroska_track_encoding[] = {
  298. { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
  299. { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
  300. { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
  301. { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
  302. { 0 }
  303. };
  304. static EbmlSyntax matroska_track_encodings[] = {
  305. { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
  306. { 0 }
  307. };
  308. static EbmlSyntax matroska_track_plane[] = {
  309. { MATROSKA_ID_TRACKPLANEUID, EBML_UINT, 0, offsetof(MatroskaTrackPlane,uid) },
  310. { MATROSKA_ID_TRACKPLANETYPE, EBML_UINT, 0, offsetof(MatroskaTrackPlane,type) },
  311. { 0 }
  312. };
  313. static EbmlSyntax matroska_track_combine_planes[] = {
  314. { MATROSKA_ID_TRACKPLANE, EBML_NEST, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n=matroska_track_plane} },
  315. { 0 }
  316. };
  317. static EbmlSyntax matroska_track_operation[] = {
  318. { MATROSKA_ID_TRACKCOMBINEPLANES, EBML_NEST, 0, 0, {.n=matroska_track_combine_planes} },
  319. { 0 }
  320. };
  321. static EbmlSyntax matroska_track[] = {
  322. { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
  323. { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
  324. { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
  325. { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
  326. { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
  327. { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
  328. { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
  329. { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
  330. { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
  331. { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
  332. { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
  333. { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
  334. { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
  335. { MATROSKA_ID_TRACKOPERATION, EBML_NEST, 0, offsetof(MatroskaTrack,operation), {.n=matroska_track_operation} },
  336. { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
  337. { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
  338. { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
  339. { MATROSKA_ID_CODECNAME, EBML_NONE },
  340. { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
  341. { MATROSKA_ID_CODECINFOURL, EBML_NONE },
  342. { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
  343. { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
  344. { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
  345. { MATROSKA_ID_TRACKMAXBLKADDID, EBML_NONE },
  346. { 0 }
  347. };
  348. static EbmlSyntax matroska_tracks[] = {
  349. { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
  350. { 0 }
  351. };
  352. static EbmlSyntax matroska_attachment[] = {
  353. { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
  354. { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
  355. { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
  356. { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
  357. { MATROSKA_ID_FILEDESC, EBML_NONE },
  358. { 0 }
  359. };
  360. static EbmlSyntax matroska_attachments[] = {
  361. { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
  362. { 0 }
  363. };
  364. static EbmlSyntax matroska_chapter_display[] = {
  365. { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
  366. { MATROSKA_ID_CHAPLANG, EBML_NONE },
  367. { 0 }
  368. };
  369. static EbmlSyntax matroska_chapter_entry[] = {
  370. { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
  371. { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
  372. { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
  373. { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
  374. { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
  375. { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
  376. { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
  377. { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
  378. { 0 }
  379. };
  380. static EbmlSyntax matroska_chapter[] = {
  381. { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
  382. { MATROSKA_ID_EDITIONUID, EBML_NONE },
  383. { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
  384. { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
  385. { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
  386. { 0 }
  387. };
  388. static EbmlSyntax matroska_chapters[] = {
  389. { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
  390. { 0 }
  391. };
  392. static EbmlSyntax matroska_index_pos[] = {
  393. { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
  394. { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
  395. { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
  396. { 0 }
  397. };
  398. static EbmlSyntax matroska_index_entry[] = {
  399. { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
  400. { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
  401. { 0 }
  402. };
  403. static EbmlSyntax matroska_index[] = {
  404. { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
  405. { 0 }
  406. };
  407. static EbmlSyntax matroska_simpletag[] = {
  408. { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
  409. { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
  410. { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
  411. { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
  412. { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
  413. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
  414. { 0 }
  415. };
  416. static EbmlSyntax matroska_tagtargets[] = {
  417. { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget,type) },
  418. { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
  419. { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
  420. { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
  421. { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
  422. { 0 }
  423. };
  424. static EbmlSyntax matroska_tag[] = {
  425. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
  426. { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
  427. { 0 }
  428. };
  429. static EbmlSyntax matroska_tags[] = {
  430. { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
  431. { 0 }
  432. };
  433. static EbmlSyntax matroska_seekhead_entry[] = {
  434. { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
  435. { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
  436. { 0 }
  437. };
  438. static EbmlSyntax matroska_seekhead[] = {
  439. { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
  440. { 0 }
  441. };
  442. static EbmlSyntax matroska_segment[] = {
  443. { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
  444. { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
  445. { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
  446. { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
  447. { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
  448. { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
  449. { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
  450. { MATROSKA_ID_CLUSTER, EBML_STOP },
  451. { 0 }
  452. };
  453. static EbmlSyntax matroska_segments[] = {
  454. { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
  455. { 0 }
  456. };
  457. static EbmlSyntax matroska_blockgroup[] = {
  458. { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
  459. { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
  460. { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration) },
  461. { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
  462. { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
  463. { 0 }
  464. };
  465. static EbmlSyntax matroska_cluster[] = {
  466. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  467. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  468. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  469. { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
  470. { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
  471. { 0 }
  472. };
  473. static EbmlSyntax matroska_clusters[] = {
  474. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
  475. { MATROSKA_ID_INFO, EBML_NONE },
  476. { MATROSKA_ID_CUES, EBML_NONE },
  477. { MATROSKA_ID_TAGS, EBML_NONE },
  478. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  479. { 0 }
  480. };
  481. static EbmlSyntax matroska_cluster_incremental_parsing[] = {
  482. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  483. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  484. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  485. { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
  486. { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
  487. { MATROSKA_ID_INFO, EBML_NONE },
  488. { MATROSKA_ID_CUES, EBML_NONE },
  489. { MATROSKA_ID_TAGS, EBML_NONE },
  490. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  491. { MATROSKA_ID_CLUSTER, EBML_STOP },
  492. { 0 }
  493. };
  494. static EbmlSyntax matroska_cluster_incremental[] = {
  495. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  496. { MATROSKA_ID_BLOCKGROUP, EBML_STOP },
  497. { MATROSKA_ID_SIMPLEBLOCK, EBML_STOP },
  498. { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
  499. { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
  500. { 0 }
  501. };
  502. static EbmlSyntax matroska_clusters_incremental[] = {
  503. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster_incremental} },
  504. { MATROSKA_ID_INFO, EBML_NONE },
  505. { MATROSKA_ID_CUES, EBML_NONE },
  506. { MATROSKA_ID_TAGS, EBML_NONE },
  507. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  508. { 0 }
  509. };
  510. static const char *const matroska_doctypes[] = { "matroska", "webm" };
  511. static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
  512. {
  513. AVIOContext *pb = matroska->ctx->pb;
  514. uint32_t id;
  515. matroska->current_id = 0;
  516. matroska->num_levels = 0;
  517. // seek to next position to resync from
  518. if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0 || avio_tell(pb) <= last_pos)
  519. goto eof;
  520. id = avio_rb32(pb);
  521. // try to find a toplevel element
  522. while (!url_feof(pb)) {
  523. if (id == MATROSKA_ID_INFO || id == MATROSKA_ID_TRACKS ||
  524. id == MATROSKA_ID_CUES || id == MATROSKA_ID_TAGS ||
  525. id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
  526. id == MATROSKA_ID_CLUSTER || id == MATROSKA_ID_CHAPTERS)
  527. {
  528. matroska->current_id = id;
  529. return 0;
  530. }
  531. id = (id << 8) | avio_r8(pb);
  532. }
  533. eof:
  534. matroska->done = 1;
  535. return AVERROR_EOF;
  536. }
  537. /*
  538. * Return: Whether we reached the end of a level in the hierarchy or not.
  539. */
  540. static int ebml_level_end(MatroskaDemuxContext *matroska)
  541. {
  542. AVIOContext *pb = matroska->ctx->pb;
  543. int64_t pos = avio_tell(pb);
  544. if (matroska->num_levels > 0) {
  545. MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
  546. if (pos - level->start >= level->length || matroska->current_id) {
  547. matroska->num_levels--;
  548. return 1;
  549. }
  550. }
  551. return 0;
  552. }
  553. /*
  554. * Read: an "EBML number", which is defined as a variable-length
  555. * array of bytes. The first byte indicates the length by giving a
  556. * number of 0-bits followed by a one. The position of the first
  557. * "one" bit inside the first byte indicates the length of this
  558. * number.
  559. * Returns: number of bytes read, < 0 on error
  560. */
  561. static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
  562. int max_size, uint64_t *number)
  563. {
  564. int read = 1, n = 1;
  565. uint64_t total = 0;
  566. /* The first byte tells us the length in bytes - avio_r8() can normally
  567. * return 0, but since that's not a valid first ebmlID byte, we can
  568. * use it safely here to catch EOS. */
  569. if (!(total = avio_r8(pb))) {
  570. /* we might encounter EOS here */
  571. if (!url_feof(pb)) {
  572. int64_t pos = avio_tell(pb);
  573. av_log(matroska->ctx, AV_LOG_ERROR,
  574. "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
  575. pos, pos);
  576. return pb->error ? pb->error : AVERROR(EIO);
  577. }
  578. return AVERROR_EOF;
  579. }
  580. /* get the length of the EBML number */
  581. read = 8 - ff_log2_tab[total];
  582. if (read > max_size) {
  583. int64_t pos = avio_tell(pb) - 1;
  584. av_log(matroska->ctx, AV_LOG_ERROR,
  585. "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
  586. (uint8_t) total, pos, pos);
  587. return AVERROR_INVALIDDATA;
  588. }
  589. /* read out length */
  590. total ^= 1 << ff_log2_tab[total];
  591. while (n++ < read)
  592. total = (total << 8) | avio_r8(pb);
  593. *number = total;
  594. return read;
  595. }
  596. /**
  597. * Read a EBML length value.
  598. * This needs special handling for the "unknown length" case which has multiple
  599. * encodings.
  600. */
  601. static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
  602. uint64_t *number)
  603. {
  604. int res = ebml_read_num(matroska, pb, 8, number);
  605. if (res > 0 && *number + 1 == 1ULL << (7 * res))
  606. *number = 0xffffffffffffffULL;
  607. return res;
  608. }
  609. /*
  610. * Read the next element as an unsigned int.
  611. * 0 is success, < 0 is failure.
  612. */
  613. static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
  614. {
  615. int n = 0;
  616. if (size > 8)
  617. return AVERROR_INVALIDDATA;
  618. /* big-endian ordering; build up number */
  619. *num = 0;
  620. while (n++ < size)
  621. *num = (*num << 8) | avio_r8(pb);
  622. return 0;
  623. }
  624. /*
  625. * Read the next element as a float.
  626. * 0 is success, < 0 is failure.
  627. */
  628. static int ebml_read_float(AVIOContext *pb, int size, double *num)
  629. {
  630. if (size == 0) {
  631. *num = 0;
  632. } else if (size == 4) {
  633. *num = av_int2float(avio_rb32(pb));
  634. } else if (size == 8){
  635. *num = av_int2double(avio_rb64(pb));
  636. } else
  637. return AVERROR_INVALIDDATA;
  638. return 0;
  639. }
  640. /*
  641. * Read the next element as an ASCII string.
  642. * 0 is success, < 0 is failure.
  643. */
  644. static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
  645. {
  646. char *res;
  647. /* EBML strings are usually not 0-terminated, so we allocate one
  648. * byte more, read the string and NULL-terminate it ourselves. */
  649. if (!(res = av_malloc(size + 1)))
  650. return AVERROR(ENOMEM);
  651. if (avio_read(pb, (uint8_t *) res, size) != size) {
  652. av_free(res);
  653. return AVERROR(EIO);
  654. }
  655. (res)[size] = '\0';
  656. av_free(*str);
  657. *str = res;
  658. return 0;
  659. }
  660. /*
  661. * Read the next element as binary data.
  662. * 0 is success, < 0 is failure.
  663. */
  664. static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
  665. {
  666. av_free(bin->data);
  667. if (!(bin->data = av_malloc(length)))
  668. return AVERROR(ENOMEM);
  669. bin->size = length;
  670. bin->pos = avio_tell(pb);
  671. if (avio_read(pb, bin->data, length) != length) {
  672. av_freep(&bin->data);
  673. return AVERROR(EIO);
  674. }
  675. return 0;
  676. }
  677. /*
  678. * Read the next element, but only the header. The contents
  679. * are supposed to be sub-elements which can be read separately.
  680. * 0 is success, < 0 is failure.
  681. */
  682. static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
  683. {
  684. AVIOContext *pb = matroska->ctx->pb;
  685. MatroskaLevel *level;
  686. if (matroska->num_levels >= EBML_MAX_DEPTH) {
  687. av_log(matroska->ctx, AV_LOG_ERROR,
  688. "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  689. return AVERROR(ENOSYS);
  690. }
  691. level = &matroska->levels[matroska->num_levels++];
  692. level->start = avio_tell(pb);
  693. level->length = length;
  694. return 0;
  695. }
  696. /*
  697. * Read signed/unsigned "EBML" numbers.
  698. * Return: number of bytes processed, < 0 on error
  699. */
  700. static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
  701. uint8_t *data, uint32_t size, uint64_t *num)
  702. {
  703. AVIOContext pb;
  704. ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
  705. return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
  706. }
  707. /*
  708. * Same as above, but signed.
  709. */
  710. static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
  711. uint8_t *data, uint32_t size, int64_t *num)
  712. {
  713. uint64_t unum;
  714. int res;
  715. /* read as unsigned number first */
  716. if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
  717. return res;
  718. /* make signed (weird way) */
  719. *num = unum - ((1LL << (7*res - 1)) - 1);
  720. return res;
  721. }
  722. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  723. EbmlSyntax *syntax, void *data);
  724. static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  725. uint32_t id, void *data)
  726. {
  727. int i;
  728. for (i=0; syntax[i].id; i++)
  729. if (id == syntax[i].id)
  730. break;
  731. if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
  732. matroska->num_levels > 0 &&
  733. matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
  734. return 0; // we reached the end of an unknown size cluster
  735. if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
  736. av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
  737. if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
  738. return AVERROR_INVALIDDATA;
  739. }
  740. return ebml_parse_elem(matroska, &syntax[i], data);
  741. }
  742. static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  743. void *data)
  744. {
  745. if (!matroska->current_id) {
  746. uint64_t id;
  747. int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
  748. if (res < 0)
  749. return res;
  750. matroska->current_id = id | 1 << 7*res;
  751. }
  752. return ebml_parse_id(matroska, syntax, matroska->current_id, data);
  753. }
  754. static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  755. void *data)
  756. {
  757. int i, res = 0;
  758. for (i=0; syntax[i].id; i++)
  759. switch (syntax[i].type) {
  760. case EBML_UINT:
  761. *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
  762. break;
  763. case EBML_FLOAT:
  764. *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
  765. break;
  766. case EBML_STR:
  767. case EBML_UTF8:
  768. *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
  769. break;
  770. }
  771. while (!res && !ebml_level_end(matroska))
  772. res = ebml_parse(matroska, syntax, data);
  773. return res;
  774. }
  775. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  776. EbmlSyntax *syntax, void *data)
  777. {
  778. static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
  779. [EBML_UINT] = 8,
  780. [EBML_FLOAT] = 8,
  781. // max. 16 MB for strings
  782. [EBML_STR] = 0x1000000,
  783. [EBML_UTF8] = 0x1000000,
  784. // max. 256 MB for binary data
  785. [EBML_BIN] = 0x10000000,
  786. // no limits for anything else
  787. };
  788. AVIOContext *pb = matroska->ctx->pb;
  789. uint32_t id = syntax->id;
  790. uint64_t length;
  791. int res;
  792. void *newelem;
  793. data = (char *)data + syntax->data_offset;
  794. if (syntax->list_elem_size) {
  795. EbmlList *list = data;
  796. newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
  797. if (!newelem)
  798. return AVERROR(ENOMEM);
  799. list->elem = newelem;
  800. data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
  801. memset(data, 0, syntax->list_elem_size);
  802. list->nb_elem++;
  803. }
  804. if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
  805. matroska->current_id = 0;
  806. if ((res = ebml_read_length(matroska, pb, &length)) < 0)
  807. return res;
  808. if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
  809. av_log(matroska->ctx, AV_LOG_ERROR,
  810. "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
  811. length, max_lengths[syntax->type], syntax->type);
  812. return AVERROR_INVALIDDATA;
  813. }
  814. }
  815. switch (syntax->type) {
  816. case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
  817. case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
  818. case EBML_STR:
  819. case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
  820. case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
  821. case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
  822. return res;
  823. if (id == MATROSKA_ID_SEGMENT)
  824. matroska->segment_start = avio_tell(matroska->ctx->pb);
  825. return ebml_parse_nest(matroska, syntax->def.n, data);
  826. case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
  827. case EBML_STOP: return 1;
  828. default:
  829. if(ffio_limit(pb, length) != length)
  830. return AVERROR(EIO);
  831. return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
  832. }
  833. if (res == AVERROR_INVALIDDATA)
  834. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  835. else if (res == AVERROR(EIO))
  836. av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  837. return res;
  838. }
  839. static void ebml_free(EbmlSyntax *syntax, void *data)
  840. {
  841. int i, j;
  842. for (i=0; syntax[i].id; i++) {
  843. void *data_off = (char *)data + syntax[i].data_offset;
  844. switch (syntax[i].type) {
  845. case EBML_STR:
  846. case EBML_UTF8: av_freep(data_off); break;
  847. case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
  848. case EBML_NEST:
  849. if (syntax[i].list_elem_size) {
  850. EbmlList *list = data_off;
  851. char *ptr = list->elem;
  852. for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
  853. ebml_free(syntax[i].def.n, ptr);
  854. av_free(list->elem);
  855. } else
  856. ebml_free(syntax[i].def.n, data_off);
  857. default: break;
  858. }
  859. }
  860. }
  861. /*
  862. * Autodetecting...
  863. */
  864. static int matroska_probe(AVProbeData *p)
  865. {
  866. uint64_t total = 0;
  867. int len_mask = 0x80, size = 1, n = 1, i;
  868. /* EBML header? */
  869. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  870. return 0;
  871. /* length of header */
  872. total = p->buf[4];
  873. while (size <= 8 && !(total & len_mask)) {
  874. size++;
  875. len_mask >>= 1;
  876. }
  877. if (size > 8)
  878. return 0;
  879. total &= (len_mask - 1);
  880. while (n < size)
  881. total = (total << 8) | p->buf[4 + n++];
  882. /* Does the probe data contain the whole header? */
  883. if (p->buf_size < 4 + size + total)
  884. return 0;
  885. /* The header should contain a known document type. For now,
  886. * we don't parse the whole header but simply check for the
  887. * availability of that array of characters inside the header.
  888. * Not fully fool-proof, but good enough. */
  889. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
  890. int probelen = strlen(matroska_doctypes[i]);
  891. if (total < probelen)
  892. continue;
  893. for (n = 4+size; n <= 4+size+total-probelen; n++)
  894. if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
  895. return AVPROBE_SCORE_MAX;
  896. }
  897. // probably valid EBML header but no recognized doctype
  898. return AVPROBE_SCORE_MAX/2;
  899. }
  900. static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
  901. int num)
  902. {
  903. MatroskaTrack *tracks = matroska->tracks.elem;
  904. int i;
  905. for (i=0; i < matroska->tracks.nb_elem; i++)
  906. if (tracks[i].num == num)
  907. return &tracks[i];
  908. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
  909. return NULL;
  910. }
  911. static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
  912. MatroskaTrack *track)
  913. {
  914. MatroskaTrackEncoding *encodings = track->encodings.elem;
  915. uint8_t* data = *buf;
  916. int isize = *buf_size;
  917. uint8_t* pkt_data = NULL;
  918. uint8_t av_unused *newpktdata;
  919. int pkt_size = isize;
  920. int result = 0;
  921. int olen;
  922. if (pkt_size >= 10000000U)
  923. return AVERROR_INVALIDDATA;
  924. switch (encodings[0].compression.algo) {
  925. case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP: {
  926. int header_size = encodings[0].compression.settings.size;
  927. uint8_t *header = encodings[0].compression.settings.data;
  928. if (header_size && !header) {
  929. av_log(0, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
  930. return -1;
  931. }
  932. if (!header_size)
  933. return 0;
  934. pkt_size = isize + header_size;
  935. pkt_data = av_malloc(pkt_size);
  936. if (!pkt_data)
  937. return AVERROR(ENOMEM);
  938. memcpy(pkt_data, header, header_size);
  939. memcpy(pkt_data + header_size, data, isize);
  940. break;
  941. }
  942. case MATROSKA_TRACK_ENCODING_COMP_LZO:
  943. do {
  944. olen = pkt_size *= 3;
  945. newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
  946. if (!newpktdata) {
  947. result = AVERROR(ENOMEM);
  948. goto failed;
  949. }
  950. pkt_data = newpktdata;
  951. result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
  952. } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
  953. if (result) {
  954. result = AVERROR_INVALIDDATA;
  955. goto failed;
  956. }
  957. pkt_size -= olen;
  958. break;
  959. #if CONFIG_ZLIB
  960. case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
  961. z_stream zstream = {0};
  962. if (inflateInit(&zstream) != Z_OK)
  963. return -1;
  964. zstream.next_in = data;
  965. zstream.avail_in = isize;
  966. do {
  967. pkt_size *= 3;
  968. newpktdata = av_realloc(pkt_data, pkt_size);
  969. if (!newpktdata) {
  970. inflateEnd(&zstream);
  971. goto failed;
  972. }
  973. pkt_data = newpktdata;
  974. zstream.avail_out = pkt_size - zstream.total_out;
  975. zstream.next_out = pkt_data + zstream.total_out;
  976. if (pkt_data) {
  977. result = inflate(&zstream, Z_NO_FLUSH);
  978. } else
  979. result = Z_MEM_ERROR;
  980. } while (result==Z_OK && pkt_size<10000000);
  981. pkt_size = zstream.total_out;
  982. inflateEnd(&zstream);
  983. if (result != Z_STREAM_END) {
  984. if (result == Z_MEM_ERROR)
  985. result = AVERROR(ENOMEM);
  986. else
  987. result = AVERROR_INVALIDDATA;
  988. goto failed;
  989. }
  990. break;
  991. }
  992. #endif
  993. #if CONFIG_BZLIB
  994. case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
  995. bz_stream bzstream = {0};
  996. if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
  997. return -1;
  998. bzstream.next_in = data;
  999. bzstream.avail_in = isize;
  1000. do {
  1001. pkt_size *= 3;
  1002. newpktdata = av_realloc(pkt_data, pkt_size);
  1003. if (!newpktdata) {
  1004. BZ2_bzDecompressEnd(&bzstream);
  1005. goto failed;
  1006. }
  1007. pkt_data = newpktdata;
  1008. bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
  1009. bzstream.next_out = pkt_data + bzstream.total_out_lo32;
  1010. if (pkt_data) {
  1011. result = BZ2_bzDecompress(&bzstream);
  1012. } else
  1013. result = BZ_MEM_ERROR;
  1014. } while (result==BZ_OK && pkt_size<10000000);
  1015. pkt_size = bzstream.total_out_lo32;
  1016. BZ2_bzDecompressEnd(&bzstream);
  1017. if (result != BZ_STREAM_END) {
  1018. if (result == BZ_MEM_ERROR)
  1019. result = AVERROR(ENOMEM);
  1020. else
  1021. result = AVERROR_INVALIDDATA;
  1022. goto failed;
  1023. }
  1024. break;
  1025. }
  1026. #endif
  1027. default:
  1028. return AVERROR_INVALIDDATA;
  1029. }
  1030. *buf = pkt_data;
  1031. *buf_size = pkt_size;
  1032. return 0;
  1033. failed:
  1034. av_free(pkt_data);
  1035. return result;
  1036. }
  1037. static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
  1038. AVPacket *pkt, uint64_t display_duration)
  1039. {
  1040. char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
  1041. for (; *ptr!=',' && ptr<end-1; ptr++);
  1042. if (*ptr == ',')
  1043. ptr++;
  1044. layer = ptr;
  1045. for (; *ptr!=',' && ptr<end-1; ptr++);
  1046. if (*ptr == ',') {
  1047. int64_t end_pts = pkt->pts + display_duration;
  1048. int sc = matroska->time_scale * pkt->pts / 10000000;
  1049. int ec = matroska->time_scale * end_pts / 10000000;
  1050. int sh, sm, ss, eh, em, es, len;
  1051. sh = sc/360000; sc -= 360000*sh;
  1052. sm = sc/ 6000; sc -= 6000*sm;
  1053. ss = sc/ 100; sc -= 100*ss;
  1054. eh = ec/360000; ec -= 360000*eh;
  1055. em = ec/ 6000; ec -= 6000*em;
  1056. es = ec/ 100; ec -= 100*es;
  1057. *ptr++ = '\0';
  1058. len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
  1059. if (!(line = av_malloc(len)))
  1060. return;
  1061. snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
  1062. layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
  1063. av_free(pkt->data);
  1064. pkt->data = line;
  1065. pkt->size = strlen(line);
  1066. }
  1067. }
  1068. static int matroska_merge_packets(AVPacket *out, AVPacket *in)
  1069. {
  1070. int ret = av_grow_packet(out, in->size);
  1071. if (ret < 0)
  1072. return ret;
  1073. memcpy(out->data + out->size - in->size, in->data, in->size);
  1074. av_destruct_packet(in);
  1075. av_free(in);
  1076. return 0;
  1077. }
  1078. static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
  1079. AVDictionary **metadata, char *prefix)
  1080. {
  1081. MatroskaTag *tags = list->elem;
  1082. char key[1024];
  1083. int i;
  1084. for (i=0; i < list->nb_elem; i++) {
  1085. const char *lang= (tags[i].lang && strcmp(tags[i].lang, "und")) ? tags[i].lang : NULL;
  1086. if (!tags[i].name) {
  1087. av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
  1088. continue;
  1089. }
  1090. if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  1091. else av_strlcpy(key, tags[i].name, sizeof(key));
  1092. if (tags[i].def || !lang) {
  1093. av_dict_set(metadata, key, tags[i].string, 0);
  1094. if (tags[i].sub.nb_elem)
  1095. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1096. }
  1097. if (lang) {
  1098. av_strlcat(key, "-", sizeof(key));
  1099. av_strlcat(key, lang, sizeof(key));
  1100. av_dict_set(metadata, key, tags[i].string, 0);
  1101. if (tags[i].sub.nb_elem)
  1102. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1103. }
  1104. }
  1105. ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
  1106. }
  1107. static void matroska_convert_tags(AVFormatContext *s)
  1108. {
  1109. MatroskaDemuxContext *matroska = s->priv_data;
  1110. MatroskaTags *tags = matroska->tags.elem;
  1111. int i, j;
  1112. for (i=0; i < matroska->tags.nb_elem; i++) {
  1113. if (tags[i].target.attachuid) {
  1114. MatroskaAttachement *attachment = matroska->attachments.elem;
  1115. for (j=0; j<matroska->attachments.nb_elem; j++)
  1116. if (attachment[j].uid == tags[i].target.attachuid
  1117. && attachment[j].stream)
  1118. matroska_convert_tag(s, &tags[i].tag,
  1119. &attachment[j].stream->metadata, NULL);
  1120. } else if (tags[i].target.chapteruid) {
  1121. MatroskaChapter *chapter = matroska->chapters.elem;
  1122. for (j=0; j<matroska->chapters.nb_elem; j++)
  1123. if (chapter[j].uid == tags[i].target.chapteruid
  1124. && chapter[j].chapter)
  1125. matroska_convert_tag(s, &tags[i].tag,
  1126. &chapter[j].chapter->metadata, NULL);
  1127. } else if (tags[i].target.trackuid) {
  1128. MatroskaTrack *track = matroska->tracks.elem;
  1129. for (j=0; j<matroska->tracks.nb_elem; j++)
  1130. if (track[j].uid == tags[i].target.trackuid && track[j].stream)
  1131. matroska_convert_tag(s, &tags[i].tag,
  1132. &track[j].stream->metadata, NULL);
  1133. } else {
  1134. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  1135. tags[i].target.type);
  1136. }
  1137. }
  1138. }
  1139. static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
  1140. {
  1141. EbmlList *seekhead_list = &matroska->seekhead;
  1142. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1143. uint32_t level_up = matroska->level_up;
  1144. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1145. uint32_t saved_id = matroska->current_id;
  1146. MatroskaLevel level;
  1147. int64_t offset;
  1148. int ret = 0;
  1149. if (idx >= seekhead_list->nb_elem
  1150. || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
  1151. || seekhead[idx].id == MATROSKA_ID_CLUSTER)
  1152. return 0;
  1153. /* seek */
  1154. offset = seekhead[idx].pos + matroska->segment_start;
  1155. if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
  1156. /* We don't want to lose our seekhead level, so we add
  1157. * a dummy. This is a crude hack. */
  1158. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1159. av_log(matroska->ctx, AV_LOG_INFO,
  1160. "Max EBML element depth (%d) reached, "
  1161. "cannot parse further.\n", EBML_MAX_DEPTH);
  1162. ret = AVERROR_INVALIDDATA;
  1163. } else {
  1164. level.start = 0;
  1165. level.length = (uint64_t)-1;
  1166. matroska->levels[matroska->num_levels] = level;
  1167. matroska->num_levels++;
  1168. matroska->current_id = 0;
  1169. ret = ebml_parse(matroska, matroska_segment, matroska);
  1170. /* remove dummy level */
  1171. while (matroska->num_levels) {
  1172. uint64_t length = matroska->levels[--matroska->num_levels].length;
  1173. if (length == (uint64_t)-1)
  1174. break;
  1175. }
  1176. }
  1177. }
  1178. /* seek back */
  1179. avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
  1180. matroska->level_up = level_up;
  1181. matroska->current_id = saved_id;
  1182. return ret;
  1183. }
  1184. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  1185. {
  1186. EbmlList *seekhead_list = &matroska->seekhead;
  1187. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1188. int i;
  1189. // we should not do any seeking in the streaming case
  1190. if (!matroska->ctx->pb->seekable ||
  1191. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  1192. return;
  1193. for (i = 0; i < seekhead_list->nb_elem; i++) {
  1194. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1195. if (seekhead[i].pos <= before_pos)
  1196. continue;
  1197. // defer cues parsing until we actually need cue data.
  1198. if (seekhead[i].id == MATROSKA_ID_CUES) {
  1199. matroska->cues_parsing_deferred = 1;
  1200. continue;
  1201. }
  1202. if (matroska_parse_seekhead_entry(matroska, i) < 0) {
  1203. // mark index as broken
  1204. matroska->cues_parsing_deferred = -1;
  1205. break;
  1206. }
  1207. }
  1208. }
  1209. static void matroska_add_index_entries(MatroskaDemuxContext *matroska) {
  1210. EbmlList *index_list;
  1211. MatroskaIndex *index;
  1212. int index_scale = 1;
  1213. int i, j;
  1214. index_list = &matroska->index;
  1215. index = index_list->elem;
  1216. if (index_list->nb_elem
  1217. && index[0].time > 1E14/matroska->time_scale) {
  1218. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1219. index_scale = matroska->time_scale;
  1220. }
  1221. for (i = 0; i < index_list->nb_elem; i++) {
  1222. EbmlList *pos_list = &index[i].pos;
  1223. MatroskaIndexPos *pos = pos_list->elem;
  1224. for (j = 0; j < pos_list->nb_elem; j++) {
  1225. MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
  1226. if (track && track->stream)
  1227. av_add_index_entry(track->stream,
  1228. pos[j].pos + matroska->segment_start,
  1229. index[i].time/index_scale, 0, 0,
  1230. AVINDEX_KEYFRAME);
  1231. }
  1232. }
  1233. }
  1234. static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
  1235. EbmlList *seekhead_list = &matroska->seekhead;
  1236. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1237. int i;
  1238. for (i = 0; i < seekhead_list->nb_elem; i++)
  1239. if (seekhead[i].id == MATROSKA_ID_CUES)
  1240. break;
  1241. assert(i <= seekhead_list->nb_elem);
  1242. if (matroska_parse_seekhead_entry(matroska, i) < 0)
  1243. matroska->cues_parsing_deferred = -1;
  1244. matroska_add_index_entries(matroska);
  1245. }
  1246. static int matroska_aac_profile(char *codec_id)
  1247. {
  1248. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  1249. int profile;
  1250. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  1251. if (strstr(codec_id, aac_profiles[profile]))
  1252. break;
  1253. return profile + 1;
  1254. }
  1255. static int matroska_aac_sri(int samplerate)
  1256. {
  1257. int sri;
  1258. for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
  1259. if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
  1260. break;
  1261. return sri;
  1262. }
  1263. static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
  1264. {
  1265. char buffer[32];
  1266. /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
  1267. time_t creation_time = date_utc / 1000000000 + 978307200;
  1268. struct tm *ptm = gmtime(&creation_time);
  1269. if (!ptm) return;
  1270. strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
  1271. av_dict_set(metadata, "creation_time", buffer, 0);
  1272. }
  1273. static int matroska_read_header(AVFormatContext *s)
  1274. {
  1275. MatroskaDemuxContext *matroska = s->priv_data;
  1276. EbmlList *attachements_list = &matroska->attachments;
  1277. MatroskaAttachement *attachements;
  1278. EbmlList *chapters_list = &matroska->chapters;
  1279. MatroskaChapter *chapters;
  1280. MatroskaTrack *tracks;
  1281. uint64_t max_start = 0;
  1282. int64_t pos;
  1283. Ebml ebml = { 0 };
  1284. AVStream *st;
  1285. int i, j, k, res;
  1286. matroska->ctx = s;
  1287. /* First read the EBML header. */
  1288. if (ebml_parse(matroska, ebml_syntax, &ebml)
  1289. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  1290. || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3 || !ebml.doctype) {
  1291. av_log(matroska->ctx, AV_LOG_ERROR,
  1292. "EBML header using unsupported features\n"
  1293. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1294. ebml.version, ebml.doctype, ebml.doctype_version);
  1295. ebml_free(ebml_syntax, &ebml);
  1296. return AVERROR_PATCHWELCOME;
  1297. } else if (ebml.doctype_version == 3) {
  1298. av_log(matroska->ctx, AV_LOG_WARNING,
  1299. "EBML header using unsupported features\n"
  1300. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1301. ebml.version, ebml.doctype, ebml.doctype_version);
  1302. }
  1303. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1304. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1305. break;
  1306. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1307. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1308. if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
  1309. ebml_free(ebml_syntax, &ebml);
  1310. return AVERROR_INVALIDDATA;
  1311. }
  1312. }
  1313. ebml_free(ebml_syntax, &ebml);
  1314. /* The next thing is a segment. */
  1315. pos = avio_tell(matroska->ctx->pb);
  1316. res = ebml_parse(matroska, matroska_segments, matroska);
  1317. // try resyncing until we find a EBML_STOP type element.
  1318. while (res != 1) {
  1319. res = matroska_resync(matroska, pos);
  1320. if (res < 0)
  1321. return res;
  1322. pos = avio_tell(matroska->ctx->pb);
  1323. res = ebml_parse(matroska, matroska_segment, matroska);
  1324. }
  1325. matroska_execute_seekhead(matroska);
  1326. if (!matroska->time_scale)
  1327. matroska->time_scale = 1000000;
  1328. if (matroska->duration)
  1329. matroska->ctx->duration = matroska->duration * matroska->time_scale
  1330. * 1000 / AV_TIME_BASE;
  1331. av_dict_set(&s->metadata, "title", matroska->title, 0);
  1332. if (matroska->date_utc.size == 8)
  1333. matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));
  1334. tracks = matroska->tracks.elem;
  1335. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1336. MatroskaTrack *track = &tracks[i];
  1337. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  1338. EbmlList *encodings_list = &track->encodings;
  1339. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1340. uint8_t *extradata = NULL;
  1341. int extradata_size = 0;
  1342. int extradata_offset = 0;
  1343. uint32_t fourcc = 0;
  1344. AVIOContext b;
  1345. /* Apply some sanity checks. */
  1346. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1347. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1348. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1349. av_log(matroska->ctx, AV_LOG_INFO,
  1350. "Unknown or unsupported track type %"PRIu64"\n",
  1351. track->type);
  1352. continue;
  1353. }
  1354. if (track->codec_id == NULL)
  1355. continue;
  1356. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1357. if (!track->default_duration && track->video.frame_rate > 0)
  1358. track->default_duration = 1000000000/track->video.frame_rate;
  1359. if (!track->video.display_width)
  1360. track->video.display_width = track->video.pixel_width;
  1361. if (!track->video.display_height)
  1362. track->video.display_height = track->video.pixel_height;
  1363. if (track->video.color_space.size == 4)
  1364. fourcc = AV_RL32(track->video.color_space.data);
  1365. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1366. if (!track->audio.out_samplerate)
  1367. track->audio.out_samplerate = track->audio.samplerate;
  1368. }
  1369. if (encodings_list->nb_elem > 1) {
  1370. av_log(matroska->ctx, AV_LOG_ERROR,
  1371. "Multiple combined encodings not supported");
  1372. } else if (encodings_list->nb_elem == 1) {
  1373. if (encodings[0].type ||
  1374. (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
  1375. #if CONFIG_ZLIB
  1376. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1377. #endif
  1378. #if CONFIG_BZLIB
  1379. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1380. #endif
  1381. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
  1382. encodings[0].scope = 0;
  1383. av_log(matroska->ctx, AV_LOG_ERROR,
  1384. "Unsupported encoding type");
  1385. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1386. uint8_t *codec_priv = track->codec_priv.data;
  1387. int ret = matroska_decode_buffer(&track->codec_priv.data,
  1388. &track->codec_priv.size,
  1389. track);
  1390. if (ret < 0) {
  1391. track->codec_priv.data = NULL;
  1392. track->codec_priv.size = 0;
  1393. av_log(matroska->ctx, AV_LOG_ERROR,
  1394. "Failed to decode codec private data\n");
  1395. }
  1396. if (codec_priv != track->codec_priv.data)
  1397. av_free(codec_priv);
  1398. }
  1399. }
  1400. for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
  1401. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1402. strlen(ff_mkv_codec_tags[j].str))){
  1403. codec_id= ff_mkv_codec_tags[j].id;
  1404. break;
  1405. }
  1406. }
  1407. st = track->stream = avformat_new_stream(s, NULL);
  1408. if (st == NULL)
  1409. return AVERROR(ENOMEM);
  1410. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1411. && track->codec_priv.size >= 40
  1412. && track->codec_priv.data != NULL) {
  1413. track->ms_compat = 1;
  1414. fourcc = AV_RL32(track->codec_priv.data + 16);
  1415. codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);
  1416. extradata_offset = 40;
  1417. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1418. && track->codec_priv.size >= 14
  1419. && track->codec_priv.data != NULL) {
  1420. int ret;
  1421. ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
  1422. AVIO_FLAG_READ, NULL, NULL, NULL, NULL);
  1423. ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1424. if (ret < 0)
  1425. return ret;
  1426. codec_id = st->codec->codec_id;
  1427. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1428. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1429. && (track->codec_priv.size >= 86)
  1430. && (track->codec_priv.data != NULL)) {
  1431. fourcc = AV_RL32(track->codec_priv.data + 4);
  1432. codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
  1433. if (ff_codec_get_id(ff_codec_movvideo_tags, AV_RL32(track->codec_priv.data))) {
  1434. fourcc = AV_RL32(track->codec_priv.data);
  1435. codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
  1436. }
  1437. } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size && track->codec_priv.size < INT_MAX-12) {
  1438. /* Only ALAC's magic cookie is stored in Matroska's track headers.
  1439. Create the "atom size", "tag", and "tag version" fields the
  1440. decoder expects manually. */
  1441. extradata_size = 12 + track->codec_priv.size;
  1442. extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  1443. if (extradata == NULL)
  1444. return AVERROR(ENOMEM);
  1445. AV_WB32(extradata, extradata_size);
  1446. memcpy(&extradata[4], "alac", 4);
  1447. AV_WB32(&extradata[8], 0);
  1448. memcpy(&extradata[12], track->codec_priv.data, track->codec_priv.size);
  1449. } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
  1450. switch (track->audio.bitdepth) {
  1451. case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
  1452. case 24: codec_id = AV_CODEC_ID_PCM_S24BE; break;
  1453. case 32: codec_id = AV_CODEC_ID_PCM_S32BE; break;
  1454. }
  1455. } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
  1456. switch (track->audio.bitdepth) {
  1457. case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
  1458. case 24: codec_id = AV_CODEC_ID_PCM_S24LE; break;
  1459. case 32: codec_id = AV_CODEC_ID_PCM_S32LE; break;
  1460. }
  1461. } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1462. codec_id = AV_CODEC_ID_PCM_F64LE;
  1463. } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
  1464. int profile = matroska_aac_profile(track->codec_id);
  1465. int sri = matroska_aac_sri(track->audio.samplerate);
  1466. extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
  1467. if (extradata == NULL)
  1468. return AVERROR(ENOMEM);
  1469. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1470. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1471. if (strstr(track->codec_id, "SBR")) {
  1472. sri = matroska_aac_sri(track->audio.out_samplerate);
  1473. extradata[2] = 0x56;
  1474. extradata[3] = 0xE5;
  1475. extradata[4] = 0x80 | (sri<<3);
  1476. extradata_size = 5;
  1477. } else
  1478. extradata_size = 2;
  1479. } else if (codec_id == AV_CODEC_ID_TTA) {
  1480. extradata_size = 30;
  1481. extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  1482. if (extradata == NULL)
  1483. return AVERROR(ENOMEM);
  1484. ffio_init_context(&b, extradata, extradata_size, 1,
  1485. NULL, NULL, NULL, NULL);
  1486. avio_write(&b, "TTA1", 4);
  1487. avio_wl16(&b, 1);
  1488. avio_wl16(&b, track->audio.channels);
  1489. avio_wl16(&b, track->audio.bitdepth);
  1490. if (track->audio.out_samplerate < 0 || track->audio.out_samplerate > INT_MAX)
  1491. return AVERROR_INVALIDDATA;
  1492. avio_wl32(&b, track->audio.out_samplerate);
  1493. avio_wl32(&b, av_rescale((matroska->duration * matroska->time_scale), track->audio.out_samplerate, AV_TIME_BASE * 1000));
  1494. } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
  1495. codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
  1496. extradata_offset = 26;
  1497. } else if (codec_id == AV_CODEC_ID_RA_144) {
  1498. track->audio.out_samplerate = 8000;
  1499. track->audio.channels = 1;
  1500. } else if ((codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
  1501. codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR)
  1502. && track->codec_priv.data) {
  1503. int flavor;
  1504. ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
  1505. 0, NULL, NULL, NULL, NULL);
  1506. avio_skip(&b, 22);
  1507. flavor = avio_rb16(&b);
  1508. track->audio.coded_framesize = avio_rb32(&b);
  1509. avio_skip(&b, 12);
  1510. track->audio.sub_packet_h = avio_rb16(&b);
  1511. track->audio.frame_size = avio_rb16(&b);
  1512. track->audio.sub_packet_size = avio_rb16(&b);
  1513. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1514. if (codec_id == AV_CODEC_ID_RA_288) {
  1515. st->codec->block_align = track->audio.coded_framesize;
  1516. track->codec_priv.size = 0;
  1517. } else {
  1518. if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
  1519. const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1520. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1521. st->codec->bit_rate = sipr_bit_rate[flavor];
  1522. }
  1523. st->codec->block_align = track->audio.sub_packet_size;
  1524. extradata_offset = 78;
  1525. }
  1526. }
  1527. track->codec_priv.size -= extradata_offset;
  1528. if (codec_id == AV_CODEC_ID_NONE)
  1529. av_log(matroska->ctx, AV_LOG_INFO,
  1530. "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
  1531. if (track->time_scale < 0.01)
  1532. track->time_scale = 1.0;
  1533. avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1534. st->codec->codec_id = codec_id;
  1535. st->start_time = 0;
  1536. if (strcmp(track->language, "und"))
  1537. av_dict_set(&st->metadata, "language", track->language, 0);
  1538. av_dict_set(&st->metadata, "title", track->name, 0);
  1539. if (track->flag_default)
  1540. st->disposition |= AV_DISPOSITION_DEFAULT;
  1541. if (track->flag_forced)
  1542. st->disposition |= AV_DISPOSITION_FORCED;
  1543. if (!st->codec->extradata) {
  1544. if(extradata){
  1545. st->codec->extradata = extradata;
  1546. st->codec->extradata_size = extradata_size;
  1547. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1548. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1549. FF_INPUT_BUFFER_PADDING_SIZE);
  1550. if(st->codec->extradata == NULL)
  1551. return AVERROR(ENOMEM);
  1552. st->codec->extradata_size = track->codec_priv.size;
  1553. memcpy(st->codec->extradata,
  1554. track->codec_priv.data + extradata_offset,
  1555. track->codec_priv.size);
  1556. }
  1557. }
  1558. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1559. MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
  1560. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1561. st->codec->codec_tag = fourcc;
  1562. st->codec->width = track->video.pixel_width;
  1563. st->codec->height = track->video.pixel_height;
  1564. av_reduce(&st->sample_aspect_ratio.num,
  1565. &st->sample_aspect_ratio.den,
  1566. st->codec->height * track->video.display_width,
  1567. st->codec-> width * track->video.display_height,
  1568. 255);
  1569. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1570. if (track->default_duration) {
  1571. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1572. 1000000000, track->default_duration, 30000);
  1573. #if FF_API_R_FRAME_RATE
  1574. if (st->avg_frame_rate.num < st->avg_frame_rate.den * 1000L)
  1575. st->r_frame_rate = st->avg_frame_rate;
  1576. #endif
  1577. }
  1578. /* export stereo mode flag as metadata tag */
  1579. if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)
  1580. av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
  1581. /* if we have virtual track, mark the real tracks */
  1582. for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
  1583. char buf[32];
  1584. if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
  1585. continue;
  1586. snprintf(buf, sizeof(buf), "%s_%d",
  1587. ff_matroska_video_stereo_plane[planes[j].type], i);
  1588. for (k=0; k < matroska->tracks.nb_elem; k++)
  1589. if (planes[j].uid == tracks[k].uid) {
  1590. av_dict_set(&s->streams[k]->metadata,
  1591. "stereo_mode", buf, 0);
  1592. break;
  1593. }
  1594. }
  1595. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1596. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1597. st->codec->sample_rate = track->audio.out_samplerate;
  1598. st->codec->channels = track->audio.channels;
  1599. if (st->codec->codec_id != AV_CODEC_ID_AAC)
  1600. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1601. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1602. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1603. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  1604. matroska->contains_ssa = 1;
  1605. }
  1606. }
  1607. attachements = attachements_list->elem;
  1608. for (j=0; j<attachements_list->nb_elem; j++) {
  1609. if (!(attachements[j].filename && attachements[j].mime &&
  1610. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1611. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1612. } else {
  1613. AVStream *st = avformat_new_stream(s, NULL);
  1614. if (st == NULL)
  1615. break;
  1616. av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
  1617. av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
  1618. st->codec->codec_id = AV_CODEC_ID_NONE;
  1619. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1620. st->codec->extradata = av_malloc(attachements[j].bin.size + FF_INPUT_BUFFER_PADDING_SIZE);
  1621. if(st->codec->extradata == NULL)
  1622. break;
  1623. st->codec->extradata_size = attachements[j].bin.size;
  1624. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1625. for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
  1626. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1627. strlen(ff_mkv_mime_tags[i].str))) {
  1628. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1629. break;
  1630. }
  1631. }
  1632. attachements[j].stream = st;
  1633. }
  1634. }
  1635. chapters = chapters_list->elem;
  1636. for (i=0; i<chapters_list->nb_elem; i++)
  1637. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1638. && (max_start==0 || chapters[i].start > max_start)) {
  1639. chapters[i].chapter =
  1640. avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1641. chapters[i].start, chapters[i].end,
  1642. chapters[i].title);
  1643. av_dict_set(&chapters[i].chapter->metadata,
  1644. "title", chapters[i].title, 0);
  1645. max_start = chapters[i].start;
  1646. }
  1647. matroska_add_index_entries(matroska);
  1648. matroska_convert_tags(s);
  1649. return 0;
  1650. }
  1651. /*
  1652. * Put one packet in an application-supplied AVPacket struct.
  1653. * Returns 0 on success or -1 on failure.
  1654. */
  1655. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1656. AVPacket *pkt)
  1657. {
  1658. if (matroska->num_packets > 0) {
  1659. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1660. av_free(matroska->packets[0]);
  1661. if (matroska->num_packets > 1) {
  1662. void *newpackets;
  1663. memmove(&matroska->packets[0], &matroska->packets[1],
  1664. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1665. newpackets = av_realloc(matroska->packets,
  1666. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1667. if (newpackets)
  1668. matroska->packets = newpackets;
  1669. } else {
  1670. av_freep(&matroska->packets);
  1671. matroska->prev_pkt = NULL;
  1672. }
  1673. matroska->num_packets--;
  1674. return 0;
  1675. }
  1676. return -1;
  1677. }
  1678. /*
  1679. * Free all packets in our internal queue.
  1680. */
  1681. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1682. {
  1683. matroska->prev_pkt = NULL;
  1684. if (matroska->packets) {
  1685. int n;
  1686. for (n = 0; n < matroska->num_packets; n++) {
  1687. av_free_packet(matroska->packets[n]);
  1688. av_free(matroska->packets[n]);
  1689. }
  1690. av_freep(&matroska->packets);
  1691. matroska->num_packets = 0;
  1692. }
  1693. }
  1694. static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
  1695. int* buf_size, int type,
  1696. uint32_t **lace_buf, int *laces)
  1697. {
  1698. int res = 0, n, size = *buf_size;
  1699. uint8_t *data = *buf;
  1700. uint32_t *lace_size;
  1701. if (!type) {
  1702. *laces = 1;
  1703. *lace_buf = av_mallocz(sizeof(int));
  1704. if (!*lace_buf)
  1705. return AVERROR(ENOMEM);
  1706. *lace_buf[0] = size;
  1707. return 0;
  1708. }
  1709. av_assert0(size > 0);
  1710. *laces = *data + 1;
  1711. data += 1;
  1712. size -= 1;
  1713. lace_size = av_mallocz(*laces * sizeof(int));
  1714. if (!lace_size)
  1715. return AVERROR(ENOMEM);
  1716. switch (type) {
  1717. case 0x1: /* Xiph lacing */ {
  1718. uint8_t temp;
  1719. uint32_t total = 0;
  1720. for (n = 0; res == 0 && n < *laces - 1; n++) {
  1721. while (1) {
  1722. if (size == 0) {
  1723. res = AVERROR_EOF;
  1724. break;
  1725. }
  1726. temp = *data;
  1727. lace_size[n] += temp;
  1728. data += 1;
  1729. size -= 1;
  1730. if (temp != 0xff)
  1731. break;
  1732. }
  1733. total += lace_size[n];
  1734. }
  1735. if (size <= total) {
  1736. res = AVERROR_INVALIDDATA;
  1737. break;
  1738. }
  1739. lace_size[n] = size - total;
  1740. break;
  1741. }
  1742. case 0x2: /* fixed-size lacing */
  1743. if (size % (*laces)) {
  1744. res = AVERROR_INVALIDDATA;
  1745. break;
  1746. }
  1747. for (n = 0; n < *laces; n++)
  1748. lace_size[n] = size / *laces;
  1749. break;
  1750. case 0x3: /* EBML lacing */ {
  1751. uint64_t num;
  1752. uint32_t total;
  1753. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1754. if (n < 0) {
  1755. av_log(matroska->ctx, AV_LOG_INFO,
  1756. "EBML block data error\n");
  1757. res = n;
  1758. break;
  1759. }
  1760. data += n;
  1761. size -= n;
  1762. total = lace_size[0] = num;
  1763. for (n = 1; res == 0 && n < *laces - 1; n++) {
  1764. int64_t snum;
  1765. int r;
  1766. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1767. if (r < 0) {
  1768. av_log(matroska->ctx, AV_LOG_INFO,
  1769. "EBML block data error\n");
  1770. res = r;
  1771. break;
  1772. }
  1773. data += r;
  1774. size -= r;
  1775. lace_size[n] = lace_size[n - 1] + snum;
  1776. total += lace_size[n];
  1777. }
  1778. if (size <= total) {
  1779. res = AVERROR_INVALIDDATA;
  1780. break;
  1781. }
  1782. lace_size[*laces - 1] = size - total;
  1783. break;
  1784. }
  1785. }
  1786. *buf = data;
  1787. *lace_buf = lace_size;
  1788. *buf_size = size;
  1789. return res;
  1790. }
  1791. static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
  1792. MatroskaTrack *track,
  1793. AVStream *st,
  1794. uint8_t *data, int size,
  1795. uint64_t timecode,
  1796. int64_t pos)
  1797. {
  1798. int a = st->codec->block_align;
  1799. int sps = track->audio.sub_packet_size;
  1800. int cfs = track->audio.coded_framesize;
  1801. int h = track->audio.sub_packet_h;
  1802. int y = track->audio.sub_packet_cnt;
  1803. int w = track->audio.frame_size;
  1804. int x;
  1805. if (!track->audio.pkt_cnt) {
  1806. if (track->audio.sub_packet_cnt == 0)
  1807. track->audio.buf_timecode = timecode;
  1808. if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
  1809. if (size < cfs * h / 2) {
  1810. av_log(matroska->ctx, AV_LOG_ERROR,
  1811. "Corrupt int4 RM-style audio packet size\n");
  1812. return AVERROR_INVALIDDATA;
  1813. }
  1814. for (x=0; x<h/2; x++)
  1815. memcpy(track->audio.buf+x*2*w+y*cfs,
  1816. data+x*cfs, cfs);
  1817. } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
  1818. if (size < w) {
  1819. av_log(matroska->ctx, AV_LOG_ERROR,
  1820. "Corrupt sipr RM-style audio packet size\n");
  1821. return AVERROR_INVALIDDATA;
  1822. }
  1823. memcpy(track->audio.buf + y*w, data, w);
  1824. } else {
  1825. if (size < sps * w / sps) {
  1826. av_log(matroska->ctx, AV_LOG_ERROR,
  1827. "Corrupt generic RM-style audio packet size\n");
  1828. return AVERROR_INVALIDDATA;
  1829. }
  1830. for (x=0; x<w/sps; x++)
  1831. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1832. }
  1833. if (++track->audio.sub_packet_cnt >= h) {
  1834. if (st->codec->codec_id == AV_CODEC_ID_SIPR)
  1835. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1836. track->audio.sub_packet_cnt = 0;
  1837. track->audio.pkt_cnt = h*w / a;
  1838. }
  1839. }
  1840. while (track->audio.pkt_cnt) {
  1841. AVPacket *pkt = av_mallocz(sizeof(AVPacket));
  1842. av_new_packet(pkt, a);
  1843. memcpy(pkt->data, track->audio.buf
  1844. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1845. pkt->pts = track->audio.buf_timecode;
  1846. track->audio.buf_timecode = AV_NOPTS_VALUE;
  1847. pkt->pos = pos;
  1848. pkt->stream_index = st->index;
  1849. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1850. }
  1851. return 0;
  1852. }
  1853. static int matroska_parse_frame(MatroskaDemuxContext *matroska,
  1854. MatroskaTrack *track,
  1855. AVStream *st,
  1856. uint8_t *data, int pkt_size,
  1857. uint64_t timecode, uint64_t lace_duration,
  1858. int64_t pos, int is_keyframe)
  1859. {
  1860. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1861. uint8_t *pkt_data = data;
  1862. int offset = 0, res;
  1863. AVPacket *pkt;
  1864. if (encodings && encodings->scope & 1) {
  1865. res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
  1866. if (res < 0)
  1867. return res;
  1868. }
  1869. if (st->codec->codec_id == AV_CODEC_ID_PRORES)
  1870. offset = 8;
  1871. pkt = av_mallocz(sizeof(AVPacket));
  1872. /* XXX: prevent data copy... */
  1873. if (av_new_packet(pkt, pkt_size + offset) < 0) {
  1874. av_free(pkt);
  1875. return AVERROR(ENOMEM);
  1876. }
  1877. if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
  1878. uint8_t *buf = pkt->data;
  1879. bytestream_put_be32(&buf, pkt_size);
  1880. bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
  1881. }
  1882. memcpy(pkt->data + offset, pkt_data, pkt_size);
  1883. if (pkt_data != data)
  1884. av_free(pkt_data);
  1885. pkt->flags = is_keyframe;
  1886. pkt->stream_index = st->index;
  1887. if (track->ms_compat)
  1888. pkt->dts = timecode;
  1889. else
  1890. pkt->pts = timecode;
  1891. pkt->pos = pos;
  1892. if (st->codec->codec_id == AV_CODEC_ID_SUBRIP) {
  1893. /*
  1894. * For backward compatibility.
  1895. * Historically, we have put subtitle duration
  1896. * in convergence_duration, on the off chance
  1897. * that the time_scale is less than 1us, which
  1898. * could result in a 32bit overflow on the
  1899. * normal duration field.
  1900. */
  1901. pkt->convergence_duration = lace_duration;
  1902. }
  1903. if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE ||
  1904. lace_duration <= INT_MAX) {
  1905. /*
  1906. * For non subtitle tracks, just store the duration
  1907. * as normal.
  1908. *
  1909. * If it's a subtitle track and duration value does
  1910. * not overflow a uint32, then also store it normally.
  1911. */
  1912. pkt->duration = lace_duration;
  1913. }
  1914. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  1915. matroska_fix_ass_packet(matroska, pkt, lace_duration);
  1916. if (matroska->prev_pkt &&
  1917. timecode != AV_NOPTS_VALUE &&
  1918. matroska->prev_pkt->pts == timecode &&
  1919. matroska->prev_pkt->stream_index == st->index &&
  1920. st->codec->codec_id == AV_CODEC_ID_SSA)
  1921. matroska_merge_packets(matroska->prev_pkt, pkt);
  1922. else {
  1923. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1924. matroska->prev_pkt = pkt;
  1925. }
  1926. return 0;
  1927. }
  1928. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1929. int size, int64_t pos, uint64_t cluster_time,
  1930. uint64_t block_duration, int is_keyframe,
  1931. int64_t cluster_pos)
  1932. {
  1933. uint64_t timecode = AV_NOPTS_VALUE;
  1934. MatroskaTrack *track;
  1935. int res = 0;
  1936. AVStream *st;
  1937. int16_t block_time;
  1938. uint32_t *lace_size = NULL;
  1939. int n, flags, laces = 0;
  1940. uint64_t num;
  1941. int trust_default_duration = 1;
  1942. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  1943. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1944. return n;
  1945. }
  1946. data += n;
  1947. size -= n;
  1948. track = matroska_find_track_by_num(matroska, num);
  1949. if (!track || !track->stream) {
  1950. av_log(matroska->ctx, AV_LOG_INFO,
  1951. "Invalid stream %"PRIu64" or size %u\n", num, size);
  1952. return AVERROR_INVALIDDATA;
  1953. } else if (size <= 3)
  1954. return 0;
  1955. st = track->stream;
  1956. if (st->discard >= AVDISCARD_ALL)
  1957. return res;
  1958. av_assert1(block_duration != AV_NOPTS_VALUE);
  1959. block_time = AV_RB16(data);
  1960. data += 2;
  1961. flags = *data++;
  1962. size -= 3;
  1963. if (is_keyframe == -1)
  1964. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  1965. if (cluster_time != (uint64_t)-1
  1966. && (block_time >= 0 || cluster_time >= -block_time)) {
  1967. timecode = cluster_time + block_time;
  1968. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  1969. && timecode < track->end_timecode)
  1970. is_keyframe = 0; /* overlapping subtitles are not key frame */
  1971. if (is_keyframe)
  1972. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  1973. }
  1974. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1975. if (timecode < matroska->skip_to_timecode)
  1976. return res;
  1977. if (!st->skip_to_keyframe) {
  1978. av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
  1979. matroska->skip_to_keyframe = 0;
  1980. }
  1981. if (is_keyframe)
  1982. matroska->skip_to_keyframe = 0;
  1983. }
  1984. res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
  1985. &lace_size, &laces);
  1986. if (res)
  1987. goto end;
  1988. if (track->audio.samplerate == 8000) {
  1989. // If this is needed for more codecs, then add them here
  1990. if (st->codec->codec_id == AV_CODEC_ID_AC3) {
  1991. if(track->audio.samplerate != st->codec->sample_rate || !st->codec->frame_size)
  1992. trust_default_duration = 0;
  1993. }
  1994. }
  1995. if (!block_duration && trust_default_duration)
  1996. block_duration = track->default_duration * laces / matroska->time_scale;
  1997. if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
  1998. track->end_timecode =
  1999. FFMAX(track->end_timecode, timecode + block_duration);
  2000. for (n = 0; n < laces; n++) {
  2001. int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
  2002. if (lace_size[n] > size) {
  2003. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
  2004. break;
  2005. }
  2006. if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
  2007. st->codec->codec_id == AV_CODEC_ID_COOK ||
  2008. st->codec->codec_id == AV_CODEC_ID_SIPR ||
  2009. st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
  2010. st->codec->block_align && track->audio.sub_packet_size) {
  2011. res = matroska_parse_rm_audio(matroska, track, st, data, size,
  2012. timecode, pos);
  2013. if (res)
  2014. goto end;
  2015. } else {
  2016. res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
  2017. timecode, lace_duration,
  2018. pos, !n? is_keyframe : 0);
  2019. if (res)
  2020. goto end;
  2021. }
  2022. if (timecode != AV_NOPTS_VALUE)
  2023. timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
  2024. data += lace_size[n];
  2025. size -= lace_size[n];
  2026. }
  2027. end:
  2028. av_free(lace_size);
  2029. return res;
  2030. }
  2031. static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
  2032. {
  2033. EbmlList *blocks_list;
  2034. MatroskaBlock *blocks;
  2035. int i, res;
  2036. res = ebml_parse(matroska,
  2037. matroska_cluster_incremental_parsing,
  2038. &matroska->current_cluster);
  2039. if (res == 1) {
  2040. /* New Cluster */
  2041. if (matroska->current_cluster_pos)
  2042. ebml_level_end(matroska);
  2043. ebml_free(matroska_cluster, &matroska->current_cluster);
  2044. memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
  2045. matroska->current_cluster_num_blocks = 0;
  2046. matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
  2047. matroska->prev_pkt = NULL;
  2048. /* sizeof the ID which was already read */
  2049. if (matroska->current_id)
  2050. matroska->current_cluster_pos -= 4;
  2051. res = ebml_parse(matroska,
  2052. matroska_clusters_incremental,
  2053. &matroska->current_cluster);
  2054. /* Try parsing the block again. */
  2055. if (res == 1)
  2056. res = ebml_parse(matroska,
  2057. matroska_cluster_incremental_parsing,
  2058. &matroska->current_cluster);
  2059. }
  2060. if (!res &&
  2061. matroska->current_cluster_num_blocks <
  2062. matroska->current_cluster.blocks.nb_elem) {
  2063. blocks_list = &matroska->current_cluster.blocks;
  2064. blocks = blocks_list->elem;
  2065. matroska->current_cluster_num_blocks = blocks_list->nb_elem;
  2066. i = blocks_list->nb_elem - 1;
  2067. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2068. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2069. if (!blocks[i].non_simple)
  2070. blocks[i].duration = 0;
  2071. res = matroska_parse_block(matroska,
  2072. blocks[i].bin.data, blocks[i].bin.size,
  2073. blocks[i].bin.pos,
  2074. matroska->current_cluster.timecode,
  2075. blocks[i].duration, is_keyframe,
  2076. matroska->current_cluster_pos);
  2077. }
  2078. }
  2079. return res;
  2080. }
  2081. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  2082. {
  2083. MatroskaCluster cluster = { 0 };
  2084. EbmlList *blocks_list;
  2085. MatroskaBlock *blocks;
  2086. int i, res;
  2087. int64_t pos;
  2088. if (!matroska->contains_ssa)
  2089. return matroska_parse_cluster_incremental(matroska);
  2090. pos = avio_tell(matroska->ctx->pb);
  2091. matroska->prev_pkt = NULL;
  2092. if (matroska->current_id)
  2093. pos -= 4; /* sizeof the ID which was already read */
  2094. res = ebml_parse(matroska, matroska_clusters, &cluster);
  2095. blocks_list = &cluster.blocks;
  2096. blocks = blocks_list->elem;
  2097. for (i=0; i<blocks_list->nb_elem; i++)
  2098. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2099. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2100. res=matroska_parse_block(matroska,
  2101. blocks[i].bin.data, blocks[i].bin.size,
  2102. blocks[i].bin.pos, cluster.timecode,
  2103. blocks[i].duration, is_keyframe,
  2104. pos);
  2105. }
  2106. ebml_free(matroska_cluster, &cluster);
  2107. return res;
  2108. }
  2109. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  2110. {
  2111. MatroskaDemuxContext *matroska = s->priv_data;
  2112. while (matroska_deliver_packet(matroska, pkt)) {
  2113. int64_t pos = avio_tell(matroska->ctx->pb);
  2114. if (matroska->done)
  2115. return AVERROR_EOF;
  2116. if (matroska_parse_cluster(matroska) < 0)
  2117. matroska_resync(matroska, pos);
  2118. }
  2119. return 0;
  2120. }
  2121. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  2122. int64_t timestamp, int flags)
  2123. {
  2124. MatroskaDemuxContext *matroska = s->priv_data;
  2125. MatroskaTrack *tracks = matroska->tracks.elem;
  2126. AVStream *st = s->streams[stream_index];
  2127. int i, index, index_sub, index_min;
  2128. /* Parse the CUES now since we need the index data to seek. */
  2129. if (matroska->cues_parsing_deferred > 0) {
  2130. matroska->cues_parsing_deferred = 0;
  2131. matroska_parse_cues(matroska);
  2132. }
  2133. if (!st->nb_index_entries)
  2134. goto err;
  2135. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  2136. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2137. avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  2138. matroska->current_id = 0;
  2139. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2140. matroska_clear_queue(matroska);
  2141. if (matroska_parse_cluster(matroska) < 0)
  2142. break;
  2143. }
  2144. }
  2145. matroska_clear_queue(matroska);
  2146. if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
  2147. goto err;
  2148. index_min = index;
  2149. for (i=0; i < matroska->tracks.nb_elem; i++) {
  2150. tracks[i].audio.pkt_cnt = 0;
  2151. tracks[i].audio.sub_packet_cnt = 0;
  2152. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  2153. tracks[i].end_timecode = 0;
  2154. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  2155. && !tracks[i].stream->discard != AVDISCARD_ALL) {
  2156. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  2157. while(index_sub >= 0
  2158. && index_min >= 0
  2159. && tracks[i].stream->index_entries[index_sub].pos < st->index_entries[index_min].pos
  2160. && st->index_entries[index].timestamp - tracks[i].stream->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  2161. index_min--;
  2162. }
  2163. }
  2164. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  2165. matroska->current_id = 0;
  2166. st->skip_to_keyframe =
  2167. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  2168. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  2169. matroska->done = 0;
  2170. matroska->num_levels = 0;
  2171. ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
  2172. return 0;
  2173. err:
  2174. // slightly hackish but allows proper fallback to
  2175. // the generic seeking code.
  2176. matroska_clear_queue(matroska);
  2177. matroska->current_id = 0;
  2178. st->skip_to_keyframe =
  2179. matroska->skip_to_keyframe = 0;
  2180. matroska->done = 0;
  2181. matroska->num_levels = 0;
  2182. return -1;
  2183. }
  2184. static int matroska_read_close(AVFormatContext *s)
  2185. {
  2186. MatroskaDemuxContext *matroska = s->priv_data;
  2187. MatroskaTrack *tracks = matroska->tracks.elem;
  2188. int n;
  2189. matroska_clear_queue(matroska);
  2190. for (n=0; n < matroska->tracks.nb_elem; n++)
  2191. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  2192. av_free(tracks[n].audio.buf);
  2193. ebml_free(matroska_cluster, &matroska->current_cluster);
  2194. ebml_free(matroska_segment, matroska);
  2195. return 0;
  2196. }
  2197. AVInputFormat ff_matroska_demuxer = {
  2198. .name = "matroska,webm",
  2199. .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
  2200. .priv_data_size = sizeof(MatroskaDemuxContext),
  2201. .read_probe = matroska_probe,
  2202. .read_header = matroska_read_header,
  2203. .read_packet = matroska_read_packet,
  2204. .read_close = matroska_read_close,
  2205. .read_seek = matroska_read_seek,
  2206. };