avidec.c 50 KB

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