avidec.c 49 KB

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