avidec.c 50 KB

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