mov.c 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111
  1. /*
  2. * MOV demuxer
  3. * Copyright (c) 2001 Fabrice Bellard
  4. * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include <limits.h>
  23. //#define DEBUG
  24. //#define DEBUG_METADATA
  25. //#define MOV_EXPORT_ALL_METADATA
  26. #include "libavutil/intreadwrite.h"
  27. #include "libavutil/avstring.h"
  28. #include "avformat.h"
  29. #include "riff.h"
  30. #include "isom.h"
  31. #include "libavcodec/mpeg4audio.h"
  32. #include "libavcodec/mpegaudiodata.h"
  33. #include "libavcodec/bitstream.h"
  34. #if CONFIG_ZLIB
  35. #include <zlib.h>
  36. #endif
  37. /*
  38. * First version by Francois Revol revol@free.fr
  39. * Seek function by Gael Chardon gael.dev@4now.net
  40. *
  41. * Features and limitations:
  42. * - reads most of the QT files I have (at least the structure),
  43. * Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
  44. * - the code is quite ugly... maybe I won't do it recursive next time :-)
  45. *
  46. * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
  47. * when coding this :) (it's a writer anyway)
  48. *
  49. * Reference documents:
  50. * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
  51. * Apple:
  52. * http://developer.apple.com/documentation/QuickTime/QTFF/
  53. * http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
  54. * QuickTime is a trademark of Apple (AFAIK :))
  55. */
  56. #include "qtpalette.h"
  57. #undef NDEBUG
  58. #include <assert.h>
  59. /* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
  60. /* those functions parse an atom */
  61. /* return code:
  62. 0: continue to parse next atom
  63. <0: error occurred, exit
  64. */
  65. /* links atom IDs to parse functions */
  66. typedef struct MOVParseTableEntry {
  67. uint32_t type;
  68. int (*parse)(MOVContext *ctx, ByteIOContext *pb, MOVAtom atom);
  69. } MOVParseTableEntry;
  70. static const MOVParseTableEntry mov_default_parse_table[];
  71. static int mov_metadata_trkn(MOVContext *c, ByteIOContext *pb, unsigned len)
  72. {
  73. char buf[16];
  74. get_be16(pb); // unknown
  75. snprintf(buf, sizeof(buf), "%d", get_be16(pb));
  76. av_metadata_set(&c->fc->metadata, "track", buf);
  77. get_be16(pb); // total tracks
  78. return 0;
  79. }
  80. static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  81. {
  82. #ifdef MOV_EXPORT_ALL_METADATA
  83. char tmp_key[5];
  84. #endif
  85. char str[1024], key2[16], language[4] = {0};
  86. const char *key = NULL;
  87. uint16_t str_size;
  88. int (*parse)(MOVContext*, ByteIOContext*, unsigned) = NULL;
  89. switch (atom.type) {
  90. case MKTAG(0xa9,'n','a','m'): key = "title"; break;
  91. case MKTAG(0xa9,'a','u','t'):
  92. case MKTAG(0xa9,'A','R','T'):
  93. case MKTAG(0xa9,'w','r','t'): key = "author"; break;
  94. case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
  95. case MKTAG(0xa9,'c','m','t'):
  96. case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
  97. case MKTAG(0xa9,'a','l','b'): key = "album"; break;
  98. case MKTAG(0xa9,'d','a','y'): key = "year"; break;
  99. case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
  100. case MKTAG(0xa9,'t','o','o'):
  101. case MKTAG(0xa9,'e','n','c'): key = "muxer"; break;
  102. case MKTAG( 't','r','k','n'): key = "track";
  103. parse = mov_metadata_trkn; break;
  104. }
  105. if (c->itunes_metadata && atom.size > 8) {
  106. int data_size = get_be32(pb);
  107. int tag = get_le32(pb);
  108. if (tag == MKTAG('d','a','t','a')) {
  109. get_be32(pb); // type
  110. get_be32(pb); // unknown
  111. str_size = data_size - 16;
  112. atom.size -= 16;
  113. } else return 0;
  114. } else if (atom.size > 4 && key && !c->itunes_metadata) {
  115. str_size = get_be16(pb); // string length
  116. ff_mov_lang_to_iso639(get_be16(pb), language);
  117. atom.size -= 4;
  118. } else
  119. str_size = atom.size;
  120. #ifdef MOV_EXPORT_ALL_METADATA
  121. if (!key) {
  122. snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
  123. key = tmp_key;
  124. }
  125. #endif
  126. if (!key)
  127. return 0;
  128. if (atom.size < 0)
  129. return -1;
  130. str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
  131. if (parse)
  132. parse(c, pb, str_size);
  133. else {
  134. get_buffer(pb, str, str_size);
  135. str[str_size] = 0;
  136. av_metadata_set(&c->fc->metadata, key, str);
  137. if (*language && strcmp(language, "und")) {
  138. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  139. av_metadata_set(&c->fc->metadata, key2, str);
  140. }
  141. }
  142. #ifdef DEBUG_METADATA
  143. av_log(c->fc, AV_LOG_DEBUG, "lang \"%3s\" ", language);
  144. av_log(c->fc, AV_LOG_DEBUG, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %lld\n",
  145. key, str, (char*)&atom.type, str_size, atom.size);
  146. #endif
  147. return 0;
  148. }
  149. static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  150. {
  151. int64_t total_size = 0;
  152. MOVAtom a;
  153. int i;
  154. int err = 0;
  155. a.offset = atom.offset;
  156. if (atom.size < 0)
  157. atom.size = INT64_MAX;
  158. while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
  159. int (*parse)(MOVContext*, ByteIOContext*, MOVAtom) = NULL;
  160. a.size = atom.size;
  161. a.type=0;
  162. if(atom.size >= 8) {
  163. a.size = get_be32(pb);
  164. a.type = get_le32(pb);
  165. }
  166. total_size += 8;
  167. a.offset += 8;
  168. dprintf(c->fc, "type: %08x %.4s sz: %"PRIx64" %"PRIx64" %"PRIx64"\n",
  169. a.type, (char*)&a.type, a.size, atom.size, total_size);
  170. if (a.size == 1) { /* 64 bit extended size */
  171. a.size = get_be64(pb) - 8;
  172. a.offset += 8;
  173. total_size += 8;
  174. }
  175. if (a.size == 0) {
  176. a.size = atom.size - total_size;
  177. if (a.size <= 8)
  178. break;
  179. }
  180. a.size -= 8;
  181. if(a.size < 0)
  182. break;
  183. a.size = FFMIN(a.size, atom.size - total_size);
  184. for (i = 0; mov_default_parse_table[i].type; i++)
  185. if (mov_default_parse_table[i].type == a.type) {
  186. parse = mov_default_parse_table[i].parse;
  187. break;
  188. }
  189. // container is user data
  190. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  191. atom.type == MKTAG('i','l','s','t')))
  192. parse = mov_read_udta_string;
  193. if (!parse) { /* skip leaf atoms data */
  194. url_fskip(pb, a.size);
  195. } else {
  196. int64_t start_pos = url_ftell(pb);
  197. int64_t left;
  198. err = parse(c, pb, a);
  199. if (url_is_streamed(pb) && c->found_moov && c->found_mdat)
  200. break;
  201. left = a.size - url_ftell(pb) + start_pos;
  202. if (left > 0) /* skip garbage at atom end */
  203. url_fskip(pb, left);
  204. }
  205. a.offset += a.size;
  206. total_size += a.size;
  207. }
  208. if (!err && total_size < atom.size && atom.size < 0x7ffff)
  209. url_fskip(pb, atom.size - total_size);
  210. return err;
  211. }
  212. static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  213. {
  214. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  215. MOVStreamContext *sc = st->priv_data;
  216. int entries, i, j;
  217. get_be32(pb); // version + flags
  218. entries = get_be32(pb);
  219. if (entries >= UINT_MAX / sizeof(*sc->drefs))
  220. return -1;
  221. sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
  222. if (!sc->drefs)
  223. return AVERROR(ENOMEM);
  224. sc->drefs_count = entries;
  225. for (i = 0; i < sc->drefs_count; i++) {
  226. MOVDref *dref = &sc->drefs[i];
  227. uint32_t size = get_be32(pb);
  228. int64_t next = url_ftell(pb) + size - 4;
  229. dref->type = get_le32(pb);
  230. get_be32(pb); // version + flags
  231. dprintf(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
  232. if (dref->type == MKTAG('a','l','i','s') && size > 150) {
  233. /* macintosh alias record */
  234. uint16_t volume_len, len;
  235. char volume[28];
  236. int16_t type;
  237. url_fskip(pb, 10);
  238. volume_len = get_byte(pb);
  239. volume_len = FFMIN(volume_len, 27);
  240. get_buffer(pb, volume, 27);
  241. volume[volume_len] = 0;
  242. av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", volume, volume_len);
  243. url_fskip(pb, 112);
  244. for (type = 0; type != -1 && url_ftell(pb) < next; ) {
  245. type = get_be16(pb);
  246. len = get_be16(pb);
  247. av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
  248. if (len&1)
  249. len += 1;
  250. if (type == 2) { // absolute path
  251. av_free(dref->path);
  252. dref->path = av_mallocz(len+1);
  253. if (!dref->path)
  254. return AVERROR(ENOMEM);
  255. get_buffer(pb, dref->path, len);
  256. if (len > volume_len && !strncmp(dref->path, volume, volume_len)) {
  257. len -= volume_len;
  258. memmove(dref->path, dref->path+volume_len, len);
  259. dref->path[len] = 0;
  260. }
  261. for (j = 0; j < len; j++)
  262. if (dref->path[j] == ':')
  263. dref->path[j] = '/';
  264. av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
  265. } else
  266. url_fskip(pb, len);
  267. }
  268. }
  269. url_fseek(pb, next, SEEK_SET);
  270. }
  271. return 0;
  272. }
  273. static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  274. {
  275. AVStream *st;
  276. uint32_t type;
  277. uint32_t ctype;
  278. if (c->fc->nb_streams < 1) // meta before first trak
  279. return 0;
  280. st = c->fc->streams[c->fc->nb_streams-1];
  281. get_byte(pb); /* version */
  282. get_be24(pb); /* flags */
  283. /* component type */
  284. ctype = get_le32(pb);
  285. type = get_le32(pb); /* component subtype */
  286. dprintf(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
  287. dprintf(c->fc, "stype= %.4s\n", (char*)&type);
  288. if (type == MKTAG('v','i','d','e'))
  289. st->codec->codec_type = CODEC_TYPE_VIDEO;
  290. else if(type == MKTAG('s','o','u','n'))
  291. st->codec->codec_type = CODEC_TYPE_AUDIO;
  292. else if(type == MKTAG('m','1','a',' '))
  293. st->codec->codec_id = CODEC_ID_MP2;
  294. else if(type == MKTAG('s','u','b','p'))
  295. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  296. get_be32(pb); /* component manufacture */
  297. get_be32(pb); /* component flags */
  298. get_be32(pb); /* component flags mask */
  299. if(atom.size <= 24)
  300. return 0; /* nothing left to read */
  301. url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
  302. return 0;
  303. }
  304. static int mp4_read_descr_len(ByteIOContext *pb)
  305. {
  306. int len = 0;
  307. int count = 4;
  308. while (count--) {
  309. int c = get_byte(pb);
  310. len = (len << 7) | (c & 0x7f);
  311. if (!(c & 0x80))
  312. break;
  313. }
  314. return len;
  315. }
  316. static int mp4_read_descr(MOVContext *c, ByteIOContext *pb, int *tag)
  317. {
  318. int len;
  319. *tag = get_byte(pb);
  320. len = mp4_read_descr_len(pb);
  321. dprintf(c->fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
  322. return len;
  323. }
  324. #define MP4ESDescrTag 0x03
  325. #define MP4DecConfigDescrTag 0x04
  326. #define MP4DecSpecificDescrTag 0x05
  327. static const AVCodecTag mp4_audio_types[] = {
  328. { CODEC_ID_MP3ON4, AOT_PS }, /* old mp3on4 draft */
  329. { CODEC_ID_MP3ON4, AOT_L1 }, /* layer 1 */
  330. { CODEC_ID_MP3ON4, AOT_L2 }, /* layer 2 */
  331. { CODEC_ID_MP3ON4, AOT_L3 }, /* layer 3 */
  332. { CODEC_ID_NONE, AOT_NULL },
  333. };
  334. static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  335. {
  336. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  337. int tag, len;
  338. get_be32(pb); /* version + flags */
  339. len = mp4_read_descr(c, pb, &tag);
  340. if (tag == MP4ESDescrTag) {
  341. get_be16(pb); /* ID */
  342. get_byte(pb); /* priority */
  343. } else
  344. get_be16(pb); /* ID */
  345. len = mp4_read_descr(c, pb, &tag);
  346. if (tag == MP4DecConfigDescrTag) {
  347. int object_type_id = get_byte(pb);
  348. get_byte(pb); /* stream type */
  349. get_be24(pb); /* buffer size db */
  350. get_be32(pb); /* max bitrate */
  351. get_be32(pb); /* avg bitrate */
  352. st->codec->codec_id= codec_get_id(ff_mp4_obj_type, object_type_id);
  353. dprintf(c->fc, "esds object type id %d\n", object_type_id);
  354. len = mp4_read_descr(c, pb, &tag);
  355. if (tag == MP4DecSpecificDescrTag) {
  356. dprintf(c->fc, "Specific MPEG4 header len=%d\n", len);
  357. if((uint64_t)len > (1<<30))
  358. return -1;
  359. st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
  360. if (!st->codec->extradata)
  361. return AVERROR(ENOMEM);
  362. get_buffer(pb, st->codec->extradata, len);
  363. st->codec->extradata_size = len;
  364. if (st->codec->codec_id == CODEC_ID_AAC) {
  365. MPEG4AudioConfig cfg;
  366. ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
  367. st->codec->extradata_size);
  368. if (cfg.chan_config > 7)
  369. return -1;
  370. st->codec->channels = ff_mpeg4audio_channels[cfg.chan_config];
  371. if (cfg.object_type == 29 && cfg.sampling_index < 3) // old mp3on4
  372. st->codec->sample_rate = ff_mpa_freq_tab[cfg.sampling_index];
  373. else
  374. st->codec->sample_rate = cfg.sample_rate; // ext sample rate ?
  375. dprintf(c->fc, "mp4a config channels %d obj %d ext obj %d "
  376. "sample rate %d ext sample rate %d\n", st->codec->channels,
  377. cfg.object_type, cfg.ext_object_type,
  378. cfg.sample_rate, cfg.ext_sample_rate);
  379. if (!(st->codec->codec_id = codec_get_id(mp4_audio_types,
  380. cfg.object_type)))
  381. st->codec->codec_id = CODEC_ID_AAC;
  382. }
  383. }
  384. }
  385. return 0;
  386. }
  387. static int mov_read_pasp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  388. {
  389. const int num = get_be32(pb);
  390. const int den = get_be32(pb);
  391. AVStream * const st = c->fc->streams[c->fc->nb_streams-1];
  392. if (den != 0) {
  393. if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
  394. (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num))
  395. av_log(c->fc, AV_LOG_WARNING,
  396. "sample aspect ratio already set to %d:%d, overriding by 'pasp' atom\n",
  397. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
  398. st->sample_aspect_ratio.num = num;
  399. st->sample_aspect_ratio.den = den;
  400. }
  401. return 0;
  402. }
  403. /* this atom contains actual media data */
  404. static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  405. {
  406. if(atom.size == 0) /* wrong one (MP4) */
  407. return 0;
  408. c->found_mdat=1;
  409. return 0; /* now go for moov */
  410. }
  411. static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  412. {
  413. uint32_t type = get_le32(pb);
  414. if (type != MKTAG('q','t',' ',' '))
  415. c->isom = 1;
  416. av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
  417. get_be32(pb); /* minor version */
  418. url_fskip(pb, atom.size - 8);
  419. return 0;
  420. }
  421. /* this atom should contain all header atoms */
  422. static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  423. {
  424. if (mov_read_default(c, pb, atom) < 0)
  425. return -1;
  426. /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
  427. /* so we don't parse the whole file if over a network */
  428. c->found_moov=1;
  429. return 0; /* now go for mdat */
  430. }
  431. static int mov_read_moof(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  432. {
  433. c->fragment.moof_offset = url_ftell(pb) - 8;
  434. dprintf(c->fc, "moof offset %llx\n", c->fragment.moof_offset);
  435. return mov_read_default(c, pb, atom);
  436. }
  437. static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  438. {
  439. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  440. MOVStreamContext *sc = st->priv_data;
  441. int version = get_byte(pb);
  442. char language[4] = {0};
  443. unsigned lang;
  444. if (version > 1)
  445. return -1; /* unsupported */
  446. get_be24(pb); /* flags */
  447. if (version == 1) {
  448. get_be64(pb);
  449. get_be64(pb);
  450. } else {
  451. get_be32(pb); /* creation time */
  452. get_be32(pb); /* modification time */
  453. }
  454. sc->time_scale = get_be32(pb);
  455. st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
  456. lang = get_be16(pb); /* language */
  457. if (ff_mov_lang_to_iso639(lang, language))
  458. av_metadata_set(&st->metadata, "language", language);
  459. get_be16(pb); /* quality */
  460. return 0;
  461. }
  462. static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  463. {
  464. int version = get_byte(pb); /* version */
  465. get_be24(pb); /* flags */
  466. if (version == 1) {
  467. get_be64(pb);
  468. get_be64(pb);
  469. } else {
  470. get_be32(pb); /* creation time */
  471. get_be32(pb); /* modification time */
  472. }
  473. c->time_scale = get_be32(pb); /* time scale */
  474. dprintf(c->fc, "time scale = %i\n", c->time_scale);
  475. c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
  476. get_be32(pb); /* preferred scale */
  477. get_be16(pb); /* preferred volume */
  478. url_fskip(pb, 10); /* reserved */
  479. url_fskip(pb, 36); /* display matrix */
  480. get_be32(pb); /* preview time */
  481. get_be32(pb); /* preview duration */
  482. get_be32(pb); /* poster time */
  483. get_be32(pb); /* selection time */
  484. get_be32(pb); /* selection duration */
  485. get_be32(pb); /* current time */
  486. get_be32(pb); /* next track ID */
  487. return 0;
  488. }
  489. static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  490. {
  491. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  492. if((uint64_t)atom.size > (1<<30))
  493. return -1;
  494. // currently SVQ3 decoder expect full STSD header - so let's fake it
  495. // this should be fixed and just SMI header should be passed
  496. av_free(st->codec->extradata);
  497. st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
  498. if (!st->codec->extradata)
  499. return AVERROR(ENOMEM);
  500. st->codec->extradata_size = 0x5a + atom.size;
  501. memcpy(st->codec->extradata, "SVQ3", 4); // fake
  502. get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
  503. dprintf(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
  504. return 0;
  505. }
  506. static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  507. {
  508. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  509. int little_endian = get_be16(pb);
  510. dprintf(c->fc, "enda %d\n", little_endian);
  511. if (little_endian == 1) {
  512. switch (st->codec->codec_id) {
  513. case CODEC_ID_PCM_S24BE:
  514. st->codec->codec_id = CODEC_ID_PCM_S24LE;
  515. break;
  516. case CODEC_ID_PCM_S32BE:
  517. st->codec->codec_id = CODEC_ID_PCM_S32LE;
  518. break;
  519. case CODEC_ID_PCM_F32BE:
  520. st->codec->codec_id = CODEC_ID_PCM_F32LE;
  521. break;
  522. case CODEC_ID_PCM_F64BE:
  523. st->codec->codec_id = CODEC_ID_PCM_F64LE;
  524. break;
  525. default:
  526. break;
  527. }
  528. }
  529. return 0;
  530. }
  531. /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
  532. static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  533. {
  534. AVStream *st;
  535. uint64_t size;
  536. uint8_t *buf;
  537. if (c->fc->nb_streams < 1) // will happen with jp2 files
  538. return 0;
  539. st= c->fc->streams[c->fc->nb_streams-1];
  540. size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
  541. if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
  542. return -1;
  543. buf= av_realloc(st->codec->extradata, size);
  544. if(!buf)
  545. return -1;
  546. st->codec->extradata= buf;
  547. buf+= st->codec->extradata_size;
  548. st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
  549. AV_WB32( buf , atom.size + 8);
  550. AV_WL32( buf + 4, atom.type);
  551. get_buffer(pb, buf + 8, atom.size);
  552. return 0;
  553. }
  554. static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  555. {
  556. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  557. if((uint64_t)atom.size > (1<<30))
  558. return -1;
  559. if (st->codec->codec_id == CODEC_ID_QDM2) {
  560. // pass all frma atom to codec, needed at least for QDM2
  561. av_free(st->codec->extradata);
  562. st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
  563. if (!st->codec->extradata)
  564. return AVERROR(ENOMEM);
  565. st->codec->extradata_size = atom.size;
  566. get_buffer(pb, st->codec->extradata, atom.size);
  567. } else if (atom.size > 8) { /* to read frma, esds atoms */
  568. if (mov_read_default(c, pb, atom) < 0)
  569. return -1;
  570. } else
  571. url_fskip(pb, atom.size);
  572. return 0;
  573. }
  574. /**
  575. * This function reads atom content and puts data in extradata without tag
  576. * nor size unlike mov_read_extradata.
  577. */
  578. static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  579. {
  580. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  581. if((uint64_t)atom.size > (1<<30))
  582. return -1;
  583. av_free(st->codec->extradata);
  584. st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
  585. if (!st->codec->extradata)
  586. return AVERROR(ENOMEM);
  587. st->codec->extradata_size = atom.size;
  588. get_buffer(pb, st->codec->extradata, atom.size);
  589. return 0;
  590. }
  591. static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  592. {
  593. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  594. MOVStreamContext *sc = st->priv_data;
  595. unsigned int i, entries;
  596. get_byte(pb); /* version */
  597. get_be24(pb); /* flags */
  598. entries = get_be32(pb);
  599. if(entries >= UINT_MAX/sizeof(int64_t))
  600. return -1;
  601. sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
  602. if (!sc->chunk_offsets)
  603. return AVERROR(ENOMEM);
  604. sc->chunk_count = entries;
  605. if (atom.type == MKTAG('s','t','c','o'))
  606. for(i=0; i<entries; i++)
  607. sc->chunk_offsets[i] = get_be32(pb);
  608. else if (atom.type == MKTAG('c','o','6','4'))
  609. for(i=0; i<entries; i++)
  610. sc->chunk_offsets[i] = get_be64(pb);
  611. else
  612. return -1;
  613. return 0;
  614. }
  615. /**
  616. * Compute codec id for 'lpcm' tag.
  617. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  618. */
  619. static enum CodecID mov_get_lpcm_codec_id(int bps, int flags)
  620. {
  621. if (flags & 1) { // floating point
  622. if (flags & 2) { // big endian
  623. if (bps == 32) return CODEC_ID_PCM_F32BE;
  624. else if (bps == 64) return CODEC_ID_PCM_F64BE;
  625. } else {
  626. if (bps == 32) return CODEC_ID_PCM_F32LE;
  627. else if (bps == 64) return CODEC_ID_PCM_F64LE;
  628. }
  629. } else {
  630. if (flags & 2) {
  631. if (bps == 8)
  632. // signed integer
  633. if (flags & 4) return CODEC_ID_PCM_S8;
  634. else return CODEC_ID_PCM_U8;
  635. else if (bps == 16) return CODEC_ID_PCM_S16BE;
  636. else if (bps == 24) return CODEC_ID_PCM_S24BE;
  637. else if (bps == 32) return CODEC_ID_PCM_S32BE;
  638. } else {
  639. if (bps == 8)
  640. if (flags & 4) return CODEC_ID_PCM_S8;
  641. else return CODEC_ID_PCM_U8;
  642. else if (bps == 16) return CODEC_ID_PCM_S16LE;
  643. else if (bps == 24) return CODEC_ID_PCM_S24LE;
  644. else if (bps == 32) return CODEC_ID_PCM_S32LE;
  645. }
  646. }
  647. return CODEC_ID_NONE;
  648. }
  649. static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  650. {
  651. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  652. MOVStreamContext *sc = st->priv_data;
  653. int j, entries, pseudo_stream_id;
  654. get_byte(pb); /* version */
  655. get_be24(pb); /* flags */
  656. entries = get_be32(pb);
  657. for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
  658. //Parsing Sample description table
  659. enum CodecID id;
  660. int dref_id;
  661. MOVAtom a = { 0, 0, 0 };
  662. int64_t start_pos = url_ftell(pb);
  663. int size = get_be32(pb); /* size */
  664. uint32_t format = get_le32(pb); /* data format */
  665. get_be32(pb); /* reserved */
  666. get_be16(pb); /* reserved */
  667. dref_id = get_be16(pb);
  668. if (st->codec->codec_tag &&
  669. st->codec->codec_tag != format &&
  670. (c->fc->video_codec_id ? codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
  671. : st->codec->codec_tag != MKTAG('j','p','e','g'))
  672. ){
  673. /* Multiple fourcc, we skip JPEG. This is not correct, we should
  674. * export it as a separate AVStream but this needs a few changes
  675. * in the MOV demuxer, patch welcome. */
  676. av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  677. url_fskip(pb, size - (url_ftell(pb) - start_pos));
  678. continue;
  679. }
  680. sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
  681. sc->dref_id= dref_id;
  682. st->codec->codec_tag = format;
  683. id = codec_get_id(codec_movaudio_tags, format);
  684. if (id<=0 && (format&0xFFFF) == 'm'+('s'<<8))
  685. id = codec_get_id(codec_wav_tags, bswap_32(format)&0xFFFF);
  686. if (st->codec->codec_type != CODEC_TYPE_VIDEO && id > 0) {
  687. st->codec->codec_type = CODEC_TYPE_AUDIO;
  688. } else if (st->codec->codec_type != CODEC_TYPE_AUDIO && /* do not overwrite codec type */
  689. format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
  690. id = codec_get_id(codec_movvideo_tags, format);
  691. if (id <= 0)
  692. id = codec_get_id(codec_bmp_tags, format);
  693. if (id > 0)
  694. st->codec->codec_type = CODEC_TYPE_VIDEO;
  695. else if(st->codec->codec_type == CODEC_TYPE_DATA){
  696. id = codec_get_id(ff_codec_movsubtitle_tags, format);
  697. if(id > 0)
  698. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  699. }
  700. }
  701. dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
  702. (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
  703. (format >> 24) & 0xff, st->codec->codec_type);
  704. if(st->codec->codec_type==CODEC_TYPE_VIDEO) {
  705. uint8_t codec_name[32];
  706. unsigned int color_depth;
  707. int color_greyscale;
  708. st->codec->codec_id = id;
  709. get_be16(pb); /* version */
  710. get_be16(pb); /* revision level */
  711. get_be32(pb); /* vendor */
  712. get_be32(pb); /* temporal quality */
  713. get_be32(pb); /* spatial quality */
  714. st->codec->width = get_be16(pb); /* width */
  715. st->codec->height = get_be16(pb); /* height */
  716. get_be32(pb); /* horiz resolution */
  717. get_be32(pb); /* vert resolution */
  718. get_be32(pb); /* data size, always 0 */
  719. get_be16(pb); /* frames per samples */
  720. get_buffer(pb, codec_name, 32); /* codec name, pascal string */
  721. if (codec_name[0] <= 31) {
  722. memcpy(st->codec->codec_name, &codec_name[1],codec_name[0]);
  723. st->codec->codec_name[codec_name[0]] = 0;
  724. }
  725. st->codec->bits_per_coded_sample = get_be16(pb); /* depth */
  726. st->codec->color_table_id = get_be16(pb); /* colortable id */
  727. dprintf(c->fc, "depth %d, ctab id %d\n",
  728. st->codec->bits_per_coded_sample, st->codec->color_table_id);
  729. /* figure out the palette situation */
  730. color_depth = st->codec->bits_per_coded_sample & 0x1F;
  731. color_greyscale = st->codec->bits_per_coded_sample & 0x20;
  732. /* if the depth is 2, 4, or 8 bpp, file is palettized */
  733. if ((color_depth == 2) || (color_depth == 4) ||
  734. (color_depth == 8)) {
  735. /* for palette traversal */
  736. unsigned int color_start, color_count, color_end;
  737. unsigned char r, g, b;
  738. st->codec->palctrl = av_malloc(sizeof(*st->codec->palctrl));
  739. if (color_greyscale) {
  740. int color_index, color_dec;
  741. /* compute the greyscale palette */
  742. st->codec->bits_per_coded_sample = color_depth;
  743. color_count = 1 << color_depth;
  744. color_index = 255;
  745. color_dec = 256 / (color_count - 1);
  746. for (j = 0; j < color_count; j++) {
  747. r = g = b = color_index;
  748. st->codec->palctrl->palette[j] =
  749. (r << 16) | (g << 8) | (b);
  750. color_index -= color_dec;
  751. if (color_index < 0)
  752. color_index = 0;
  753. }
  754. } else if (st->codec->color_table_id) {
  755. const uint8_t *color_table;
  756. /* if flag bit 3 is set, use the default palette */
  757. color_count = 1 << color_depth;
  758. if (color_depth == 2)
  759. color_table = ff_qt_default_palette_4;
  760. else if (color_depth == 4)
  761. color_table = ff_qt_default_palette_16;
  762. else
  763. color_table = ff_qt_default_palette_256;
  764. for (j = 0; j < color_count; j++) {
  765. r = color_table[j * 3 + 0];
  766. g = color_table[j * 3 + 1];
  767. b = color_table[j * 3 + 2];
  768. st->codec->palctrl->palette[j] =
  769. (r << 16) | (g << 8) | (b);
  770. }
  771. } else {
  772. /* load the palette from the file */
  773. color_start = get_be32(pb);
  774. color_count = get_be16(pb);
  775. color_end = get_be16(pb);
  776. if ((color_start <= 255) &&
  777. (color_end <= 255)) {
  778. for (j = color_start; j <= color_end; j++) {
  779. /* each R, G, or B component is 16 bits;
  780. * only use the top 8 bits; skip alpha bytes
  781. * up front */
  782. get_byte(pb);
  783. get_byte(pb);
  784. r = get_byte(pb);
  785. get_byte(pb);
  786. g = get_byte(pb);
  787. get_byte(pb);
  788. b = get_byte(pb);
  789. get_byte(pb);
  790. st->codec->palctrl->palette[j] =
  791. (r << 16) | (g << 8) | (b);
  792. }
  793. }
  794. }
  795. st->codec->palctrl->palette_changed = 1;
  796. }
  797. } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
  798. int bits_per_sample, flags;
  799. uint16_t version = get_be16(pb);
  800. st->codec->codec_id = id;
  801. get_be16(pb); /* revision level */
  802. get_be32(pb); /* vendor */
  803. st->codec->channels = get_be16(pb); /* channel count */
  804. dprintf(c->fc, "audio channels %d\n", st->codec->channels);
  805. st->codec->bits_per_coded_sample = get_be16(pb); /* sample size */
  806. sc->audio_cid = get_be16(pb);
  807. get_be16(pb); /* packet size = 0 */
  808. st->codec->sample_rate = ((get_be32(pb) >> 16));
  809. //Read QT version 1 fields. In version 0 these do not exist.
  810. dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
  811. if(!c->isom) {
  812. if(version==1) {
  813. sc->samples_per_frame = get_be32(pb);
  814. get_be32(pb); /* bytes per packet */
  815. sc->bytes_per_frame = get_be32(pb);
  816. get_be32(pb); /* bytes per sample */
  817. } else if(version==2) {
  818. get_be32(pb); /* sizeof struct only */
  819. st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
  820. st->codec->channels = get_be32(pb);
  821. get_be32(pb); /* always 0x7F000000 */
  822. st->codec->bits_per_coded_sample = get_be32(pb); /* bits per channel if sound is uncompressed */
  823. flags = get_be32(pb); /* lcpm format specific flag */
  824. sc->bytes_per_frame = get_be32(pb); /* bytes per audio packet if constant */
  825. sc->samples_per_frame = get_be32(pb); /* lpcm frames per audio packet if constant */
  826. if (format == MKTAG('l','p','c','m'))
  827. st->codec->codec_id = mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
  828. }
  829. }
  830. switch (st->codec->codec_id) {
  831. case CODEC_ID_PCM_S8:
  832. case CODEC_ID_PCM_U8:
  833. if (st->codec->bits_per_coded_sample == 16)
  834. st->codec->codec_id = CODEC_ID_PCM_S16BE;
  835. break;
  836. case CODEC_ID_PCM_S16LE:
  837. case CODEC_ID_PCM_S16BE:
  838. if (st->codec->bits_per_coded_sample == 8)
  839. st->codec->codec_id = CODEC_ID_PCM_S8;
  840. else if (st->codec->bits_per_coded_sample == 24)
  841. st->codec->codec_id =
  842. st->codec->codec_id == CODEC_ID_PCM_S16BE ?
  843. CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
  844. break;
  845. /* set values for old format before stsd version 1 appeared */
  846. case CODEC_ID_MACE3:
  847. sc->samples_per_frame = 6;
  848. sc->bytes_per_frame = 2*st->codec->channels;
  849. break;
  850. case CODEC_ID_MACE6:
  851. sc->samples_per_frame = 6;
  852. sc->bytes_per_frame = 1*st->codec->channels;
  853. break;
  854. case CODEC_ID_ADPCM_IMA_QT:
  855. sc->samples_per_frame = 64;
  856. sc->bytes_per_frame = 34*st->codec->channels;
  857. break;
  858. case CODEC_ID_GSM:
  859. sc->samples_per_frame = 160;
  860. sc->bytes_per_frame = 33;
  861. break;
  862. default:
  863. break;
  864. }
  865. bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
  866. if (bits_per_sample) {
  867. st->codec->bits_per_coded_sample = bits_per_sample;
  868. sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
  869. }
  870. } else if(st->codec->codec_type==CODEC_TYPE_SUBTITLE){
  871. // ttxt stsd contains display flags, justification, background
  872. // color, fonts, and default styles, so fake an atom to read it
  873. MOVAtom fake_atom = { .size = size - (url_ftell(pb) - start_pos) };
  874. mov_read_glbl(c, pb, fake_atom);
  875. st->codec->codec_id= id;
  876. st->codec->width = sc->width;
  877. st->codec->height = sc->height;
  878. } else {
  879. /* other codec type, just skip (rtp, mp4s, tmcd ...) */
  880. url_fskip(pb, size - (url_ftell(pb) - start_pos));
  881. }
  882. /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
  883. a.size = size - (url_ftell(pb) - start_pos);
  884. if (a.size > 8) {
  885. if (mov_read_default(c, pb, a) < 0)
  886. return -1;
  887. } else if (a.size > 0)
  888. url_fskip(pb, a.size);
  889. }
  890. if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
  891. st->codec->sample_rate= sc->time_scale;
  892. /* special codec parameters handling */
  893. switch (st->codec->codec_id) {
  894. #if CONFIG_DV_DEMUXER
  895. case CODEC_ID_DVAUDIO:
  896. c->dv_fctx = avformat_alloc_context();
  897. c->dv_demux = dv_init_demux(c->dv_fctx);
  898. if (!c->dv_demux) {
  899. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  900. return -1;
  901. }
  902. sc->dv_audio_container = 1;
  903. st->codec->codec_id = CODEC_ID_PCM_S16LE;
  904. break;
  905. #endif
  906. /* no ifdef since parameters are always those */
  907. case CODEC_ID_QCELP:
  908. st->codec->frame_size= 160;
  909. st->codec->channels= 1; /* really needed */
  910. break;
  911. case CODEC_ID_AMR_NB:
  912. case CODEC_ID_AMR_WB:
  913. st->codec->frame_size= sc->samples_per_frame;
  914. st->codec->channels= 1; /* really needed */
  915. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  916. if (st->codec->codec_id == CODEC_ID_AMR_NB)
  917. st->codec->sample_rate = 8000;
  918. else if (st->codec->codec_id == CODEC_ID_AMR_WB)
  919. st->codec->sample_rate = 16000;
  920. break;
  921. case CODEC_ID_MP2:
  922. case CODEC_ID_MP3:
  923. st->codec->codec_type = CODEC_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
  924. st->need_parsing = AVSTREAM_PARSE_FULL;
  925. break;
  926. case CODEC_ID_GSM:
  927. case CODEC_ID_ADPCM_MS:
  928. case CODEC_ID_ADPCM_IMA_WAV:
  929. st->codec->block_align = sc->bytes_per_frame;
  930. break;
  931. case CODEC_ID_ALAC:
  932. if (st->codec->extradata_size == 36) {
  933. st->codec->frame_size = AV_RB32(st->codec->extradata+12);
  934. st->codec->channels = AV_RB8 (st->codec->extradata+21);
  935. }
  936. break;
  937. default:
  938. break;
  939. }
  940. return 0;
  941. }
  942. static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  943. {
  944. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  945. MOVStreamContext *sc = st->priv_data;
  946. unsigned int i, entries;
  947. get_byte(pb); /* version */
  948. get_be24(pb); /* flags */
  949. entries = get_be32(pb);
  950. dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  951. if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
  952. return -1;
  953. sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
  954. if (!sc->stsc_data)
  955. return AVERROR(ENOMEM);
  956. sc->stsc_count = entries;
  957. for(i=0; i<entries; i++) {
  958. sc->stsc_data[i].first = get_be32(pb);
  959. sc->stsc_data[i].count = get_be32(pb);
  960. sc->stsc_data[i].id = get_be32(pb);
  961. }
  962. return 0;
  963. }
  964. static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  965. {
  966. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  967. MOVStreamContext *sc = st->priv_data;
  968. unsigned int i, entries;
  969. get_byte(pb); /* version */
  970. get_be24(pb); /* flags */
  971. entries = get_be32(pb);
  972. dprintf(c->fc, "keyframe_count = %d\n", entries);
  973. if(entries >= UINT_MAX / sizeof(int))
  974. return -1;
  975. sc->keyframes = av_malloc(entries * sizeof(int));
  976. if (!sc->keyframes)
  977. return AVERROR(ENOMEM);
  978. sc->keyframe_count = entries;
  979. for(i=0; i<entries; i++) {
  980. sc->keyframes[i] = get_be32(pb);
  981. //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
  982. }
  983. return 0;
  984. }
  985. static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  986. {
  987. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  988. MOVStreamContext *sc = st->priv_data;
  989. unsigned int i, entries, sample_size, field_size, num_bytes;
  990. GetBitContext gb;
  991. unsigned char* buf;
  992. get_byte(pb); /* version */
  993. get_be24(pb); /* flags */
  994. if (atom.type == MKTAG('s','t','s','z')) {
  995. sample_size = get_be32(pb);
  996. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  997. sc->sample_size = sample_size;
  998. field_size = 32;
  999. } else {
  1000. sample_size = 0;
  1001. get_be24(pb); /* reserved */
  1002. field_size = get_byte(pb);
  1003. }
  1004. entries = get_be32(pb);
  1005. dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  1006. sc->sample_count = entries;
  1007. if (sample_size)
  1008. return 0;
  1009. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  1010. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  1011. return -1;
  1012. }
  1013. if(entries >= UINT_MAX / sizeof(int))
  1014. return -1;
  1015. sc->sample_sizes = av_malloc(entries * sizeof(int));
  1016. if (!sc->sample_sizes)
  1017. return AVERROR(ENOMEM);
  1018. num_bytes = (entries*field_size+4)>>3;
  1019. buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
  1020. if (!buf) {
  1021. av_freep(&sc->sample_sizes);
  1022. return AVERROR(ENOMEM);
  1023. }
  1024. if (get_buffer(pb, buf, num_bytes) < num_bytes) {
  1025. av_freep(&sc->sample_sizes);
  1026. av_free(buf);
  1027. return -1;
  1028. }
  1029. init_get_bits(&gb, buf, 8*num_bytes);
  1030. for(i=0; i<entries; i++)
  1031. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  1032. av_free(buf);
  1033. return 0;
  1034. }
  1035. static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1036. {
  1037. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  1038. MOVStreamContext *sc = st->priv_data;
  1039. unsigned int i, entries;
  1040. int64_t duration=0;
  1041. int64_t total_sample_count=0;
  1042. get_byte(pb); /* version */
  1043. get_be24(pb); /* flags */
  1044. entries = get_be32(pb);
  1045. dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
  1046. if(entries >= UINT_MAX / sizeof(*sc->stts_data))
  1047. return -1;
  1048. sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
  1049. if (!sc->stts_data)
  1050. return AVERROR(ENOMEM);
  1051. sc->stts_count = entries;
  1052. for(i=0; i<entries; i++) {
  1053. int sample_duration;
  1054. int sample_count;
  1055. sample_count=get_be32(pb);
  1056. sample_duration = get_be32(pb);
  1057. sc->stts_data[i].count= sample_count;
  1058. sc->stts_data[i].duration= sample_duration;
  1059. sc->time_rate= av_gcd(sc->time_rate, sample_duration);
  1060. dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
  1061. duration+=(int64_t)sample_duration*sample_count;
  1062. total_sample_count+=sample_count;
  1063. }
  1064. st->nb_frames= total_sample_count;
  1065. if(duration)
  1066. st->duration= duration;
  1067. return 0;
  1068. }
  1069. static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1070. {
  1071. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  1072. MOVStreamContext *sc = st->priv_data;
  1073. unsigned int i, entries;
  1074. get_byte(pb); /* version */
  1075. get_be24(pb); /* flags */
  1076. entries = get_be32(pb);
  1077. dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  1078. if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
  1079. return -1;
  1080. sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
  1081. if (!sc->ctts_data)
  1082. return AVERROR(ENOMEM);
  1083. sc->ctts_count = entries;
  1084. for(i=0; i<entries; i++) {
  1085. int count =get_be32(pb);
  1086. int duration =get_be32(pb);
  1087. if (duration < 0) {
  1088. sc->wrong_dts = 1;
  1089. st->codec->has_b_frames = 1;
  1090. }
  1091. sc->ctts_data[i].count = count;
  1092. sc->ctts_data[i].duration= duration;
  1093. sc->time_rate= av_gcd(sc->time_rate, FFABS(duration));
  1094. }
  1095. return 0;
  1096. }
  1097. static void mov_build_index(MOVContext *mov, AVStream *st)
  1098. {
  1099. MOVStreamContext *sc = st->priv_data;
  1100. int64_t current_offset;
  1101. int64_t current_dts = 0;
  1102. unsigned int stts_index = 0;
  1103. unsigned int stsc_index = 0;
  1104. unsigned int stss_index = 0;
  1105. unsigned int i, j;
  1106. /* adjust first dts according to edit list */
  1107. if (sc->time_offset) {
  1108. int rescaled = sc->time_offset < 0 ? av_rescale(sc->time_offset, sc->time_scale, mov->time_scale) : sc->time_offset;
  1109. assert(sc->time_offset % sc->time_rate == 0);
  1110. current_dts = - (rescaled / sc->time_rate);
  1111. if (sc->ctts_data && sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
  1112. /* more than 16 frames delay, dts are likely wrong
  1113. this happens with files created by iMovie */
  1114. sc->wrong_dts = 1;
  1115. st->codec->has_b_frames = 1;
  1116. }
  1117. }
  1118. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  1119. if (!(st->codec->codec_type == CODEC_TYPE_AUDIO &&
  1120. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  1121. unsigned int current_sample = 0;
  1122. unsigned int stts_sample = 0;
  1123. unsigned int keyframe, sample_size;
  1124. unsigned int distance = 0;
  1125. int key_off = sc->keyframes && sc->keyframes[0] == 1;
  1126. st->nb_frames = sc->sample_count;
  1127. for (i = 0; i < sc->chunk_count; i++) {
  1128. current_offset = sc->chunk_offsets[i];
  1129. if (stsc_index + 1 < sc->stsc_count &&
  1130. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1131. stsc_index++;
  1132. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  1133. if (current_sample >= sc->sample_count) {
  1134. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  1135. return;
  1136. }
  1137. keyframe = !sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index];
  1138. if (keyframe) {
  1139. distance = 0;
  1140. if (stss_index + 1 < sc->keyframe_count)
  1141. stss_index++;
  1142. }
  1143. sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
  1144. if(sc->pseudo_stream_id == -1 ||
  1145. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  1146. av_add_index_entry(st, current_offset, current_dts, sample_size, distance,
  1147. keyframe ? AVINDEX_KEYFRAME : 0);
  1148. dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1149. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  1150. current_offset, current_dts, sample_size, distance, keyframe);
  1151. }
  1152. current_offset += sample_size;
  1153. assert(sc->stts_data[stts_index].duration % sc->time_rate == 0);
  1154. current_dts += sc->stts_data[stts_index].duration / sc->time_rate;
  1155. distance++;
  1156. stts_sample++;
  1157. current_sample++;
  1158. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  1159. stts_sample = 0;
  1160. stts_index++;
  1161. }
  1162. }
  1163. }
  1164. } else { /* read whole chunk */
  1165. unsigned int chunk_samples, chunk_size, chunk_duration;
  1166. unsigned int frames = 1;
  1167. for (i = 0; i < sc->chunk_count; i++) {
  1168. current_offset = sc->chunk_offsets[i];
  1169. if (stsc_index + 1 < sc->stsc_count &&
  1170. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1171. stsc_index++;
  1172. chunk_samples = sc->stsc_data[stsc_index].count;
  1173. /* get chunk size, beware of alaw/ulaw/mace */
  1174. if (sc->samples_per_frame > 0 &&
  1175. (chunk_samples * sc->bytes_per_frame % sc->samples_per_frame == 0)) {
  1176. if (sc->samples_per_frame < 160)
  1177. chunk_size = chunk_samples * sc->bytes_per_frame / sc->samples_per_frame;
  1178. else {
  1179. chunk_size = sc->bytes_per_frame;
  1180. frames = chunk_samples / sc->samples_per_frame;
  1181. chunk_samples = sc->samples_per_frame;
  1182. }
  1183. } else
  1184. chunk_size = chunk_samples * sc->sample_size;
  1185. for (j = 0; j < frames; j++) {
  1186. av_add_index_entry(st, current_offset, current_dts, chunk_size, 0, AVINDEX_KEYFRAME);
  1187. /* get chunk duration */
  1188. chunk_duration = 0;
  1189. while (chunk_samples > 0) {
  1190. if (chunk_samples < sc->stts_data[stts_index].count) {
  1191. chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
  1192. sc->stts_data[stts_index].count -= chunk_samples;
  1193. break;
  1194. } else {
  1195. chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
  1196. chunk_samples -= sc->stts_data[stts_index].count;
  1197. if (stts_index + 1 < sc->stts_count)
  1198. stts_index++;
  1199. }
  1200. }
  1201. current_offset += sc->bytes_per_frame;
  1202. dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  1203. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  1204. chunk_size, chunk_duration);
  1205. assert(chunk_duration % sc->time_rate == 0);
  1206. current_dts += chunk_duration / sc->time_rate;
  1207. }
  1208. }
  1209. }
  1210. }
  1211. static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1212. {
  1213. AVStream *st;
  1214. MOVStreamContext *sc;
  1215. int ret;
  1216. st = av_new_stream(c->fc, c->fc->nb_streams);
  1217. if (!st) return AVERROR(ENOMEM);
  1218. sc = av_mallocz(sizeof(MOVStreamContext));
  1219. if (!sc) return AVERROR(ENOMEM);
  1220. st->priv_data = sc;
  1221. st->codec->codec_type = CODEC_TYPE_DATA;
  1222. sc->ffindex = st->index;
  1223. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1224. return ret;
  1225. /* sanity checks */
  1226. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  1227. (!sc->sample_size && !sc->sample_count))) {
  1228. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  1229. st->index);
  1230. return 0;
  1231. }
  1232. if (!sc->time_rate)
  1233. sc->time_rate = 1;
  1234. if (!sc->time_scale)
  1235. sc->time_scale = c->time_scale;
  1236. av_set_pts_info(st, 64, sc->time_rate, sc->time_scale);
  1237. if (st->codec->codec_type == CODEC_TYPE_AUDIO &&
  1238. !st->codec->frame_size && sc->stts_count == 1) {
  1239. st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
  1240. st->codec->sample_rate, sc->time_scale);
  1241. dprintf(c->fc, "frame size %d\n", st->codec->frame_size);
  1242. }
  1243. if (st->duration != AV_NOPTS_VALUE) {
  1244. assert(st->duration % sc->time_rate == 0);
  1245. st->duration /= sc->time_rate;
  1246. }
  1247. mov_build_index(c, st);
  1248. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  1249. if (url_fopen(&sc->pb, sc->drefs[sc->dref_id-1].path, URL_RDONLY) < 0)
  1250. av_log(c->fc, AV_LOG_ERROR, "stream %d, error opening file %s: %s\n",
  1251. st->index, sc->drefs[sc->dref_id-1].path, strerror(errno));
  1252. } else
  1253. sc->pb = c->fc->pb;
  1254. switch (st->codec->codec_id) {
  1255. #if CONFIG_H261_DECODER
  1256. case CODEC_ID_H261:
  1257. #endif
  1258. #if CONFIG_H263_DECODER
  1259. case CODEC_ID_H263:
  1260. #endif
  1261. #if CONFIG_H264_DECODER
  1262. case CODEC_ID_H264:
  1263. #endif
  1264. #if CONFIG_MPEG4_DECODER
  1265. case CODEC_ID_MPEG4:
  1266. #endif
  1267. st->codec->width = 0; /* let decoder init width/height */
  1268. st->codec->height= 0;
  1269. break;
  1270. }
  1271. /* Do not need those anymore. */
  1272. av_freep(&sc->chunk_offsets);
  1273. av_freep(&sc->stsc_data);
  1274. av_freep(&sc->sample_sizes);
  1275. av_freep(&sc->keyframes);
  1276. av_freep(&sc->stts_data);
  1277. return 0;
  1278. }
  1279. static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1280. {
  1281. int ret;
  1282. c->itunes_metadata = 1;
  1283. ret = mov_read_default(c, pb, atom);
  1284. c->itunes_metadata = 0;
  1285. return ret;
  1286. }
  1287. static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1288. {
  1289. while (atom.size > 8) {
  1290. uint32_t tag = get_le32(pb);
  1291. atom.size -= 4;
  1292. if (tag == MKTAG('h','d','l','r')) {
  1293. url_fseek(pb, -8, SEEK_CUR);
  1294. atom.size += 8;
  1295. return mov_read_default(c, pb, atom);
  1296. }
  1297. }
  1298. return 0;
  1299. }
  1300. static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1301. {
  1302. int i;
  1303. int width;
  1304. int height;
  1305. int64_t disp_transform[2];
  1306. int display_matrix[3][2];
  1307. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  1308. MOVStreamContext *sc = st->priv_data;
  1309. int version = get_byte(pb);
  1310. get_be24(pb); /* flags */
  1311. /*
  1312. MOV_TRACK_ENABLED 0x0001
  1313. MOV_TRACK_IN_MOVIE 0x0002
  1314. MOV_TRACK_IN_PREVIEW 0x0004
  1315. MOV_TRACK_IN_POSTER 0x0008
  1316. */
  1317. if (version == 1) {
  1318. get_be64(pb);
  1319. get_be64(pb);
  1320. } else {
  1321. get_be32(pb); /* creation time */
  1322. get_be32(pb); /* modification time */
  1323. }
  1324. st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
  1325. get_be32(pb); /* reserved */
  1326. /* highlevel (considering edits) duration in movie timebase */
  1327. (version == 1) ? get_be64(pb) : get_be32(pb);
  1328. get_be32(pb); /* reserved */
  1329. get_be32(pb); /* reserved */
  1330. get_be16(pb); /* layer */
  1331. get_be16(pb); /* alternate group */
  1332. get_be16(pb); /* volume */
  1333. get_be16(pb); /* reserved */
  1334. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  1335. // they're kept in fixed point format through all calculations
  1336. // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
  1337. for (i = 0; i < 3; i++) {
  1338. display_matrix[i][0] = get_be32(pb); // 16.16 fixed point
  1339. display_matrix[i][1] = get_be32(pb); // 16.16 fixed point
  1340. get_be32(pb); // 2.30 fixed point (not used)
  1341. }
  1342. width = get_be32(pb); // 16.16 fixed point track width
  1343. height = get_be32(pb); // 16.16 fixed point track height
  1344. sc->width = width >> 16;
  1345. sc->height = height >> 16;
  1346. //transform the display width/height according to the matrix
  1347. // skip this if the display matrix is the default identity matrix
  1348. // to keep the same scale, use [width height 1<<16]
  1349. if (width && height &&
  1350. (display_matrix[0][0] != 65536 || display_matrix[0][1] ||
  1351. display_matrix[1][0] || display_matrix[1][1] != 65536 ||
  1352. display_matrix[2][0] || display_matrix[2][1])) {
  1353. for (i = 0; i < 2; i++)
  1354. disp_transform[i] =
  1355. (int64_t) width * display_matrix[0][i] +
  1356. (int64_t) height * display_matrix[1][i] +
  1357. ((int64_t) display_matrix[2][i] << 16);
  1358. //sample aspect ratio is new width/height divided by old width/height
  1359. st->sample_aspect_ratio = av_d2q(
  1360. ((double) disp_transform[0] * height) /
  1361. ((double) disp_transform[1] * width), INT_MAX);
  1362. }
  1363. return 0;
  1364. }
  1365. static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1366. {
  1367. MOVFragment *frag = &c->fragment;
  1368. MOVTrackExt *trex = NULL;
  1369. int flags, track_id, i;
  1370. get_byte(pb); /* version */
  1371. flags = get_be24(pb);
  1372. track_id = get_be32(pb);
  1373. if (!track_id)
  1374. return -1;
  1375. frag->track_id = track_id;
  1376. for (i = 0; i < c->trex_count; i++)
  1377. if (c->trex_data[i].track_id == frag->track_id) {
  1378. trex = &c->trex_data[i];
  1379. break;
  1380. }
  1381. if (!trex) {
  1382. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  1383. return -1;
  1384. }
  1385. if (flags & 0x01) frag->base_data_offset = get_be64(pb);
  1386. else frag->base_data_offset = frag->moof_offset;
  1387. if (flags & 0x02) frag->stsd_id = get_be32(pb);
  1388. else frag->stsd_id = trex->stsd_id;
  1389. frag->duration = flags & 0x08 ? get_be32(pb) : trex->duration;
  1390. frag->size = flags & 0x10 ? get_be32(pb) : trex->size;
  1391. frag->flags = flags & 0x20 ? get_be32(pb) : trex->flags;
  1392. dprintf(c->fc, "frag flags 0x%x\n", frag->flags);
  1393. return 0;
  1394. }
  1395. static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1396. {
  1397. MOVTrackExt *trex;
  1398. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  1399. return -1;
  1400. trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
  1401. if (!trex)
  1402. return AVERROR(ENOMEM);
  1403. c->trex_data = trex;
  1404. trex = &c->trex_data[c->trex_count++];
  1405. get_byte(pb); /* version */
  1406. get_be24(pb); /* flags */
  1407. trex->track_id = get_be32(pb);
  1408. trex->stsd_id = get_be32(pb);
  1409. trex->duration = get_be32(pb);
  1410. trex->size = get_be32(pb);
  1411. trex->flags = get_be32(pb);
  1412. return 0;
  1413. }
  1414. static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1415. {
  1416. MOVFragment *frag = &c->fragment;
  1417. AVStream *st = NULL;
  1418. MOVStreamContext *sc;
  1419. uint64_t offset;
  1420. int64_t dts;
  1421. int data_offset = 0;
  1422. unsigned entries, first_sample_flags = frag->flags;
  1423. int flags, distance, i;
  1424. for (i = 0; i < c->fc->nb_streams; i++) {
  1425. if (c->fc->streams[i]->id == frag->track_id) {
  1426. st = c->fc->streams[i];
  1427. break;
  1428. }
  1429. }
  1430. if (!st) {
  1431. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  1432. return -1;
  1433. }
  1434. sc = st->priv_data;
  1435. if (sc->pseudo_stream_id+1 != frag->stsd_id)
  1436. return 0;
  1437. get_byte(pb); /* version */
  1438. flags = get_be24(pb);
  1439. entries = get_be32(pb);
  1440. dprintf(c->fc, "flags 0x%x entries %d\n", flags, entries);
  1441. if (flags & 0x001) data_offset = get_be32(pb);
  1442. if (flags & 0x004) first_sample_flags = get_be32(pb);
  1443. if (flags & 0x800) {
  1444. MOVStts *ctts_data;
  1445. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  1446. return -1;
  1447. ctts_data = av_realloc(sc->ctts_data,
  1448. (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
  1449. if (!ctts_data)
  1450. return AVERROR(ENOMEM);
  1451. sc->ctts_data = ctts_data;
  1452. }
  1453. dts = st->duration;
  1454. offset = frag->base_data_offset + data_offset;
  1455. distance = 0;
  1456. dprintf(c->fc, "first sample flags 0x%x\n", first_sample_flags);
  1457. for (i = 0; i < entries; i++) {
  1458. unsigned sample_size = frag->size;
  1459. int sample_flags = i ? frag->flags : first_sample_flags;
  1460. unsigned sample_duration = frag->duration;
  1461. int keyframe;
  1462. if (flags & 0x100) sample_duration = get_be32(pb);
  1463. if (flags & 0x200) sample_size = get_be32(pb);
  1464. if (flags & 0x400) sample_flags = get_be32(pb);
  1465. if (flags & 0x800) {
  1466. sc->ctts_data[sc->ctts_count].count = 1;
  1467. sc->ctts_data[sc->ctts_count].duration = get_be32(pb);
  1468. sc->ctts_count++;
  1469. }
  1470. if ((keyframe = st->codec->codec_type == CODEC_TYPE_AUDIO ||
  1471. (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
  1472. distance = 0;
  1473. av_add_index_entry(st, offset, dts, sample_size, distance,
  1474. keyframe ? AVINDEX_KEYFRAME : 0);
  1475. dprintf(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1476. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  1477. offset, dts, sample_size, distance, keyframe);
  1478. distance++;
  1479. assert(sample_duration % sc->time_rate == 0);
  1480. dts += sample_duration / sc->time_rate;
  1481. offset += sample_size;
  1482. }
  1483. frag->moof_offset = offset;
  1484. st->duration = dts;
  1485. return 0;
  1486. }
  1487. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  1488. /* like the files created with Adobe Premiere 5.0, for samples see */
  1489. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  1490. static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1491. {
  1492. int err;
  1493. if (atom.size < 8)
  1494. return 0; /* continue */
  1495. if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  1496. url_fskip(pb, atom.size - 4);
  1497. return 0;
  1498. }
  1499. atom.type = get_le32(pb);
  1500. atom.offset += 8;
  1501. atom.size -= 8;
  1502. if (atom.type != MKTAG('m','d','a','t')) {
  1503. url_fskip(pb, atom.size);
  1504. return 0;
  1505. }
  1506. err = mov_read_mdat(c, pb, atom);
  1507. return err;
  1508. }
  1509. static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1510. {
  1511. #if CONFIG_ZLIB
  1512. ByteIOContext ctx;
  1513. uint8_t *cmov_data;
  1514. uint8_t *moov_data; /* uncompressed data */
  1515. long cmov_len, moov_len;
  1516. int ret = -1;
  1517. get_be32(pb); /* dcom atom */
  1518. if (get_le32(pb) != MKTAG('d','c','o','m'))
  1519. return -1;
  1520. if (get_le32(pb) != MKTAG('z','l','i','b')) {
  1521. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
  1522. return -1;
  1523. }
  1524. get_be32(pb); /* cmvd atom */
  1525. if (get_le32(pb) != MKTAG('c','m','v','d'))
  1526. return -1;
  1527. moov_len = get_be32(pb); /* uncompressed size */
  1528. cmov_len = atom.size - 6 * 4;
  1529. cmov_data = av_malloc(cmov_len);
  1530. if (!cmov_data)
  1531. return AVERROR(ENOMEM);
  1532. moov_data = av_malloc(moov_len);
  1533. if (!moov_data) {
  1534. av_free(cmov_data);
  1535. return AVERROR(ENOMEM);
  1536. }
  1537. get_buffer(pb, cmov_data, cmov_len);
  1538. if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  1539. goto free_and_return;
  1540. if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  1541. goto free_and_return;
  1542. atom.type = MKTAG('m','o','o','v');
  1543. atom.offset = 0;
  1544. atom.size = moov_len;
  1545. #ifdef DEBUG
  1546. // { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
  1547. #endif
  1548. ret = mov_read_default(c, &ctx, atom);
  1549. free_and_return:
  1550. av_free(moov_data);
  1551. av_free(cmov_data);
  1552. return ret;
  1553. #else
  1554. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  1555. return -1;
  1556. #endif
  1557. }
  1558. /* edit list atom */
  1559. static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1560. {
  1561. MOVStreamContext *sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  1562. int i, edit_count;
  1563. get_byte(pb); /* version */
  1564. get_be24(pb); /* flags */
  1565. edit_count = get_be32(pb); /* entries */
  1566. for(i=0; i<edit_count; i++){
  1567. int time;
  1568. int duration = get_be32(pb); /* Track duration */
  1569. time = get_be32(pb); /* Media time */
  1570. get_be32(pb); /* Media rate */
  1571. if (i == 0 && time >= -1) {
  1572. sc->time_offset = time != -1 ? time : -duration;
  1573. sc->time_rate = av_gcd(sc->time_rate, FFABS(sc->time_offset));
  1574. }
  1575. }
  1576. if(edit_count > 1)
  1577. av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
  1578. "a/v desync might occur, patch welcome\n");
  1579. dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  1580. return 0;
  1581. }
  1582. static const MOVParseTableEntry mov_default_parse_table[] = {
  1583. { MKTAG('a','v','s','s'), mov_read_extradata },
  1584. { MKTAG('c','o','6','4'), mov_read_stco },
  1585. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  1586. { MKTAG('d','i','n','f'), mov_read_default },
  1587. { MKTAG('d','r','e','f'), mov_read_dref },
  1588. { MKTAG('e','d','t','s'), mov_read_default },
  1589. { MKTAG('e','l','s','t'), mov_read_elst },
  1590. { MKTAG('e','n','d','a'), mov_read_enda },
  1591. { MKTAG('f','i','e','l'), mov_read_extradata },
  1592. { MKTAG('f','t','y','p'), mov_read_ftyp },
  1593. { MKTAG('g','l','b','l'), mov_read_glbl },
  1594. { MKTAG('h','d','l','r'), mov_read_hdlr },
  1595. { MKTAG('i','l','s','t'), mov_read_ilst },
  1596. { MKTAG('j','p','2','h'), mov_read_extradata },
  1597. { MKTAG('m','d','a','t'), mov_read_mdat },
  1598. { MKTAG('m','d','h','d'), mov_read_mdhd },
  1599. { MKTAG('m','d','i','a'), mov_read_default },
  1600. { MKTAG('m','e','t','a'), mov_read_meta },
  1601. { MKTAG('m','i','n','f'), mov_read_default },
  1602. { MKTAG('m','o','o','f'), mov_read_moof },
  1603. { MKTAG('m','o','o','v'), mov_read_moov },
  1604. { MKTAG('m','v','e','x'), mov_read_default },
  1605. { MKTAG('m','v','h','d'), mov_read_mvhd },
  1606. { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
  1607. { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
  1608. { MKTAG('a','v','c','C'), mov_read_glbl },
  1609. { MKTAG('p','a','s','p'), mov_read_pasp },
  1610. { MKTAG('s','t','b','l'), mov_read_default },
  1611. { MKTAG('s','t','c','o'), mov_read_stco },
  1612. { MKTAG('s','t','s','c'), mov_read_stsc },
  1613. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  1614. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  1615. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  1616. { MKTAG('s','t','t','s'), mov_read_stts },
  1617. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  1618. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  1619. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  1620. { MKTAG('t','r','a','k'), mov_read_trak },
  1621. { MKTAG('t','r','a','f'), mov_read_default },
  1622. { MKTAG('t','r','e','x'), mov_read_trex },
  1623. { MKTAG('t','r','u','n'), mov_read_trun },
  1624. { MKTAG('u','d','t','a'), mov_read_default },
  1625. { MKTAG('w','a','v','e'), mov_read_wave },
  1626. { MKTAG('e','s','d','s'), mov_read_esds },
  1627. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  1628. { MKTAG('c','m','o','v'), mov_read_cmov },
  1629. { 0, NULL }
  1630. };
  1631. static int mov_probe(AVProbeData *p)
  1632. {
  1633. unsigned int offset;
  1634. uint32_t tag;
  1635. int score = 0;
  1636. /* check file header */
  1637. offset = 0;
  1638. for(;;) {
  1639. /* ignore invalid offset */
  1640. if ((offset + 8) > (unsigned int)p->buf_size)
  1641. return score;
  1642. tag = AV_RL32(p->buf + offset + 4);
  1643. switch(tag) {
  1644. /* check for obvious tags */
  1645. case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
  1646. case MKTAG('m','o','o','v'):
  1647. case MKTAG('m','d','a','t'):
  1648. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  1649. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  1650. case MKTAG('f','t','y','p'):
  1651. return AVPROBE_SCORE_MAX;
  1652. /* those are more common words, so rate then a bit less */
  1653. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  1654. case MKTAG('w','i','d','e'):
  1655. case MKTAG('f','r','e','e'):
  1656. case MKTAG('j','u','n','k'):
  1657. case MKTAG('p','i','c','t'):
  1658. return AVPROBE_SCORE_MAX - 5;
  1659. case MKTAG(0x82,0x82,0x7f,0x7d):
  1660. case MKTAG('s','k','i','p'):
  1661. case MKTAG('u','u','i','d'):
  1662. case MKTAG('p','r','f','l'):
  1663. offset = AV_RB32(p->buf+offset) + offset;
  1664. /* if we only find those cause probedata is too small at least rate them */
  1665. score = AVPROBE_SCORE_MAX - 50;
  1666. break;
  1667. default:
  1668. /* unrecognized tag */
  1669. return score;
  1670. }
  1671. }
  1672. return score;
  1673. }
  1674. static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1675. {
  1676. MOVContext *mov = s->priv_data;
  1677. ByteIOContext *pb = s->pb;
  1678. int err;
  1679. MOVAtom atom = { 0, 0, 0 };
  1680. mov->fc = s;
  1681. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  1682. if(!url_is_streamed(pb))
  1683. atom.size = url_fsize(pb);
  1684. else
  1685. atom.size = INT64_MAX;
  1686. /* check MOV header */
  1687. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  1688. av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
  1689. return err;
  1690. }
  1691. if (!mov->found_moov) {
  1692. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  1693. return -1;
  1694. }
  1695. dprintf(mov->fc, "on_parse_exit_offset=%lld\n", url_ftell(pb));
  1696. return 0;
  1697. }
  1698. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  1699. {
  1700. MOVContext *mov = s->priv_data;
  1701. MOVStreamContext *sc = 0;
  1702. AVIndexEntry *sample = 0;
  1703. int64_t best_dts = INT64_MAX;
  1704. int i, ret;
  1705. retry:
  1706. for (i = 0; i < s->nb_streams; i++) {
  1707. AVStream *st = s->streams[i];
  1708. MOVStreamContext *msc = st->priv_data;
  1709. if (st->discard != AVDISCARD_ALL && msc->pb && msc->current_sample < st->nb_index_entries) {
  1710. AVIndexEntry *current_sample = &st->index_entries[msc->current_sample];
  1711. int64_t dts = av_rescale(current_sample->timestamp * (int64_t)msc->time_rate,
  1712. AV_TIME_BASE, msc->time_scale);
  1713. dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  1714. if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
  1715. (!url_is_streamed(s->pb) &&
  1716. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  1717. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  1718. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  1719. sample = current_sample;
  1720. best_dts = dts;
  1721. sc = msc;
  1722. }
  1723. }
  1724. }
  1725. if (!sample) {
  1726. mov->found_mdat = 0;
  1727. if (!url_is_streamed(s->pb) ||
  1728. mov_read_default(mov, s->pb, (MOVAtom){ 0, 0, INT64_MAX }) < 0 ||
  1729. url_feof(s->pb))
  1730. return -1;
  1731. dprintf(s, "read fragments, offset 0x%llx\n", url_ftell(s->pb));
  1732. goto retry;
  1733. }
  1734. /* must be done just before reading, to avoid infinite loop on sample */
  1735. sc->current_sample++;
  1736. if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  1737. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  1738. sc->ffindex, sample->pos);
  1739. return -1;
  1740. }
  1741. ret = av_get_packet(sc->pb, pkt, sample->size);
  1742. if (ret < 0)
  1743. return ret;
  1744. #if CONFIG_DV_DEMUXER
  1745. if (mov->dv_demux && sc->dv_audio_container) {
  1746. dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
  1747. av_free(pkt->data);
  1748. pkt->size = 0;
  1749. if (dv_get_packet(mov->dv_demux, pkt) < 0)
  1750. return -1;
  1751. }
  1752. #endif
  1753. pkt->stream_index = sc->ffindex;
  1754. pkt->dts = sample->timestamp;
  1755. if (sc->ctts_data) {
  1756. assert(sc->ctts_data[sc->ctts_index].duration % sc->time_rate == 0);
  1757. pkt->pts = pkt->dts + sc->ctts_data[sc->ctts_index].duration / sc->time_rate;
  1758. /* update ctts context */
  1759. sc->ctts_sample++;
  1760. if (sc->ctts_index < sc->ctts_count &&
  1761. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  1762. sc->ctts_index++;
  1763. sc->ctts_sample = 0;
  1764. }
  1765. if (sc->wrong_dts)
  1766. pkt->dts = AV_NOPTS_VALUE;
  1767. } else {
  1768. AVStream *st = s->streams[sc->ffindex];
  1769. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  1770. st->index_entries[sc->current_sample].timestamp : st->duration;
  1771. pkt->duration = next_dts - pkt->dts;
  1772. pkt->pts = pkt->dts;
  1773. }
  1774. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? PKT_FLAG_KEY : 0;
  1775. pkt->pos = sample->pos;
  1776. dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
  1777. pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
  1778. return 0;
  1779. }
  1780. static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
  1781. {
  1782. MOVStreamContext *sc = st->priv_data;
  1783. int sample, time_sample;
  1784. int i;
  1785. sample = av_index_search_timestamp(st, timestamp, flags);
  1786. dprintf(st->codec, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  1787. if (sample < 0) /* not sure what to do */
  1788. return -1;
  1789. sc->current_sample = sample;
  1790. dprintf(st->codec, "stream %d, found sample %d\n", st->index, sc->current_sample);
  1791. /* adjust ctts index */
  1792. if (sc->ctts_data) {
  1793. time_sample = 0;
  1794. for (i = 0; i < sc->ctts_count; i++) {
  1795. int next = time_sample + sc->ctts_data[i].count;
  1796. if (next > sc->current_sample) {
  1797. sc->ctts_index = i;
  1798. sc->ctts_sample = sc->current_sample - time_sample;
  1799. break;
  1800. }
  1801. time_sample = next;
  1802. }
  1803. }
  1804. return sample;
  1805. }
  1806. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  1807. {
  1808. AVStream *st;
  1809. int64_t seek_timestamp, timestamp;
  1810. int sample;
  1811. int i;
  1812. if (stream_index >= s->nb_streams)
  1813. return -1;
  1814. if (sample_time < 0)
  1815. sample_time = 0;
  1816. st = s->streams[stream_index];
  1817. sample = mov_seek_stream(st, sample_time, flags);
  1818. if (sample < 0)
  1819. return -1;
  1820. /* adjust seek timestamp to found sample timestamp */
  1821. seek_timestamp = st->index_entries[sample].timestamp;
  1822. for (i = 0; i < s->nb_streams; i++) {
  1823. st = s->streams[i];
  1824. if (stream_index == i || st->discard == AVDISCARD_ALL)
  1825. continue;
  1826. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  1827. mov_seek_stream(st, timestamp, flags);
  1828. }
  1829. return 0;
  1830. }
  1831. static int mov_read_close(AVFormatContext *s)
  1832. {
  1833. MOVContext *mov = s->priv_data;
  1834. int i, j;
  1835. for (i = 0; i < s->nb_streams; i++) {
  1836. AVStream *st = s->streams[i];
  1837. MOVStreamContext *sc = st->priv_data;
  1838. av_freep(&sc->ctts_data);
  1839. for (j = 0; j < sc->drefs_count; j++)
  1840. av_freep(&sc->drefs[j].path);
  1841. av_freep(&sc->drefs);
  1842. if (sc->pb && sc->pb != s->pb)
  1843. url_fclose(sc->pb);
  1844. av_freep(&st->codec->palctrl);
  1845. }
  1846. if (mov->dv_demux) {
  1847. for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
  1848. av_freep(&mov->dv_fctx->streams[i]->codec);
  1849. av_freep(&mov->dv_fctx->streams[i]);
  1850. }
  1851. av_freep(&mov->dv_fctx);
  1852. av_freep(&mov->dv_demux);
  1853. }
  1854. av_freep(&mov->trex_data);
  1855. return 0;
  1856. }
  1857. AVInputFormat mov_demuxer = {
  1858. "mov,mp4,m4a,3gp,3g2,mj2",
  1859. NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
  1860. sizeof(MOVContext),
  1861. mov_probe,
  1862. mov_read_header,
  1863. mov_read_packet,
  1864. mov_read_close,
  1865. mov_read_seek,
  1866. };