You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1609 lines
55KB

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