matroskadec.c 84 KB

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