avidec.c 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471
  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, 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= avio_size(s->pb);
  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)
  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 = avio_size(pb);
  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);
  604. }
  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. avi->movi_list = avio_tell(pb) - 4;
  639. avi->movi_end = avio_size(pb);
  640. goto end_of_header;
  641. }
  642. /* skip tag */
  643. size += (size & 1);
  644. avio_skip(pb, size);
  645. break;
  646. }
  647. }
  648. end_of_header:
  649. /* check stream number */
  650. if (stream_index != s->nb_streams - 1) {
  651. fail:
  652. return -1;
  653. }
  654. if(!avi->index_loaded && pb->seekable)
  655. avi_load_index(s);
  656. avi->index_loaded = 1;
  657. avi->non_interleaved |= guess_ni_flag(s) | (s->flags & AVFMT_FLAG_SORT_DTS);
  658. for(i=0; i<s->nb_streams; i++){
  659. AVStream *st = s->streams[i];
  660. if(st->nb_index_entries)
  661. break;
  662. }
  663. // DV-in-AVI cannot be non-interleaved, if set this must be
  664. // a mis-detection.
  665. if(avi->dv_demux)
  666. avi->non_interleaved=0;
  667. if(i==s->nb_streams && avi->non_interleaved) {
  668. av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
  669. avi->non_interleaved=0;
  670. }
  671. if(avi->non_interleaved) {
  672. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  673. clean_index(s);
  674. }
  675. ff_metadata_conv_ctx(s, NULL, ff_avi_metadata_conv);
  676. return 0;
  677. }
  678. static int read_gab2_sub(AVStream *st, AVPacket *pkt) {
  679. if (!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data+5) == 2) {
  680. uint8_t desc[256];
  681. int score = AVPROBE_SCORE_MAX / 2, ret;
  682. AVIStream *ast = st->priv_data;
  683. AVInputFormat *sub_demuxer;
  684. AVRational time_base;
  685. AVIOContext *pb = avio_alloc_context( pkt->data + 7,
  686. pkt->size - 7,
  687. 0, NULL, NULL, NULL, NULL);
  688. AVProbeData pd;
  689. unsigned int desc_len = avio_rl32(pb);
  690. if (desc_len > pb->buf_end - pb->buf_ptr)
  691. goto error;
  692. ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
  693. avio_skip(pb, desc_len - ret);
  694. if (*desc)
  695. av_dict_set(&st->metadata, "title", desc, 0);
  696. avio_rl16(pb); /* flags? */
  697. avio_rl32(pb); /* data size */
  698. pd = (AVProbeData) { .buf = pb->buf_ptr, .buf_size = pb->buf_end - pb->buf_ptr };
  699. if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
  700. goto error;
  701. if (!(ast->sub_ctx = avformat_alloc_context()))
  702. goto error;
  703. ast->sub_ctx->pb = pb;
  704. if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
  705. av_read_packet(ast->sub_ctx, &ast->sub_pkt);
  706. *st->codec = *ast->sub_ctx->streams[0]->codec;
  707. ast->sub_ctx->streams[0]->codec->extradata = NULL;
  708. time_base = ast->sub_ctx->streams[0]->time_base;
  709. av_set_pts_info(st, 64, time_base.num, time_base.den);
  710. }
  711. ast->sub_buffer = pkt->data;
  712. memset(pkt, 0, sizeof(*pkt));
  713. return 1;
  714. error:
  715. av_freep(&pb);
  716. }
  717. return 0;
  718. }
  719. static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
  720. AVPacket *pkt)
  721. {
  722. AVIStream *ast, *next_ast = next_st->priv_data;
  723. int64_t ts, next_ts, ts_min = INT64_MAX;
  724. AVStream *st, *sub_st = NULL;
  725. int i;
  726. next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
  727. AV_TIME_BASE_Q);
  728. for (i=0; i<s->nb_streams; i++) {
  729. st = s->streams[i];
  730. ast = st->priv_data;
  731. if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
  732. ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
  733. if (ts <= next_ts && ts < ts_min) {
  734. ts_min = ts;
  735. sub_st = st;
  736. }
  737. }
  738. }
  739. if (sub_st) {
  740. ast = sub_st->priv_data;
  741. *pkt = ast->sub_pkt;
  742. pkt->stream_index = sub_st->index;
  743. if (av_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
  744. ast->sub_pkt.data = NULL;
  745. }
  746. return sub_st;
  747. }
  748. static int get_stream_idx(int *d){
  749. if( d[0] >= '0' && d[0] <= '9'
  750. && d[1] >= '0' && d[1] <= '9'){
  751. return (d[0] - '0') * 10 + (d[1] - '0');
  752. }else{
  753. return 100; //invalid stream ID
  754. }
  755. }
  756. static int avi_sync(AVFormatContext *s, int exit_early)
  757. {
  758. AVIContext *avi = s->priv_data;
  759. AVIOContext *pb = s->pb;
  760. int n, d[8];
  761. unsigned int size;
  762. int64_t i, sync;
  763. start_sync:
  764. memset(d, -1, sizeof(int)*8);
  765. for(i=sync=avio_tell(pb); !url_feof(pb); i++) {
  766. int j;
  767. for(j=0; j<7; j++)
  768. d[j]= d[j+1];
  769. d[7]= avio_r8(pb);
  770. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  771. n= get_stream_idx(d+2);
  772. //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);
  773. if(i + (uint64_t)size > avi->fsize || d[0]<0)
  774. continue;
  775. //parse ix##
  776. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  777. //parse JUNK
  778. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  779. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  780. avio_skip(pb, size);
  781. //av_log(s, AV_LOG_DEBUG, "SKIP\n");
  782. goto start_sync;
  783. }
  784. //parse stray LIST
  785. if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
  786. avio_skip(pb, 4);
  787. goto start_sync;
  788. }
  789. n= get_stream_idx(d);
  790. if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
  791. continue;
  792. //detect ##ix chunk and skip
  793. if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
  794. avio_skip(pb, size);
  795. goto start_sync;
  796. }
  797. //parse ##dc/##wb
  798. if(n < s->nb_streams){
  799. AVStream *st;
  800. AVIStream *ast;
  801. st = s->streams[n];
  802. ast = st->priv_data;
  803. if(s->nb_streams>=2){
  804. AVStream *st1 = s->streams[1];
  805. AVIStream *ast1= st1->priv_data;
  806. //workaround for broken small-file-bug402.avi
  807. if( d[2] == 'w' && d[3] == 'b'
  808. && n==0
  809. && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
  810. && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
  811. && ast->prefix == 'd'*256+'c'
  812. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  813. ){
  814. n=1;
  815. st = st1;
  816. ast = ast1;
  817. av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
  818. }
  819. }
  820. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  821. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  822. || st->discard >= AVDISCARD_ALL){
  823. if (!exit_early) {
  824. ast->frame_offset += get_duration(ast, size);
  825. }
  826. avio_skip(pb, size);
  827. goto start_sync;
  828. }
  829. if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
  830. int k = avio_r8(pb);
  831. int last = (k + avio_r8(pb) - 1) & 0xFF;
  832. avio_rl16(pb); //flags
  833. for (; k <= last; k++)
  834. ast->pal[k] = avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
  835. ast->has_pal= 1;
  836. goto start_sync;
  837. } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  838. d[2]*256+d[3] == ast->prefix /*||
  839. (d[2] == 'd' && d[3] == 'c') ||
  840. (d[2] == 'w' && d[3] == 'b')*/) {
  841. if (exit_early)
  842. return 0;
  843. //av_log(s, AV_LOG_DEBUG, "OK\n");
  844. if(d[2]*256+d[3] == ast->prefix)
  845. ast->prefix_count++;
  846. else{
  847. ast->prefix= d[2]*256+d[3];
  848. ast->prefix_count= 0;
  849. }
  850. avi->stream_index= n;
  851. ast->packet_size= size + 8;
  852. ast->remaining= size;
  853. if(size || !ast->sample_size){
  854. uint64_t pos= avio_tell(pb) - 8;
  855. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  856. av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
  857. }
  858. }
  859. return 0;
  860. }
  861. }
  862. }
  863. return AVERROR_EOF;
  864. }
  865. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  866. {
  867. AVIContext *avi = s->priv_data;
  868. AVIOContext *pb = s->pb;
  869. int err;
  870. void* dstr;
  871. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  872. int size = dv_get_packet(avi->dv_demux, pkt);
  873. if (size >= 0)
  874. return size;
  875. }
  876. if(avi->non_interleaved){
  877. int best_stream_index = 0;
  878. AVStream *best_st= NULL;
  879. AVIStream *best_ast;
  880. int64_t best_ts= INT64_MAX;
  881. int i;
  882. for(i=0; i<s->nb_streams; i++){
  883. AVStream *st = s->streams[i];
  884. AVIStream *ast = st->priv_data;
  885. int64_t ts= ast->frame_offset;
  886. int64_t last_ts;
  887. if(!st->nb_index_entries)
  888. continue;
  889. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  890. if(!ast->remaining && ts > last_ts)
  891. continue;
  892. ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
  893. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
  894. if(ts < best_ts){
  895. best_ts= ts;
  896. best_st= st;
  897. best_stream_index= i;
  898. }
  899. }
  900. if(!best_st)
  901. return -1;
  902. best_ast = best_st->priv_data;
  903. best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
  904. if(best_ast->remaining)
  905. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  906. else{
  907. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  908. if(i>=0)
  909. best_ast->frame_offset= best_st->index_entries[i].timestamp;
  910. }
  911. // av_log(s, AV_LOG_DEBUG, "%d\n", i);
  912. if(i>=0){
  913. int64_t pos= best_st->index_entries[i].pos;
  914. pos += best_ast->packet_size - best_ast->remaining;
  915. avio_seek(s->pb, pos + 8, SEEK_SET);
  916. // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  917. assert(best_ast->remaining <= best_ast->packet_size);
  918. avi->stream_index= best_stream_index;
  919. if(!best_ast->remaining)
  920. best_ast->packet_size=
  921. best_ast->remaining= best_st->index_entries[i].size;
  922. }
  923. }
  924. resync:
  925. if(avi->stream_index >= 0){
  926. AVStream *st= s->streams[ avi->stream_index ];
  927. AVIStream *ast= st->priv_data;
  928. int size, err;
  929. if(get_subtitle_pkt(s, st, pkt))
  930. return 0;
  931. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  932. size= INT_MAX;
  933. else if(ast->sample_size < 32)
  934. // arbitrary multiplier to avoid tiny packets for raw PCM data
  935. size= 1024*ast->sample_size;
  936. else
  937. size= ast->sample_size;
  938. if(size > ast->remaining)
  939. size= ast->remaining;
  940. avi->last_pkt_pos= avio_tell(pb);
  941. err= av_get_packet(pb, pkt, size);
  942. if(err<0)
  943. return err;
  944. if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
  945. uint8_t *pal;
  946. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  947. if(!pal){
  948. av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n");
  949. }else{
  950. memcpy(pal, ast->pal, AVPALETTE_SIZE);
  951. ast->has_pal = 0;
  952. }
  953. }
  954. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  955. dstr = pkt->destruct;
  956. size = dv_produce_packet(avi->dv_demux, pkt,
  957. pkt->data, pkt->size, pkt->pos);
  958. pkt->destruct = dstr;
  959. pkt->flags |= AV_PKT_FLAG_KEY;
  960. if (size < 0)
  961. av_free_packet(pkt);
  962. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
  963. && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
  964. ast->frame_offset++;
  965. avi->stream_index = -1;
  966. ast->remaining = 0;
  967. goto resync;
  968. } else {
  969. /* XXX: How to handle B-frames in AVI? */
  970. pkt->dts = ast->frame_offset;
  971. // pkt->dts += ast->start;
  972. if(ast->sample_size)
  973. pkt->dts /= ast->sample_size;
  974. //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);
  975. pkt->stream_index = avi->stream_index;
  976. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  977. AVIndexEntry *e;
  978. int index;
  979. assert(st->index_entries);
  980. index= av_index_search_timestamp(st, ast->frame_offset, 0);
  981. e= &st->index_entries[index];
  982. if(index >= 0 && e->timestamp == ast->frame_offset){
  983. if (index == st->nb_index_entries-1){
  984. int key=1;
  985. int i;
  986. uint32_t state=-1;
  987. for(i=0; i<FFMIN(size,256); i++){
  988. if(st->codec->codec_id == CODEC_ID_MPEG4){
  989. if(state == 0x1B6){
  990. key= !(pkt->data[i]&0xC0);
  991. break;
  992. }
  993. }else
  994. break;
  995. state= (state<<8) + pkt->data[i];
  996. }
  997. if(!key)
  998. e->flags &= ~AVINDEX_KEYFRAME;
  999. }
  1000. if (e->flags & AVINDEX_KEYFRAME)
  1001. pkt->flags |= AV_PKT_FLAG_KEY;
  1002. }
  1003. } else {
  1004. pkt->flags |= AV_PKT_FLAG_KEY;
  1005. }
  1006. ast->frame_offset += get_duration(ast, pkt->size);
  1007. }
  1008. ast->remaining -= size;
  1009. if(!ast->remaining){
  1010. avi->stream_index= -1;
  1011. ast->packet_size= 0;
  1012. }
  1013. if(!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos){
  1014. av_free_packet(pkt);
  1015. goto resync;
  1016. }
  1017. ast->seek_pos= 0;
  1018. if(!avi->non_interleaved && st->nb_index_entries>1){
  1019. int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
  1020. if(avi->dts_max - dts > 2*AV_TIME_BASE){
  1021. avi->non_interleaved= 1;
  1022. av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
  1023. }else if(avi->dts_max < dts)
  1024. avi->dts_max = dts;
  1025. }
  1026. return size;
  1027. }
  1028. if ((err = avi_sync(s, 0)) < 0)
  1029. return err;
  1030. goto resync;
  1031. }
  1032. /* XXX: We make the implicit supposition that the positions are sorted
  1033. for each stream. */
  1034. static int avi_read_idx1(AVFormatContext *s, int size)
  1035. {
  1036. AVIContext *avi = s->priv_data;
  1037. AVIOContext *pb = s->pb;
  1038. int nb_index_entries, i;
  1039. AVStream *st;
  1040. AVIStream *ast;
  1041. unsigned int index, tag, flags, pos, len, first_packet = 1;
  1042. unsigned last_pos= -1;
  1043. int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
  1044. nb_index_entries = size / 16;
  1045. if (nb_index_entries <= 0)
  1046. return -1;
  1047. idx1_pos = avio_tell(pb);
  1048. avio_seek(pb, avi->movi_list+4, SEEK_SET);
  1049. if (avi_sync(s, 1) == 0) {
  1050. first_packet_pos = avio_tell(pb) - 8;
  1051. }
  1052. avi->stream_index = -1;
  1053. avio_seek(pb, idx1_pos, SEEK_SET);
  1054. /* Read the entries and sort them in each stream component. */
  1055. for(i = 0; i < nb_index_entries; i++) {
  1056. tag = avio_rl32(pb);
  1057. flags = avio_rl32(pb);
  1058. pos = avio_rl32(pb);
  1059. len = avio_rl32(pb);
  1060. av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  1061. i, tag, flags, pos, len);
  1062. index = ((tag & 0xff) - '0') * 10;
  1063. index += ((tag >> 8) & 0xff) - '0';
  1064. if (index >= s->nb_streams)
  1065. continue;
  1066. st = s->streams[index];
  1067. ast = st->priv_data;
  1068. if(first_packet && first_packet_pos && len) {
  1069. data_offset = first_packet_pos - pos;
  1070. first_packet = 0;
  1071. }
  1072. pos += data_offset;
  1073. av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  1074. if(url_feof(pb))
  1075. return -1;
  1076. if(last_pos == pos)
  1077. avi->non_interleaved= 1;
  1078. else if(len || !ast->sample_size)
  1079. av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  1080. ast->cum_len += get_duration(ast, len);
  1081. last_pos= pos;
  1082. }
  1083. return 0;
  1084. }
  1085. static int guess_ni_flag(AVFormatContext *s){
  1086. int i;
  1087. int64_t last_start=0;
  1088. int64_t first_end= INT64_MAX;
  1089. int64_t oldpos= avio_tell(s->pb);
  1090. for(i=0; i<s->nb_streams; i++){
  1091. AVStream *st = s->streams[i];
  1092. int n= st->nb_index_entries;
  1093. unsigned int size;
  1094. if(n <= 0)
  1095. continue;
  1096. if(n >= 2){
  1097. int64_t pos= st->index_entries[0].pos;
  1098. avio_seek(s->pb, pos + 4, SEEK_SET);
  1099. size= avio_rl32(s->pb);
  1100. if(pos + size > st->index_entries[1].pos)
  1101. last_start= INT64_MAX;
  1102. }
  1103. if(st->index_entries[0].pos > last_start)
  1104. last_start= st->index_entries[0].pos;
  1105. if(st->index_entries[n-1].pos < first_end)
  1106. first_end= st->index_entries[n-1].pos;
  1107. }
  1108. avio_seek(s->pb, oldpos, SEEK_SET);
  1109. return last_start > first_end;
  1110. }
  1111. static int avi_load_index(AVFormatContext *s)
  1112. {
  1113. AVIContext *avi = s->priv_data;
  1114. AVIOContext *pb = s->pb;
  1115. uint32_t tag, size;
  1116. int64_t pos= avio_tell(pb);
  1117. int ret = -1;
  1118. if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
  1119. goto the_end; // maybe truncated file
  1120. av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
  1121. for(;;) {
  1122. if (url_feof(pb))
  1123. break;
  1124. tag = avio_rl32(pb);
  1125. size = avio_rl32(pb);
  1126. av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
  1127. tag & 0xff,
  1128. (tag >> 8) & 0xff,
  1129. (tag >> 16) & 0xff,
  1130. (tag >> 24) & 0xff,
  1131. size);
  1132. if (tag == MKTAG('i', 'd', 'x', '1') &&
  1133. avi_read_idx1(s, size) >= 0) {
  1134. ret = 0;
  1135. break;
  1136. }
  1137. size += (size & 1);
  1138. if (avio_skip(pb, size) < 0)
  1139. break; // something is wrong here
  1140. }
  1141. the_end:
  1142. avio_seek(pb, pos, SEEK_SET);
  1143. return ret;
  1144. }
  1145. static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
  1146. {
  1147. AVIStream *ast2 = st2->priv_data;
  1148. int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
  1149. av_free_packet(&ast2->sub_pkt);
  1150. if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
  1151. avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
  1152. av_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
  1153. }
  1154. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  1155. {
  1156. AVIContext *avi = s->priv_data;
  1157. AVStream *st;
  1158. int i, index;
  1159. int64_t pos, pos_min;
  1160. AVIStream *ast;
  1161. if (!avi->index_loaded) {
  1162. /* we only load the index on demand */
  1163. avi_load_index(s);
  1164. avi->index_loaded = 1;
  1165. }
  1166. assert(stream_index>= 0);
  1167. st = s->streams[stream_index];
  1168. ast= st->priv_data;
  1169. index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
  1170. if(index<0)
  1171. return -1;
  1172. /* find the position */
  1173. pos = st->index_entries[index].pos;
  1174. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  1175. // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  1176. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1177. /* One and only one real stream for DV in AVI, and it has video */
  1178. /* offsets. Calling with other stream indexes should have failed */
  1179. /* the av_index_search_timestamp call above. */
  1180. assert(stream_index == 0);
  1181. /* Feed the DV video stream version of the timestamp to the */
  1182. /* DV demux so it can synthesize correct timestamps. */
  1183. dv_offset_reset(avi->dv_demux, timestamp);
  1184. avio_seek(s->pb, pos, SEEK_SET);
  1185. avi->stream_index= -1;
  1186. return 0;
  1187. }
  1188. pos_min= pos;
  1189. for(i = 0; i < s->nb_streams; i++) {
  1190. AVStream *st2 = s->streams[i];
  1191. AVIStream *ast2 = st2->priv_data;
  1192. ast2->packet_size=
  1193. ast2->remaining= 0;
  1194. if (ast2->sub_ctx) {
  1195. seek_subtitle(st, st2, timestamp);
  1196. continue;
  1197. }
  1198. if (st2->nb_index_entries <= 0)
  1199. continue;
  1200. // assert(st2->codec->block_align);
  1201. assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
  1202. index = av_index_search_timestamp(
  1203. st2,
  1204. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  1205. flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
  1206. if(index<0)
  1207. index=0;
  1208. ast2->seek_pos= st2->index_entries[index].pos;
  1209. pos_min= FFMIN(pos_min,ast2->seek_pos);
  1210. }
  1211. for(i = 0; i < s->nb_streams; i++) {
  1212. AVStream *st2 = s->streams[i];
  1213. AVIStream *ast2 = st2->priv_data;
  1214. if (ast2->sub_ctx || st2->nb_index_entries <= 0)
  1215. continue;
  1216. index = av_index_search_timestamp(
  1217. st2,
  1218. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  1219. flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
  1220. if(index<0)
  1221. index=0;
  1222. while(!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)
  1223. index--;
  1224. ast2->frame_offset = st2->index_entries[index].timestamp;
  1225. }
  1226. /* do the seek */
  1227. avio_seek(s->pb, pos_min, SEEK_SET);
  1228. avi->stream_index= -1;
  1229. avi->dts_max= INT_MIN;
  1230. return 0;
  1231. }
  1232. static int avi_read_close(AVFormatContext *s)
  1233. {
  1234. int i;
  1235. AVIContext *avi = s->priv_data;
  1236. for(i=0;i<s->nb_streams;i++) {
  1237. AVStream *st = s->streams[i];
  1238. AVIStream *ast = st->priv_data;
  1239. if (ast) {
  1240. if (ast->sub_ctx) {
  1241. av_freep(&ast->sub_ctx->pb);
  1242. av_close_input_file(ast->sub_ctx);
  1243. }
  1244. av_free(ast->sub_buffer);
  1245. av_free_packet(&ast->sub_pkt);
  1246. }
  1247. }
  1248. av_free(avi->dv_demux);
  1249. return 0;
  1250. }
  1251. static int avi_probe(AVProbeData *p)
  1252. {
  1253. int i;
  1254. /* check file header */
  1255. for(i=0; avi_headers[i][0]; i++)
  1256. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  1257. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  1258. return AVPROBE_SCORE_MAX;
  1259. return 0;
  1260. }
  1261. AVInputFormat ff_avi_demuxer = {
  1262. .name = "avi",
  1263. .long_name = NULL_IF_CONFIG_SMALL("AVI format"),
  1264. .priv_data_size = sizeof(AVIContext),
  1265. .read_probe = avi_probe,
  1266. .read_header = avi_read_header,
  1267. .read_packet = avi_read_packet,
  1268. .read_close = avi_read_close,
  1269. .read_seek = avi_read_seek,
  1270. .priv_class = &demuxer_class,
  1271. };