avidec.c 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604
  1. /*
  2. * AVI demuxer
  3. * Copyright (c) 2001 Fabrice Bellard
  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. #include "libavutil/intreadwrite.h"
  22. #include "libavutil/mathematics.h"
  23. #include "libavutil/bswap.h"
  24. #include "libavutil/opt.h"
  25. #include "libavutil/dict.h"
  26. #include "libavutil/avstring.h"
  27. #include "avformat.h"
  28. #include "internal.h"
  29. #include "avi.h"
  30. #include "dv.h"
  31. #include "riff.h"
  32. #undef NDEBUG
  33. #include <assert.h>
  34. typedef struct AVIStream {
  35. int64_t frame_offset; /* current frame (video) or byte (audio) counter
  36. (used to compute the pts) */
  37. int remaining;
  38. int packet_size;
  39. int scale;
  40. int rate;
  41. int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
  42. int64_t cum_len; /* temporary storage (used during seek) */
  43. int prefix; ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
  44. int prefix_count;
  45. uint32_t pal[256];
  46. int has_pal;
  47. int dshow_block_align; ///< block align variable used to emulate bugs in the MS dshow demuxer
  48. AVFormatContext *sub_ctx;
  49. AVPacket sub_pkt;
  50. uint8_t *sub_buffer;
  51. int64_t seek_pos;
  52. } AVIStream;
  53. typedef struct {
  54. const AVClass *class;
  55. int64_t riff_end;
  56. int64_t movi_end;
  57. int64_t fsize;
  58. int64_t movi_list;
  59. int64_t last_pkt_pos;
  60. int index_loaded;
  61. int is_odml;
  62. int non_interleaved;
  63. int stream_index;
  64. DVDemuxContext* dv_demux;
  65. int odml_depth;
  66. int use_odml;
  67. #define MAX_ODML_DEPTH 1000
  68. int64_t dts_max;
  69. } AVIContext;
  70. static const AVOption options[] = {
  71. { "use_odml", "use odml index", offsetof(AVIContext, use_odml), AV_OPT_TYPE_INT, {.dbl = 1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
  72. { NULL },
  73. };
  74. static const AVClass demuxer_class = {
  75. "AVI demuxer",
  76. av_default_item_name,
  77. options,
  78. LIBAVUTIL_VERSION_INT,
  79. };
  80. static const char avi_headers[][8] = {
  81. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
  82. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
  83. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19},
  84. { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
  85. { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
  86. { 0 }
  87. };
  88. static const AVMetadataConv avi_metadata_conv[] = {
  89. { "strn", "title" },
  90. { 0 },
  91. };
  92. static int avi_load_index(AVFormatContext *s);
  93. static int guess_ni_flag(AVFormatContext *s);
  94. #define print_tag(str, tag, size) \
  95. av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
  96. str, tag & 0xff, \
  97. (tag >> 8) & 0xff, \
  98. (tag >> 16) & 0xff, \
  99. (tag >> 24) & 0xff, \
  100. size)
  101. static inline int get_duration(AVIStream *ast, int len){
  102. if(ast->sample_size){
  103. return len;
  104. }else if (ast->dshow_block_align){
  105. return (len + ast->dshow_block_align - 1)/ast->dshow_block_align;
  106. }else
  107. return 1;
  108. }
  109. static int get_riff(AVFormatContext *s, AVIOContext *pb)
  110. {
  111. AVIContext *avi = s->priv_data;
  112. char header[8];
  113. int i;
  114. /* check RIFF header */
  115. avio_read(pb, header, 4);
  116. avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
  117. avi->riff_end += avio_tell(pb); /* RIFF chunk end */
  118. avio_read(pb, header+4, 4);
  119. for(i=0; avi_headers[i][0]; i++)
  120. if(!memcmp(header, avi_headers[i], 8))
  121. break;
  122. if(!avi_headers[i][0])
  123. return -1;
  124. if(header[7] == 0x19)
  125. av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
  126. return 0;
  127. }
  128. static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
  129. AVIContext *avi = s->priv_data;
  130. AVIOContext *pb = s->pb;
  131. int longs_pre_entry= avio_rl16(pb);
  132. int index_sub_type = avio_r8(pb);
  133. int index_type = avio_r8(pb);
  134. int entries_in_use = avio_rl32(pb);
  135. int chunk_id = avio_rl32(pb);
  136. int64_t base = avio_rl64(pb);
  137. int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
  138. AVStream *st;
  139. AVIStream *ast;
  140. int i;
  141. int64_t last_pos= -1;
  142. int64_t filesize= avi->fsize;
  143. av_dlog(s, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
  144. longs_pre_entry,index_type, entries_in_use, chunk_id, base);
  145. if(stream_id >= s->nb_streams || stream_id < 0)
  146. return -1;
  147. st= s->streams[stream_id];
  148. ast = st->priv_data;
  149. if(index_sub_type)
  150. return -1;
  151. avio_rl32(pb);
  152. if(index_type && longs_pre_entry != 2)
  153. return -1;
  154. if(index_type>1)
  155. return -1;
  156. if(filesize > 0 && base >= filesize){
  157. av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
  158. if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
  159. base &= 0xFFFFFFFF;
  160. else
  161. return -1;
  162. }
  163. for(i=0; i<entries_in_use; i++){
  164. if(index_type){
  165. int64_t pos= avio_rl32(pb) + base - 8;
  166. int len = avio_rl32(pb);
  167. int key= len >= 0;
  168. len &= 0x7FFFFFFF;
  169. #ifdef DEBUG_SEEK
  170. av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
  171. #endif
  172. if(url_feof(pb))
  173. return -1;
  174. if(last_pos == pos || pos == base - 8)
  175. avi->non_interleaved= 1;
  176. if(last_pos != pos && (len || !ast->sample_size))
  177. av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
  178. ast->cum_len += get_duration(ast, len);
  179. last_pos= pos;
  180. }else{
  181. int64_t offset, pos;
  182. int duration;
  183. offset = avio_rl64(pb);
  184. avio_rl32(pb); /* size */
  185. duration = avio_rl32(pb);
  186. if(url_feof(pb))
  187. return -1;
  188. pos = avio_tell(pb);
  189. if(avi->odml_depth > MAX_ODML_DEPTH){
  190. av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
  191. return -1;
  192. }
  193. if(avio_seek(pb, offset+8, SEEK_SET) < 0)
  194. return -1;
  195. avi->odml_depth++;
  196. read_braindead_odml_indx(s, frame_num);
  197. avi->odml_depth--;
  198. frame_num += duration;
  199. if(avio_seek(pb, pos, SEEK_SET) < 0) {
  200. av_log(s, AV_LOG_ERROR, "Failed to restore position after reading index");
  201. return -1;
  202. }
  203. }
  204. }
  205. avi->index_loaded=2;
  206. return 0;
  207. }
  208. static void clean_index(AVFormatContext *s){
  209. int i;
  210. int64_t j;
  211. for(i=0; i<s->nb_streams; i++){
  212. AVStream *st = s->streams[i];
  213. AVIStream *ast = st->priv_data;
  214. int n= st->nb_index_entries;
  215. int max= ast->sample_size;
  216. int64_t pos, size, ts;
  217. if(n != 1 || ast->sample_size==0)
  218. continue;
  219. while(max < 1024) max+=max;
  220. pos= st->index_entries[0].pos;
  221. size= st->index_entries[0].size;
  222. ts= st->index_entries[0].timestamp;
  223. for(j=0; j<size; j+=max){
  224. av_add_index_entry(st, pos+j, ts+j, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
  225. }
  226. }
  227. }
  228. static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
  229. {
  230. AVIOContext *pb = s->pb;
  231. char key[5] = {0}, *value;
  232. size += (size & 1);
  233. if (size == UINT_MAX)
  234. return -1;
  235. value = av_malloc(size+1);
  236. if (!value)
  237. return -1;
  238. avio_read(pb, value, size);
  239. value[size]=0;
  240. AV_WL32(key, tag);
  241. return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
  242. AV_DICT_DONT_STRDUP_VAL);
  243. }
  244. static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  245. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  246. static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
  247. {
  248. char month[4], time[9], buffer[64];
  249. int i, day, year;
  250. /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
  251. if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
  252. month, &day, time, &year) == 4) {
  253. for (i=0; i<12; i++)
  254. if (!av_strcasecmp(month, months[i])) {
  255. snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
  256. year, i+1, day, time);
  257. av_dict_set(metadata, "creation_time", buffer, 0);
  258. }
  259. } else if (date[4] == '/' && date[7] == '/') {
  260. date[4] = date[7] = '-';
  261. av_dict_set(metadata, "creation_time", date, 0);
  262. }
  263. }
  264. static void avi_read_nikon(AVFormatContext *s, uint64_t end)
  265. {
  266. while (avio_tell(s->pb) < end) {
  267. uint32_t tag = avio_rl32(s->pb);
  268. uint32_t size = avio_rl32(s->pb);
  269. switch (tag) {
  270. case MKTAG('n', 'c', 't', 'g'): { /* Nikon Tags */
  271. uint64_t tag_end = avio_tell(s->pb) + size;
  272. while (avio_tell(s->pb) < tag_end) {
  273. uint16_t tag = avio_rl16(s->pb);
  274. uint16_t size = avio_rl16(s->pb);
  275. const char *name = NULL;
  276. char buffer[64] = {0};
  277. size -= avio_read(s->pb, buffer,
  278. FFMIN(size, sizeof(buffer)-1));
  279. switch (tag) {
  280. case 0x03: name = "maker"; break;
  281. case 0x04: name = "model"; break;
  282. case 0x13: name = "creation_time";
  283. if (buffer[4] == ':' && buffer[7] == ':')
  284. buffer[4] = buffer[7] = '-';
  285. break;
  286. }
  287. if (name)
  288. av_dict_set(&s->metadata, name, buffer, 0);
  289. avio_skip(s->pb, size);
  290. }
  291. break;
  292. }
  293. default:
  294. avio_skip(s->pb, size);
  295. break;
  296. }
  297. }
  298. }
  299. static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
  300. {
  301. AVIContext *avi = s->priv_data;
  302. AVIOContext *pb = s->pb;
  303. unsigned int tag, tag1, handler;
  304. int codec_type, stream_index, frame_period;
  305. unsigned int size;
  306. int i;
  307. AVStream *st;
  308. AVIStream *ast = NULL;
  309. int avih_width=0, avih_height=0;
  310. int amv_file_format=0;
  311. uint64_t list_end = 0;
  312. int ret;
  313. avi->stream_index= -1;
  314. if (get_riff(s, pb) < 0)
  315. return -1;
  316. av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
  317. avi->fsize = avio_size(pb);
  318. if(avi->fsize<=0 || avi->fsize < avi->riff_end)
  319. avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
  320. /* first list tag */
  321. stream_index = -1;
  322. codec_type = -1;
  323. frame_period = 0;
  324. for(;;) {
  325. if (url_feof(pb))
  326. goto fail;
  327. tag = avio_rl32(pb);
  328. size = avio_rl32(pb);
  329. print_tag("tag", tag, size);
  330. switch(tag) {
  331. case MKTAG('L', 'I', 'S', 'T'):
  332. list_end = avio_tell(pb) + size;
  333. /* Ignored, except at start of video packets. */
  334. tag1 = avio_rl32(pb);
  335. print_tag("list", tag1, 0);
  336. if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
  337. avi->movi_list = avio_tell(pb) - 4;
  338. if(size) avi->movi_end = avi->movi_list + size + (size & 1);
  339. else avi->movi_end = avi->fsize;
  340. av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
  341. goto end_of_header;
  342. }
  343. else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
  344. ff_read_riff_info(s, size - 4);
  345. else if (tag1 == MKTAG('n', 'c', 'd', 't'))
  346. avi_read_nikon(s, list_end);
  347. break;
  348. case MKTAG('I', 'D', 'I', 'T'): {
  349. unsigned char date[64] = {0};
  350. size += (size & 1);
  351. size -= avio_read(pb, date, FFMIN(size, sizeof(date)-1));
  352. avio_skip(pb, size);
  353. avi_metadata_creation_time(&s->metadata, date);
  354. break;
  355. }
  356. case MKTAG('d', 'm', 'l', 'h'):
  357. avi->is_odml = 1;
  358. avio_skip(pb, size + (size & 1));
  359. break;
  360. case MKTAG('a', 'm', 'v', 'h'):
  361. amv_file_format=1;
  362. case MKTAG('a', 'v', 'i', 'h'):
  363. /* AVI header */
  364. /* using frame_period is bad idea */
  365. frame_period = avio_rl32(pb);
  366. avio_rl32(pb); /* max. bytes per second */
  367. avio_rl32(pb);
  368. avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
  369. avio_skip(pb, 2 * 4);
  370. avio_rl32(pb);
  371. avio_rl32(pb);
  372. avih_width=avio_rl32(pb);
  373. avih_height=avio_rl32(pb);
  374. avio_skip(pb, size - 10 * 4);
  375. break;
  376. case MKTAG('s', 't', 'r', 'h'):
  377. /* stream header */
  378. tag1 = avio_rl32(pb);
  379. handler = avio_rl32(pb); /* codec tag */
  380. if(tag1 == MKTAG('p', 'a', 'd', 's')){
  381. avio_skip(pb, size - 8);
  382. break;
  383. }else{
  384. stream_index++;
  385. st = avformat_new_stream(s, NULL);
  386. if (!st)
  387. goto fail;
  388. st->id = stream_index;
  389. ast = av_mallocz(sizeof(AVIStream));
  390. if (!ast)
  391. goto fail;
  392. st->priv_data = ast;
  393. }
  394. if(amv_file_format)
  395. tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
  396. print_tag("strh", tag1, -1);
  397. if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
  398. int64_t dv_dur;
  399. /*
  400. * After some consideration -- I don't think we
  401. * have to support anything but DV in type1 AVIs.
  402. */
  403. if (s->nb_streams != 1)
  404. goto fail;
  405. if (handler != MKTAG('d', 'v', 's', 'd') &&
  406. handler != MKTAG('d', 'v', 'h', 'd') &&
  407. handler != MKTAG('d', 'v', 's', 'l'))
  408. goto fail;
  409. ast = s->streams[0]->priv_data;
  410. av_freep(&s->streams[0]->codec->extradata);
  411. av_freep(&s->streams[0]->codec);
  412. av_freep(&s->streams[0]);
  413. s->nb_streams = 0;
  414. if (CONFIG_DV_DEMUXER) {
  415. avi->dv_demux = avpriv_dv_init_demux(s);
  416. if (!avi->dv_demux)
  417. goto fail;
  418. }
  419. s->streams[0]->priv_data = ast;
  420. avio_skip(pb, 3 * 4);
  421. ast->scale = avio_rl32(pb);
  422. ast->rate = avio_rl32(pb);
  423. avio_skip(pb, 4); /* start time */
  424. dv_dur = avio_rl32(pb);
  425. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  426. dv_dur *= AV_TIME_BASE;
  427. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  428. }
  429. /*
  430. * else, leave duration alone; timing estimation in utils.c
  431. * will make a guess based on bitrate.
  432. */
  433. stream_index = s->nb_streams - 1;
  434. avio_skip(pb, size - 9*4);
  435. break;
  436. }
  437. assert(stream_index < s->nb_streams);
  438. st->codec->stream_codec_tag= handler;
  439. avio_rl32(pb); /* flags */
  440. avio_rl16(pb); /* priority */
  441. avio_rl16(pb); /* language */
  442. avio_rl32(pb); /* initial frame */
  443. ast->scale = avio_rl32(pb);
  444. ast->rate = avio_rl32(pb);
  445. if(!(ast->scale && ast->rate)){
  446. av_log(s, AV_LOG_WARNING, "scale/rate is %u/%u which is invalid. (This file has been generated by broken software.)\n", ast->scale, ast->rate);
  447. if(frame_period){
  448. ast->rate = 1000000;
  449. ast->scale = frame_period;
  450. }else{
  451. ast->rate = 25;
  452. ast->scale = 1;
  453. }
  454. }
  455. avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
  456. ast->cum_len=avio_rl32(pb); /* start */
  457. st->nb_frames = avio_rl32(pb);
  458. st->start_time = 0;
  459. avio_rl32(pb); /* buffer size */
  460. avio_rl32(pb); /* quality */
  461. if (ast->cum_len*ast->scale/ast->rate > 3600) {
  462. av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n");
  463. return AVERROR_INVALIDDATA;
  464. }
  465. ast->sample_size = avio_rl32(pb); /* sample ssize */
  466. ast->cum_len *= FFMAX(1, ast->sample_size);
  467. // av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
  468. switch(tag1) {
  469. case MKTAG('v', 'i', 'd', 's'):
  470. codec_type = AVMEDIA_TYPE_VIDEO;
  471. ast->sample_size = 0;
  472. break;
  473. case MKTAG('a', 'u', 'd', 's'):
  474. codec_type = AVMEDIA_TYPE_AUDIO;
  475. break;
  476. case MKTAG('t', 'x', 't', 's'):
  477. codec_type = AVMEDIA_TYPE_SUBTITLE;
  478. break;
  479. case MKTAG('d', 'a', 't', 's'):
  480. codec_type = AVMEDIA_TYPE_DATA;
  481. break;
  482. default:
  483. av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
  484. }
  485. if(ast->sample_size == 0)
  486. st->duration = st->nb_frames;
  487. ast->frame_offset= ast->cum_len;
  488. avio_skip(pb, size - 12 * 4);
  489. break;
  490. case MKTAG('s', 't', 'r', 'f'):
  491. /* stream header */
  492. if (!size)
  493. break;
  494. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  495. avio_skip(pb, size);
  496. } else {
  497. uint64_t cur_pos = avio_tell(pb);
  498. if (cur_pos < list_end)
  499. size = FFMIN(size, list_end - cur_pos);
  500. st = s->streams[stream_index];
  501. switch(codec_type) {
  502. case AVMEDIA_TYPE_VIDEO:
  503. if(amv_file_format){
  504. st->codec->width=avih_width;
  505. st->codec->height=avih_height;
  506. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  507. st->codec->codec_id = CODEC_ID_AMV;
  508. avio_skip(pb, size);
  509. break;
  510. }
  511. tag1 = ff_get_bmp_header(pb, st);
  512. if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
  513. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  514. st->codec->codec_tag = tag1;
  515. st->codec->codec_id = CODEC_ID_XSUB;
  516. break;
  517. }
  518. if(size > 10*4 && size<(1<<30) && size < avi->fsize){
  519. st->codec->extradata_size= size - 10*4;
  520. st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  521. if (!st->codec->extradata) {
  522. st->codec->extradata_size= 0;
  523. return AVERROR(ENOMEM);
  524. }
  525. avio_read(pb, st->codec->extradata, st->codec->extradata_size);
  526. }
  527. if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
  528. avio_r8(pb);
  529. /* Extract palette from extradata if bpp <= 8. */
  530. /* This code assumes that extradata contains only palette. */
  531. /* This is true for all paletted codecs implemented in FFmpeg. */
  532. if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
  533. int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
  534. const uint8_t *pal_src;
  535. pal_size = FFMIN(pal_size, st->codec->extradata_size);
  536. pal_src = st->codec->extradata + st->codec->extradata_size - pal_size;
  537. for (i = 0; i < pal_size/4; i++)
  538. ast->pal[i] = 0xFF<<24 | AV_RL32(pal_src+4*i);
  539. ast->has_pal = 1;
  540. }
  541. print_tag("video", tag1, 0);
  542. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  543. st->codec->codec_tag = tag1;
  544. st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
  545. st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
  546. // Support "Resolution 1:1" for Avid AVI Codec
  547. if(tag1 == MKTAG('A', 'V', 'R', 'n') &&
  548. st->codec->extradata_size >= 31 &&
  549. !memcmp(&st->codec->extradata[28], "1:1", 3))
  550. st->codec->codec_id = CODEC_ID_RAWVIDEO;
  551. if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
  552. st->codec->extradata_size+= 9;
  553. st->codec->extradata= av_realloc_f(st->codec->extradata, 1, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  554. if(st->codec->extradata)
  555. memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
  556. }
  557. st->codec->height= FFABS(st->codec->height);
  558. // avio_skip(pb, size - 5 * 4);
  559. break;
  560. case AVMEDIA_TYPE_AUDIO:
  561. ret = ff_get_wav_header(pb, st->codec, size);
  562. if (ret < 0)
  563. return ret;
  564. ast->dshow_block_align= st->codec->block_align;
  565. if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
  566. av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
  567. ast->sample_size= st->codec->block_align;
  568. }
  569. if (size&1) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  570. avio_skip(pb, 1);
  571. /* Force parsing as several audio frames can be in
  572. * one packet and timestamps refer to packet start. */
  573. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  574. /* ADTS header is in extradata, AAC without header must be
  575. * stored as exact frames. Parser not needed and it will
  576. * fail. */
  577. if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
  578. st->need_parsing = AVSTREAM_PARSE_NONE;
  579. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  580. * audio in the header but have Axan as stream_code_tag. */
  581. if (st->codec->stream_codec_tag == AV_RL32("Axan")){
  582. st->codec->codec_id = CODEC_ID_XAN_DPCM;
  583. st->codec->codec_tag = 0;
  584. ast->dshow_block_align = 0;
  585. }
  586. if (amv_file_format){
  587. st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
  588. ast->dshow_block_align = 0;
  589. }
  590. break;
  591. case AVMEDIA_TYPE_SUBTITLE:
  592. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  593. st->request_probe= 1;
  594. break;
  595. default:
  596. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  597. st->codec->codec_id= CODEC_ID_NONE;
  598. st->codec->codec_tag= 0;
  599. avio_skip(pb, size);
  600. break;
  601. }
  602. }
  603. break;
  604. case MKTAG('s', 't', 'r', 'd'):
  605. if (stream_index >= (unsigned)s->nb_streams
  606. || s->streams[stream_index]->codec->extradata_size
  607. || s->streams[stream_index]->codec->codec_tag == MKTAG('H','2','6','4')) {
  608. avio_skip(pb, size);
  609. } else {
  610. uint64_t cur_pos = avio_tell(pb);
  611. if (cur_pos < list_end)
  612. size = FFMIN(size, list_end - cur_pos);
  613. st = s->streams[stream_index];
  614. if(size<(1<<30)){
  615. st->codec->extradata_size= size;
  616. st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  617. if (!st->codec->extradata) {
  618. st->codec->extradata_size= 0;
  619. return AVERROR(ENOMEM);
  620. }
  621. avio_read(pb, st->codec->extradata, st->codec->extradata_size);
  622. }
  623. if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
  624. avio_r8(pb);
  625. }
  626. break;
  627. case MKTAG('i', 'n', 'd', 'x'):
  628. i= avio_tell(pb);
  629. if(pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) && avi->use_odml &&
  630. read_braindead_odml_indx(s, 0) < 0 && s->error_recognition >= FF_ER_EXPLODE)
  631. goto fail;
  632. avio_seek(pb, i+size, SEEK_SET);
  633. break;
  634. case MKTAG('v', 'p', 'r', 'p'):
  635. if(stream_index < (unsigned)s->nb_streams && size > 9*4){
  636. AVRational active, active_aspect;
  637. st = s->streams[stream_index];
  638. avio_rl32(pb);
  639. avio_rl32(pb);
  640. avio_rl32(pb);
  641. avio_rl32(pb);
  642. avio_rl32(pb);
  643. active_aspect.den= avio_rl16(pb);
  644. active_aspect.num= avio_rl16(pb);
  645. active.num = avio_rl32(pb);
  646. active.den = avio_rl32(pb);
  647. avio_rl32(pb); //nbFieldsPerFrame
  648. if(active_aspect.num && active_aspect.den && active.num && active.den){
  649. st->sample_aspect_ratio= av_div_q(active_aspect, active);
  650. //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
  651. }
  652. size -= 9*4;
  653. }
  654. avio_skip(pb, size);
  655. break;
  656. case MKTAG('s', 't', 'r', 'n'):
  657. if(s->nb_streams){
  658. avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
  659. break;
  660. }
  661. default:
  662. if(size > 1000000){
  663. av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
  664. "I will ignore it and try to continue anyway.\n");
  665. if (s->error_recognition & AV_EF_EXPLODE)
  666. goto fail;
  667. avi->movi_list = avio_tell(pb) - 4;
  668. avi->movi_end = avi->fsize;
  669. goto end_of_header;
  670. }
  671. /* skip tag */
  672. size += (size & 1);
  673. avio_skip(pb, size);
  674. break;
  675. }
  676. }
  677. end_of_header:
  678. /* check stream number */
  679. if (stream_index != s->nb_streams - 1) {
  680. fail:
  681. return -1;
  682. }
  683. if(!avi->index_loaded && pb->seekable)
  684. avi_load_index(s);
  685. avi->index_loaded |= 1;
  686. if ((ret = guess_ni_flag(s)) < 0)
  687. return ret;
  688. avi->non_interleaved |= ret | (s->flags & AVFMT_FLAG_SORT_DTS);
  689. for(i=0; i<s->nb_streams; i++){
  690. AVStream *st = s->streams[i];
  691. if(st->nb_index_entries)
  692. break;
  693. }
  694. // DV-in-AVI cannot be non-interleaved, if set this must be
  695. // a mis-detection.
  696. if(avi->dv_demux)
  697. avi->non_interleaved=0;
  698. if(i==s->nb_streams && avi->non_interleaved) {
  699. av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
  700. avi->non_interleaved=0;
  701. }
  702. if(avi->non_interleaved) {
  703. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  704. clean_index(s);
  705. }
  706. ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
  707. ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
  708. return 0;
  709. }
  710. static int read_gab2_sub(AVStream *st, AVPacket *pkt)
  711. {
  712. if (pkt->size >= 7 &&
  713. !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
  714. uint8_t desc[256];
  715. int score = AVPROBE_SCORE_MAX / 2, ret;
  716. AVIStream *ast = st->priv_data;
  717. AVInputFormat *sub_demuxer;
  718. AVRational time_base;
  719. AVIOContext *pb = avio_alloc_context( pkt->data + 7,
  720. pkt->size - 7,
  721. 0, NULL, NULL, NULL, NULL);
  722. AVProbeData pd;
  723. unsigned int desc_len = avio_rl32(pb);
  724. if (desc_len > pb->buf_end - pb->buf_ptr)
  725. goto error;
  726. ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
  727. avio_skip(pb, desc_len - ret);
  728. if (*desc)
  729. av_dict_set(&st->metadata, "title", desc, 0);
  730. avio_rl16(pb); /* flags? */
  731. avio_rl32(pb); /* data size */
  732. pd = (AVProbeData) { .buf = pb->buf_ptr, .buf_size = pb->buf_end - pb->buf_ptr };
  733. if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
  734. goto error;
  735. if (!(ast->sub_ctx = avformat_alloc_context()))
  736. goto error;
  737. ast->sub_ctx->pb = pb;
  738. if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
  739. av_read_packet(ast->sub_ctx, &ast->sub_pkt);
  740. *st->codec = *ast->sub_ctx->streams[0]->codec;
  741. ast->sub_ctx->streams[0]->codec->extradata = NULL;
  742. time_base = ast->sub_ctx->streams[0]->time_base;
  743. avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
  744. }
  745. ast->sub_buffer = pkt->data;
  746. memset(pkt, 0, sizeof(*pkt));
  747. return 1;
  748. error:
  749. av_freep(&pb);
  750. }
  751. return 0;
  752. }
  753. static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
  754. AVPacket *pkt)
  755. {
  756. AVIStream *ast, *next_ast = next_st->priv_data;
  757. int64_t ts, next_ts, ts_min = INT64_MAX;
  758. AVStream *st, *sub_st = NULL;
  759. int i;
  760. next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
  761. AV_TIME_BASE_Q);
  762. for (i=0; i<s->nb_streams; i++) {
  763. st = s->streams[i];
  764. ast = st->priv_data;
  765. if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
  766. ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
  767. if (ts <= next_ts && ts < ts_min) {
  768. ts_min = ts;
  769. sub_st = st;
  770. }
  771. }
  772. }
  773. if (sub_st) {
  774. ast = sub_st->priv_data;
  775. *pkt = ast->sub_pkt;
  776. pkt->stream_index = sub_st->index;
  777. if (av_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
  778. ast->sub_pkt.data = NULL;
  779. }
  780. return sub_st;
  781. }
  782. static int get_stream_idx(int *d){
  783. if( d[0] >= '0' && d[0] <= '9'
  784. && d[1] >= '0' && d[1] <= '9'){
  785. return (d[0] - '0') * 10 + (d[1] - '0');
  786. }else{
  787. return 100; //invalid stream ID
  788. }
  789. }
  790. static int avi_sync(AVFormatContext *s, int exit_early)
  791. {
  792. AVIContext *avi = s->priv_data;
  793. AVIOContext *pb = s->pb;
  794. int n;
  795. unsigned int d[8];
  796. unsigned int size;
  797. int64_t i, sync;
  798. start_sync:
  799. memset(d, -1, sizeof(d));
  800. for(i=sync=avio_tell(pb); !url_feof(pb); i++) {
  801. int j;
  802. for(j=0; j<7; j++)
  803. d[j]= d[j+1];
  804. d[7]= avio_r8(pb);
  805. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  806. n= get_stream_idx(d+2);
  807. //av_log(s, AV_LOG_DEBUG, "%X %X %X %X %X %X %X %X %"PRId64" %d %d\n", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
  808. if(i + (uint64_t)size > avi->fsize || d[0] > 127)
  809. continue;
  810. //parse ix##
  811. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  812. //parse JUNK
  813. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  814. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  815. avio_skip(pb, size);
  816. //av_log(s, AV_LOG_DEBUG, "SKIP\n");
  817. goto start_sync;
  818. }
  819. //parse stray LIST
  820. if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
  821. avio_skip(pb, 4);
  822. goto start_sync;
  823. }
  824. n = avi->dv_demux ? 0 : get_stream_idx(d);
  825. if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
  826. continue;
  827. //detect ##ix chunk and skip
  828. if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
  829. avio_skip(pb, size);
  830. goto start_sync;
  831. }
  832. //parse ##dc/##wb
  833. if(n < s->nb_streams){
  834. AVStream *st;
  835. AVIStream *ast;
  836. st = s->streams[n];
  837. ast = st->priv_data;
  838. if (!ast) {
  839. av_log(s, AV_LOG_WARNING, "Skiping foreign stream %d packet\n", n);
  840. continue;
  841. }
  842. if(s->nb_streams>=2){
  843. AVStream *st1 = s->streams[1];
  844. AVIStream *ast1= st1->priv_data;
  845. //workaround for broken small-file-bug402.avi
  846. if( d[2] == 'w' && d[3] == 'b'
  847. && n==0
  848. && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
  849. && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
  850. && ast->prefix == 'd'*256+'c'
  851. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  852. ){
  853. n=1;
  854. st = st1;
  855. ast = ast1;
  856. av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
  857. }
  858. }
  859. if (!avi->dv_demux &&
  860. ((st->discard >= AVDISCARD_DEFAULT && size==0) /* ||
  861. //FIXME needs a little reordering
  862. (st->discard >= AVDISCARD_NONKEY &&
  863. !(pkt->flags & AV_PKT_FLAG_KEY)) */
  864. || st->discard >= AVDISCARD_ALL)) {
  865. if (!exit_early) {
  866. ast->frame_offset += get_duration(ast, size);
  867. avio_skip(pb, size);
  868. goto start_sync;
  869. }
  870. }
  871. if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
  872. int k = avio_r8(pb);
  873. int last = (k + avio_r8(pb) - 1) & 0xFF;
  874. avio_rl16(pb); //flags
  875. for (; k <= last; k++)
  876. ast->pal[k] = 0xFF<<24 | avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
  877. ast->has_pal= 1;
  878. goto start_sync;
  879. } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  880. d[2]*256+d[3] == ast->prefix /*||
  881. (d[2] == 'd' && d[3] == 'c') ||
  882. (d[2] == 'w' && d[3] == 'b')*/) {
  883. if (exit_early)
  884. return 0;
  885. //av_log(s, AV_LOG_DEBUG, "OK\n");
  886. if(d[2]*256+d[3] == ast->prefix)
  887. ast->prefix_count++;
  888. else{
  889. ast->prefix= d[2]*256+d[3];
  890. ast->prefix_count= 0;
  891. }
  892. avi->stream_index= n;
  893. ast->packet_size= size + 8;
  894. ast->remaining= size;
  895. if(size || !ast->sample_size){
  896. uint64_t pos= avio_tell(pb) - 8;
  897. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  898. av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
  899. }
  900. }
  901. return 0;
  902. }
  903. }
  904. }
  905. if(pb->error)
  906. return pb->error;
  907. return AVERROR_EOF;
  908. }
  909. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  910. {
  911. AVIContext *avi = s->priv_data;
  912. AVIOContext *pb = s->pb;
  913. int err;
  914. void* dstr;
  915. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  916. int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
  917. if (size >= 0)
  918. return size;
  919. else
  920. goto resync;
  921. }
  922. if(avi->non_interleaved){
  923. int best_stream_index = 0;
  924. AVStream *best_st= NULL;
  925. AVIStream *best_ast;
  926. int64_t best_ts= INT64_MAX;
  927. int i;
  928. for(i=0; i<s->nb_streams; i++){
  929. AVStream *st = s->streams[i];
  930. AVIStream *ast = st->priv_data;
  931. int64_t ts= ast->frame_offset;
  932. int64_t last_ts;
  933. if(!st->nb_index_entries)
  934. continue;
  935. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  936. if(!ast->remaining && ts > last_ts)
  937. continue;
  938. ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
  939. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
  940. if(ts < best_ts){
  941. best_ts= ts;
  942. best_st= st;
  943. best_stream_index= i;
  944. }
  945. }
  946. if(!best_st)
  947. return AVERROR_EOF;
  948. best_ast = best_st->priv_data;
  949. best_ts = best_ast->frame_offset;
  950. if(best_ast->remaining)
  951. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  952. else{
  953. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  954. if(i>=0)
  955. best_ast->frame_offset= best_st->index_entries[i].timestamp;
  956. }
  957. // av_log(s, AV_LOG_DEBUG, "%d\n", i);
  958. if(i>=0){
  959. int64_t pos= best_st->index_entries[i].pos;
  960. pos += best_ast->packet_size - best_ast->remaining;
  961. if(avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
  962. return AVERROR_EOF;
  963. // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  964. assert(best_ast->remaining <= best_ast->packet_size);
  965. avi->stream_index= best_stream_index;
  966. if(!best_ast->remaining)
  967. best_ast->packet_size=
  968. best_ast->remaining= best_st->index_entries[i].size;
  969. }
  970. else
  971. return AVERROR_EOF;
  972. }
  973. resync:
  974. if(avi->stream_index >= 0){
  975. AVStream *st= s->streams[ avi->stream_index ];
  976. AVIStream *ast= st->priv_data;
  977. int size, err;
  978. if(get_subtitle_pkt(s, st, pkt))
  979. return 0;
  980. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  981. size= INT_MAX;
  982. else if(ast->sample_size < 32)
  983. // arbitrary multiplier to avoid tiny packets for raw PCM data
  984. size= 1024*ast->sample_size;
  985. else
  986. size= ast->sample_size;
  987. if(size > ast->remaining)
  988. size= ast->remaining;
  989. avi->last_pkt_pos= avio_tell(pb);
  990. err= av_get_packet(pb, pkt, size);
  991. if(err<0)
  992. return err;
  993. if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
  994. uint8_t *pal;
  995. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  996. if(!pal){
  997. av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n");
  998. }else{
  999. memcpy(pal, ast->pal, AVPALETTE_SIZE);
  1000. ast->has_pal = 0;
  1001. }
  1002. }
  1003. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1004. dstr = pkt->destruct;
  1005. size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
  1006. pkt->data, pkt->size, pkt->pos);
  1007. pkt->destruct = dstr;
  1008. pkt->flags |= AV_PKT_FLAG_KEY;
  1009. if (size < 0)
  1010. av_free_packet(pkt);
  1011. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
  1012. && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
  1013. ast->frame_offset++;
  1014. avi->stream_index = -1;
  1015. ast->remaining = 0;
  1016. goto resync;
  1017. } else {
  1018. /* XXX: How to handle B-frames in AVI? */
  1019. pkt->dts = ast->frame_offset;
  1020. // pkt->dts += ast->start;
  1021. if(ast->sample_size)
  1022. pkt->dts /= ast->sample_size;
  1023. //av_log(s, AV_LOG_DEBUG, "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d base:%d st:%d size:%d\n", pkt->dts, ast->frame_offset, ast->scale, ast->rate, ast->sample_size, AV_TIME_BASE, avi->stream_index, size);
  1024. pkt->stream_index = avi->stream_index;
  1025. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1026. AVIndexEntry *e;
  1027. int index;
  1028. assert(st->index_entries);
  1029. index= av_index_search_timestamp(st, ast->frame_offset, 0);
  1030. e= &st->index_entries[index];
  1031. if(index >= 0 && e->timestamp == ast->frame_offset){
  1032. if (index == st->nb_index_entries-1){
  1033. int key=1;
  1034. int i;
  1035. uint32_t state=-1;
  1036. for(i=0; i<FFMIN(size,256); i++){
  1037. if(st->codec->codec_id == CODEC_ID_MPEG4){
  1038. if(state == 0x1B6){
  1039. key= !(pkt->data[i]&0xC0);
  1040. break;
  1041. }
  1042. }else
  1043. break;
  1044. state= (state<<8) + pkt->data[i];
  1045. }
  1046. if(!key)
  1047. e->flags &= ~AVINDEX_KEYFRAME;
  1048. }
  1049. if (e->flags & AVINDEX_KEYFRAME)
  1050. pkt->flags |= AV_PKT_FLAG_KEY;
  1051. }
  1052. } else {
  1053. pkt->flags |= AV_PKT_FLAG_KEY;
  1054. }
  1055. ast->frame_offset += get_duration(ast, pkt->size);
  1056. }
  1057. ast->remaining -= err;
  1058. if(!ast->remaining){
  1059. avi->stream_index= -1;
  1060. ast->packet_size= 0;
  1061. }
  1062. if(!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos){
  1063. av_free_packet(pkt);
  1064. goto resync;
  1065. }
  1066. ast->seek_pos= 0;
  1067. if(!avi->non_interleaved && st->nb_index_entries>1 && avi->index_loaded>1){
  1068. int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
  1069. if(avi->dts_max - dts > 2*AV_TIME_BASE){
  1070. avi->non_interleaved= 1;
  1071. av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
  1072. }else if(avi->dts_max < dts)
  1073. avi->dts_max = dts;
  1074. }
  1075. return 0;
  1076. }
  1077. if ((err = avi_sync(s, 0)) < 0)
  1078. return err;
  1079. goto resync;
  1080. }
  1081. /* XXX: We make the implicit supposition that the positions are sorted
  1082. for each stream. */
  1083. static int avi_read_idx1(AVFormatContext *s, int size)
  1084. {
  1085. AVIContext *avi = s->priv_data;
  1086. AVIOContext *pb = s->pb;
  1087. int nb_index_entries, i;
  1088. AVStream *st;
  1089. AVIStream *ast;
  1090. unsigned int index, tag, flags, pos, len, first_packet = 1;
  1091. unsigned last_pos= -1;
  1092. int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
  1093. nb_index_entries = size / 16;
  1094. if (nb_index_entries <= 0)
  1095. return -1;
  1096. idx1_pos = avio_tell(pb);
  1097. avio_seek(pb, avi->movi_list+4, SEEK_SET);
  1098. if (avi_sync(s, 1) == 0) {
  1099. first_packet_pos = avio_tell(pb) - 8;
  1100. }
  1101. avi->stream_index = -1;
  1102. avio_seek(pb, idx1_pos, SEEK_SET);
  1103. if (s->nb_streams == 1 && s->streams[0]->codec->codec_tag == AV_RL32("MMES")){
  1104. first_packet_pos = 0;
  1105. data_offset = avi->movi_list;
  1106. }
  1107. /* Read the entries and sort them in each stream component. */
  1108. for(i = 0; i < nb_index_entries; i++) {
  1109. if(url_feof(pb))
  1110. return -1;
  1111. tag = avio_rl32(pb);
  1112. flags = avio_rl32(pb);
  1113. pos = avio_rl32(pb);
  1114. len = avio_rl32(pb);
  1115. av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  1116. i, tag, flags, pos, len);
  1117. index = ((tag & 0xff) - '0') * 10;
  1118. index += ((tag >> 8) & 0xff) - '0';
  1119. if (index >= s->nb_streams)
  1120. continue;
  1121. st = s->streams[index];
  1122. ast = st->priv_data;
  1123. if (first_packet && first_packet_pos) {
  1124. data_offset = first_packet_pos - pos;
  1125. first_packet = 0;
  1126. }
  1127. pos += data_offset;
  1128. av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  1129. if(last_pos == pos)
  1130. avi->non_interleaved= 1;
  1131. else if(len || !ast->sample_size)
  1132. av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  1133. ast->cum_len += get_duration(ast, len);
  1134. last_pos= pos;
  1135. }
  1136. return 0;
  1137. }
  1138. /* Scan the index and consider any file with streams more than
  1139. * 2 seconds or 64MB apart non-interleaved. */
  1140. static int check_stream_max_drift(AVFormatContext *s)
  1141. {
  1142. int64_t min_pos, pos;
  1143. int i;
  1144. int *idx = av_malloc(s->nb_streams * sizeof(*idx));
  1145. if (!idx)
  1146. return AVERROR(ENOMEM);
  1147. else
  1148. memset(idx, 0, s->nb_streams * sizeof(*idx));
  1149. for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
  1150. int64_t max_dts = INT64_MIN / 2;
  1151. int64_t min_dts = INT64_MAX / 2;
  1152. int64_t max_buffer = 0;
  1153. min_pos = INT64_MAX;
  1154. for (i = 0; i < s->nb_streams; i++) {
  1155. AVStream *st = s->streams[i];
  1156. AVIStream *ast = st->priv_data;
  1157. int n = st->nb_index_entries;
  1158. while (idx[i] < n && st->index_entries[idx[i]].pos < pos)
  1159. idx[i]++;
  1160. if (idx[i] < n) {
  1161. int64_t dts;
  1162. dts = av_rescale_q(st->index_entries[idx[i]].timestamp /
  1163. FFMAX(ast->sample_size, 1),
  1164. st->time_base, AV_TIME_BASE_Q);
  1165. min_dts = FFMIN(min_dts, dts);
  1166. min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
  1167. }
  1168. }
  1169. for (i = 0; i < s->nb_streams; i++) {
  1170. AVStream *st = s->streams[i];
  1171. AVIStream *ast = st->priv_data;
  1172. if (idx[i] && min_dts != INT64_MAX / 2) {
  1173. int64_t dts;
  1174. dts = av_rescale_q(st->index_entries[idx[i] - 1].timestamp /
  1175. FFMAX(ast->sample_size, 1),
  1176. st->time_base, AV_TIME_BASE_Q);
  1177. max_dts = FFMAX(max_dts, dts);
  1178. max_buffer = FFMAX(max_buffer,
  1179. av_rescale(dts - min_dts,
  1180. st->codec->bit_rate,
  1181. AV_TIME_BASE));
  1182. }
  1183. }
  1184. if (max_dts - min_dts > 2 * AV_TIME_BASE ||
  1185. max_buffer > 1024 * 1024 * 8 * 8) {
  1186. av_free(idx);
  1187. return 1;
  1188. }
  1189. }
  1190. av_free(idx);
  1191. return 0;
  1192. }
  1193. static int guess_ni_flag(AVFormatContext *s){
  1194. int i;
  1195. int64_t last_start=0;
  1196. int64_t first_end= INT64_MAX;
  1197. int64_t oldpos= avio_tell(s->pb);
  1198. for(i=0; i<s->nb_streams; i++){
  1199. AVStream *st = s->streams[i];
  1200. int n= st->nb_index_entries;
  1201. unsigned int size;
  1202. if(n <= 0)
  1203. continue;
  1204. if(n >= 2){
  1205. int64_t pos= st->index_entries[0].pos;
  1206. avio_seek(s->pb, pos + 4, SEEK_SET);
  1207. size= avio_rl32(s->pb);
  1208. if(pos + size > st->index_entries[1].pos)
  1209. last_start= INT64_MAX;
  1210. }
  1211. if(st->index_entries[0].pos > last_start)
  1212. last_start= st->index_entries[0].pos;
  1213. if(st->index_entries[n-1].pos < first_end)
  1214. first_end= st->index_entries[n-1].pos;
  1215. }
  1216. avio_seek(s->pb, oldpos, SEEK_SET);
  1217. if (last_start > first_end)
  1218. return 1;
  1219. return check_stream_max_drift(s);
  1220. }
  1221. static int avi_load_index(AVFormatContext *s)
  1222. {
  1223. AVIContext *avi = s->priv_data;
  1224. AVIOContext *pb = s->pb;
  1225. uint32_t tag, size;
  1226. int64_t pos= avio_tell(pb);
  1227. int ret = -1;
  1228. if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
  1229. goto the_end; // maybe truncated file
  1230. av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
  1231. for(;;) {
  1232. if (url_feof(pb))
  1233. break;
  1234. tag = avio_rl32(pb);
  1235. size = avio_rl32(pb);
  1236. av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
  1237. tag & 0xff,
  1238. (tag >> 8) & 0xff,
  1239. (tag >> 16) & 0xff,
  1240. (tag >> 24) & 0xff,
  1241. size);
  1242. if (tag == MKTAG('i', 'd', 'x', '1') &&
  1243. avi_read_idx1(s, size) >= 0) {
  1244. avi->index_loaded=2;
  1245. ret = 0;
  1246. break;
  1247. }
  1248. size += (size & 1);
  1249. if (avio_skip(pb, size) < 0)
  1250. break; // something is wrong here
  1251. }
  1252. the_end:
  1253. avio_seek(pb, pos, SEEK_SET);
  1254. return ret;
  1255. }
  1256. static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
  1257. {
  1258. AVIStream *ast2 = st2->priv_data;
  1259. int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
  1260. av_free_packet(&ast2->sub_pkt);
  1261. if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
  1262. avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
  1263. av_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
  1264. }
  1265. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  1266. {
  1267. AVIContext *avi = s->priv_data;
  1268. AVStream *st;
  1269. int i, index;
  1270. int64_t pos, pos_min;
  1271. AVIStream *ast;
  1272. /* Does not matter which stream is requested dv in avi has the
  1273. * stream information in the first video stream.
  1274. */
  1275. if (avi->dv_demux)
  1276. stream_index = 0;
  1277. if (!avi->index_loaded) {
  1278. /* we only load the index on demand */
  1279. avi_load_index(s);
  1280. avi->index_loaded |= 1;
  1281. }
  1282. st = s->streams[stream_index];
  1283. ast= st->priv_data;
  1284. index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
  1285. if(index<0)
  1286. return -1;
  1287. /* find the position */
  1288. pos = st->index_entries[index].pos;
  1289. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  1290. // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  1291. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1292. /* One and only one real stream for DV in AVI, and it has video */
  1293. /* offsets. Calling with other stream indexes should have failed */
  1294. /* the av_index_search_timestamp call above. */
  1295. if(avio_seek(s->pb, pos, SEEK_SET) < 0)
  1296. return -1;
  1297. /* Feed the DV video stream version of the timestamp to the */
  1298. /* DV demux so it can synthesize correct timestamps. */
  1299. dv_offset_reset(avi->dv_demux, timestamp);
  1300. avi->stream_index= -1;
  1301. return 0;
  1302. }
  1303. pos_min= pos;
  1304. for(i = 0; i < s->nb_streams; i++) {
  1305. AVStream *st2 = s->streams[i];
  1306. AVIStream *ast2 = st2->priv_data;
  1307. ast2->packet_size=
  1308. ast2->remaining= 0;
  1309. if (ast2->sub_ctx) {
  1310. seek_subtitle(st, st2, timestamp);
  1311. continue;
  1312. }
  1313. if (st2->nb_index_entries <= 0)
  1314. continue;
  1315. // assert(st2->codec->block_align);
  1316. assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
  1317. index = av_index_search_timestamp(
  1318. st2,
  1319. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  1320. flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
  1321. if(index<0)
  1322. index=0;
  1323. ast2->seek_pos= st2->index_entries[index].pos;
  1324. pos_min= FFMIN(pos_min,ast2->seek_pos);
  1325. }
  1326. for(i = 0; i < s->nb_streams; i++) {
  1327. AVStream *st2 = s->streams[i];
  1328. AVIStream *ast2 = st2->priv_data;
  1329. if (ast2->sub_ctx || st2->nb_index_entries <= 0)
  1330. continue;
  1331. index = av_index_search_timestamp(
  1332. st2,
  1333. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  1334. flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
  1335. if(index<0)
  1336. index=0;
  1337. while(!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)
  1338. index--;
  1339. ast2->frame_offset = st2->index_entries[index].timestamp;
  1340. }
  1341. /* do the seek */
  1342. if (avio_seek(s->pb, pos_min, SEEK_SET) < 0)
  1343. return -1;
  1344. avi->stream_index= -1;
  1345. avi->dts_max= INT_MIN;
  1346. return 0;
  1347. }
  1348. static int avi_read_close(AVFormatContext *s)
  1349. {
  1350. int i;
  1351. AVIContext *avi = s->priv_data;
  1352. for(i=0;i<s->nb_streams;i++) {
  1353. AVStream *st = s->streams[i];
  1354. AVIStream *ast = st->priv_data;
  1355. if (ast) {
  1356. if (ast->sub_ctx) {
  1357. av_freep(&ast->sub_ctx->pb);
  1358. avformat_close_input(&ast->sub_ctx);
  1359. }
  1360. av_free(ast->sub_buffer);
  1361. av_free_packet(&ast->sub_pkt);
  1362. }
  1363. }
  1364. av_free(avi->dv_demux);
  1365. return 0;
  1366. }
  1367. static int avi_probe(AVProbeData *p)
  1368. {
  1369. int i;
  1370. /* check file header */
  1371. for(i=0; avi_headers[i][0]; i++)
  1372. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  1373. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  1374. return AVPROBE_SCORE_MAX;
  1375. return 0;
  1376. }
  1377. AVInputFormat ff_avi_demuxer = {
  1378. .name = "avi",
  1379. .long_name = NULL_IF_CONFIG_SMALL("AVI format"),
  1380. .priv_data_size = sizeof(AVIContext),
  1381. .read_probe = avi_probe,
  1382. .read_header = avi_read_header,
  1383. .read_packet = avi_read_packet,
  1384. .read_close = avi_read_close,
  1385. .read_seek = avi_read_seek,
  1386. .priv_class = &demuxer_class,
  1387. };