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.

1016 lines
36KB

  1. /*
  2. * AVI muxer
  3. * Copyright (c) 2000 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 <math.h>
  22. #include "avformat.h"
  23. #include "internal.h"
  24. #include "avi.h"
  25. #include "avio_internal.h"
  26. #include "riff.h"
  27. #include "mpegts.h"
  28. #include "libavformat/avlanguage.h"
  29. #include "libavutil/avstring.h"
  30. #include "libavutil/avutil.h"
  31. #include "libavutil/internal.h"
  32. #include "libavutil/dict.h"
  33. #include "libavutil/avassert.h"
  34. #include "libavutil/timestamp.h"
  35. #include "libavutil/opt.h"
  36. #include "libavutil/pixdesc.h"
  37. #include "libavcodec/raw.h"
  38. /*
  39. * TODO:
  40. * - fill all fields if non streamed (nb_frames for example)
  41. */
  42. typedef struct AVIIentry {
  43. char tag[4];
  44. unsigned int flags;
  45. unsigned int pos;
  46. unsigned int len;
  47. } AVIIentry;
  48. #define AVI_INDEX_CLUSTER_SIZE 16384
  49. #define AVI_MASTER_INDEX_PREFIX_SIZE (8+2+1+1+4+8+4+4)
  50. #define AVI_MASTER_INDEX_ENTRY_SIZE 16 /* bytes per entry */
  51. #define AVI_MASTER_INDEX_SIZE_DEFAULT 256 /* number of entries */
  52. typedef struct AVIIndex {
  53. int64_t indx_start;
  54. int64_t audio_strm_offset;
  55. int entry;
  56. int ents_allocated;
  57. int master_odml_riff_id_base;
  58. AVIIentry** cluster;
  59. } AVIIndex;
  60. typedef struct AVIContext {
  61. const AVClass *class;
  62. int64_t riff_start, movi_list, odml_list;
  63. int64_t frames_hdr_all;
  64. int riff_id;
  65. int reserve_index_space;
  66. int master_index_max_size;
  67. int write_channel_mask;
  68. } AVIContext;
  69. typedef struct AVIStream {
  70. int64_t frames_hdr_strm;
  71. int64_t audio_strm_length;
  72. int packet_count;
  73. int entry;
  74. int max_size;
  75. int sample_requested;
  76. int64_t last_dts;
  77. AVIIndex indexes;
  78. int64_t strh_flags_offset;
  79. uint32_t palette[AVPALETTE_COUNT];
  80. uint32_t old_palette[AVPALETTE_COUNT];
  81. int64_t pal_offset;
  82. } AVIStream;
  83. static int avi_write_packet_internal(AVFormatContext *s, AVPacket *pkt);
  84. static inline AVIIentry *avi_get_ientry(const AVIIndex *idx, int ent_id)
  85. {
  86. int cl = ent_id / AVI_INDEX_CLUSTER_SIZE;
  87. int id = ent_id % AVI_INDEX_CLUSTER_SIZE;
  88. return &idx->cluster[cl][id];
  89. }
  90. static int avi_add_ientry(AVFormatContext *s, int stream_index, char *tag,
  91. unsigned int flags, unsigned int size)
  92. {
  93. AVIContext *avi = s->priv_data;
  94. AVIOContext *pb = s->pb;
  95. AVIStream *avist = s->streams[stream_index]->priv_data;
  96. AVIIndex *idx = &avist->indexes;
  97. int cl = idx->entry / AVI_INDEX_CLUSTER_SIZE;
  98. int id = idx->entry % AVI_INDEX_CLUSTER_SIZE;
  99. if (idx->ents_allocated <= idx->entry) {
  100. idx->cluster = av_realloc_f(idx->cluster, sizeof(void*), cl+1);
  101. if (!idx->cluster) {
  102. idx->ents_allocated = 0;
  103. idx->entry = 0;
  104. return AVERROR(ENOMEM);
  105. }
  106. idx->cluster[cl] =
  107. av_malloc(AVI_INDEX_CLUSTER_SIZE * sizeof(AVIIentry));
  108. if (!idx->cluster[cl])
  109. return AVERROR(ENOMEM);
  110. idx->ents_allocated += AVI_INDEX_CLUSTER_SIZE;
  111. }
  112. if (tag)
  113. memcpy(idx->cluster[cl][id].tag, tag, 4);
  114. else
  115. memset(idx->cluster[cl][id].tag, 0, 4);
  116. idx->cluster[cl][id].flags = flags;
  117. idx->cluster[cl][id].pos = avio_tell(pb) - avi->movi_list;
  118. idx->cluster[cl][id].len = size;
  119. avist->max_size = FFMAX(avist->max_size, size);
  120. idx->entry++;
  121. return 0;
  122. }
  123. static av_cold int avi_init(struct AVFormatContext *s)
  124. {
  125. AVIContext *avi = s->priv_data;
  126. if (avi->reserve_index_space > 0) {
  127. avi->master_index_max_size = (avi->reserve_index_space - AVI_MASTER_INDEX_PREFIX_SIZE) / AVI_MASTER_INDEX_ENTRY_SIZE;
  128. avi->master_index_max_size = FFMAX(avi->master_index_max_size, 16);
  129. } else
  130. avi->master_index_max_size = AVI_MASTER_INDEX_SIZE_DEFAULT;
  131. av_log(s, AV_LOG_DEBUG, "reserve_index_space:%d master_index_max_size:%d\n",
  132. avi->reserve_index_space, avi->master_index_max_size);
  133. return 1; /* stream initialization continues in avi_write_header */
  134. }
  135. static int64_t avi_start_new_riff(AVFormatContext *s, AVIOContext *pb,
  136. const char *riff_tag, const char *list_tag)
  137. {
  138. AVIContext *avi = s->priv_data;
  139. int64_t loff;
  140. int i;
  141. avi->riff_id++;
  142. for (i = 0; i < s->nb_streams; i++) {
  143. AVIStream *avist = s->streams[i]->priv_data;
  144. avist->indexes.audio_strm_offset = avist->audio_strm_length;
  145. avist->indexes.entry = 0;
  146. }
  147. avi->riff_start = ff_start_tag(pb, "RIFF");
  148. ffio_wfourcc(pb, riff_tag);
  149. loff = ff_start_tag(pb, "LIST");
  150. ffio_wfourcc(pb, list_tag);
  151. return loff;
  152. }
  153. static char *avi_stream2fourcc(char *tag, int index, enum AVMediaType type)
  154. {
  155. tag[0] = '0' + index / 10;
  156. tag[1] = '0' + index % 10;
  157. if (type == AVMEDIA_TYPE_VIDEO) {
  158. tag[2] = 'd';
  159. tag[3] = 'c';
  160. } else if (type == AVMEDIA_TYPE_SUBTITLE) {
  161. // note: this is not an official code
  162. tag[2] = 's';
  163. tag[3] = 'b';
  164. } else {
  165. tag[2] = 'w';
  166. tag[3] = 'b';
  167. }
  168. tag[4] = '\0';
  169. return tag;
  170. }
  171. static int avi_write_counters(AVFormatContext *s, int riff_id)
  172. {
  173. AVIOContext *pb = s->pb;
  174. AVIContext *avi = s->priv_data;
  175. int n, au_byterate, au_ssize, au_scale, nb_frames = 0;
  176. int64_t file_size;
  177. AVCodecParameters *par;
  178. file_size = avio_tell(pb);
  179. for (n = 0; n < s->nb_streams; n++) {
  180. AVIStream *avist = s->streams[n]->priv_data;
  181. av_assert0(avist->frames_hdr_strm);
  182. par = s->streams[n]->codecpar;
  183. avio_seek(pb, avist->frames_hdr_strm, SEEK_SET);
  184. ff_parse_specific_params(s->streams[n], &au_byterate, &au_ssize, &au_scale);
  185. if (au_ssize == 0)
  186. avio_wl32(pb, avist->packet_count);
  187. else
  188. avio_wl32(pb, avist->audio_strm_length / au_ssize);
  189. if (par->codec_type == AVMEDIA_TYPE_VIDEO)
  190. nb_frames = FFMAX(nb_frames, avist->packet_count);
  191. }
  192. if (riff_id == 1) {
  193. av_assert0(avi->frames_hdr_all);
  194. avio_seek(pb, avi->frames_hdr_all, SEEK_SET);
  195. avio_wl32(pb, nb_frames);
  196. }
  197. avio_seek(pb, file_size, SEEK_SET);
  198. return 0;
  199. }
  200. static void write_odml_master(AVFormatContext *s, int stream_index)
  201. {
  202. AVIOContext *pb = s->pb;
  203. AVIContext *avi = s->priv_data;
  204. AVStream *st = s->streams[stream_index];
  205. AVCodecParameters *par = st->codecpar;
  206. AVIStream *avist = st->priv_data;
  207. unsigned char tag[5];
  208. int j;
  209. /* Starting to lay out AVI OpenDML master index.
  210. * We want to make it JUNK entry for now, since we'd
  211. * like to get away without making AVI an OpenDML one
  212. * for compatibility reasons. */
  213. avist->indexes.indx_start = ff_start_tag(pb, "JUNK");
  214. avio_wl16(pb, 4); /* wLongsPerEntry */
  215. avio_w8(pb, 0); /* bIndexSubType (0 == frame index) */
  216. avio_w8(pb, 0); /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
  217. avio_wl32(pb, 0); /* nEntriesInUse (will fill out later on) */
  218. ffio_wfourcc(pb, avi_stream2fourcc(tag, stream_index, par->codec_type));
  219. /* dwChunkId */
  220. avio_wl64(pb, 0); /* dwReserved[3] */
  221. avio_wl32(pb, 0); /* Must be 0. */
  222. for (j = 0; j < avi->master_index_max_size * 2; j++)
  223. avio_wl64(pb, 0);
  224. ff_end_tag(pb, avist->indexes.indx_start);
  225. }
  226. static int avi_write_header(AVFormatContext *s)
  227. {
  228. AVIContext *avi = s->priv_data;
  229. AVIOContext *pb = s->pb;
  230. int bitrate, n, i, nb_frames, au_byterate, au_ssize, au_scale;
  231. int64_t max_stream_duration = 0;
  232. AVCodecParameters *video_par;
  233. AVStream *video_st = NULL;
  234. int64_t list1, list2, strh, strf;
  235. AVDictionaryEntry *t = NULL;
  236. int padding;
  237. if (s->nb_streams > AVI_MAX_STREAM_COUNT) {
  238. av_log(s, AV_LOG_ERROR, "AVI does not support >%d streams\n",
  239. AVI_MAX_STREAM_COUNT);
  240. return AVERROR(EINVAL);
  241. }
  242. for (n = 0; n < s->nb_streams; n++) {
  243. s->streams[n]->priv_data = av_mallocz(sizeof(AVIStream));
  244. if (!s->streams[n]->priv_data)
  245. return AVERROR(ENOMEM);
  246. }
  247. /* header list */
  248. avi->riff_id = 0;
  249. list1 = avi_start_new_riff(s, pb, "AVI ", "hdrl");
  250. /* avi header */
  251. ffio_wfourcc(pb, "avih");
  252. avio_wl32(pb, 14 * 4);
  253. bitrate = 0;
  254. video_par = NULL;
  255. for (n = 0; n < s->nb_streams; n++) {
  256. AVCodecParameters *par = s->streams[n]->codecpar;
  257. AVStream *st = s->streams[n];
  258. bitrate = FFMIN(bitrate + par->bit_rate, INT32_MAX);
  259. if (st->duration > 0) {
  260. int64_t stream_duration = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
  261. max_stream_duration = FFMAX(stream_duration, max_stream_duration);
  262. }
  263. if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
  264. video_par = par;
  265. video_st = st;
  266. }
  267. }
  268. /* guess master index size based on bitrate and duration */
  269. if (!avi->reserve_index_space) {
  270. double duration_est, filesize_est;
  271. if (s->duration > 0)
  272. duration_est = (double)s->duration / AV_TIME_BASE;
  273. else if (max_stream_duration > 0)
  274. duration_est = (double)max_stream_duration / AV_TIME_BASE;
  275. else
  276. duration_est = 10 * 60 * 60; /* default to 10 hours */
  277. filesize_est = duration_est * (bitrate / 8) * 1.10; /* add 10% safety margin for muxer+bitrate */
  278. avi->master_index_max_size = FFMAX((int)ceil(filesize_est / AVI_MAX_RIFF_SIZE) + 1,
  279. avi->master_index_max_size);
  280. av_log(s, AV_LOG_DEBUG, "duration_est:%0.3f, filesize_est:%0.1fGiB, master_index_max_size:%d\n",
  281. duration_est, filesize_est / (1024*1024*1024), avi->master_index_max_size);
  282. }
  283. nb_frames = 0;
  284. // TODO: should be avg_frame_rate
  285. if (video_st)
  286. avio_wl32(pb, (uint32_t) (INT64_C(1000000) * video_st->time_base.num /
  287. video_st->time_base.den));
  288. else
  289. avio_wl32(pb, 0);
  290. avio_wl32(pb, bitrate / 8); /* XXX: not quite exact */
  291. avio_wl32(pb, 0); /* padding */
  292. if (!(pb->seekable & AVIO_SEEKABLE_NORMAL))
  293. avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_ISINTERLEAVED); /* flags */
  294. else
  295. avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_HASINDEX | AVIF_ISINTERLEAVED); /* flags */
  296. avi->frames_hdr_all = avio_tell(pb); /* remember this offset to fill later */
  297. avio_wl32(pb, nb_frames); /* nb frames, filled later */
  298. avio_wl32(pb, 0); /* initial frame */
  299. avio_wl32(pb, s->nb_streams); /* nb streams */
  300. avio_wl32(pb, 1024 * 1024); /* suggested buffer size */
  301. if (video_par) {
  302. avio_wl32(pb, video_par->width);
  303. avio_wl32(pb, video_par->height);
  304. } else {
  305. avio_wl32(pb, 0);
  306. avio_wl32(pb, 0);
  307. }
  308. avio_wl32(pb, 0); /* reserved */
  309. avio_wl32(pb, 0); /* reserved */
  310. avio_wl32(pb, 0); /* reserved */
  311. avio_wl32(pb, 0); /* reserved */
  312. /* stream list */
  313. for (i = 0; i < n; i++) {
  314. AVStream *st = s->streams[i];
  315. AVCodecParameters *par = st->codecpar;
  316. AVIStream *avist = st->priv_data;
  317. list2 = ff_start_tag(pb, "LIST");
  318. ffio_wfourcc(pb, "strl");
  319. /* stream generic header */
  320. strh = ff_start_tag(pb, "strh");
  321. switch (par->codec_type) {
  322. case AVMEDIA_TYPE_SUBTITLE:
  323. // XSUB subtitles behave like video tracks, other subtitles
  324. // are not (yet) supported.
  325. if (par->codec_id != AV_CODEC_ID_XSUB) {
  326. avpriv_report_missing_feature(s, "Subtitle streams other than DivX XSUB");
  327. return AVERROR_PATCHWELCOME;
  328. }
  329. case AVMEDIA_TYPE_VIDEO:
  330. ffio_wfourcc(pb, "vids");
  331. break;
  332. case AVMEDIA_TYPE_AUDIO:
  333. ffio_wfourcc(pb, "auds");
  334. break;
  335. // case AVMEDIA_TYPE_TEXT:
  336. // ffio_wfourcc(pb, "txts");
  337. // break;
  338. case AVMEDIA_TYPE_DATA:
  339. ffio_wfourcc(pb, "dats");
  340. break;
  341. }
  342. if (par->codec_type == AVMEDIA_TYPE_VIDEO ||
  343. par->codec_id == AV_CODEC_ID_XSUB)
  344. avio_wl32(pb, par->codec_tag);
  345. else
  346. avio_wl32(pb, 1);
  347. avist->strh_flags_offset = avio_tell(pb);
  348. avio_wl32(pb, 0); /* flags */
  349. avio_wl16(pb, 0); /* priority */
  350. avio_wl16(pb, 0); /* language */
  351. avio_wl32(pb, 0); /* initial frame */
  352. ff_parse_specific_params(st, &au_byterate, &au_ssize, &au_scale);
  353. if ( par->codec_type == AVMEDIA_TYPE_VIDEO
  354. && par->codec_id != AV_CODEC_ID_XSUB
  355. && au_byterate > 1000LL*au_scale) {
  356. au_byterate = 600;
  357. au_scale = 1;
  358. }
  359. avpriv_set_pts_info(st, 64, au_scale, au_byterate);
  360. if (par->codec_id == AV_CODEC_ID_XSUB)
  361. au_scale = au_byterate = 0;
  362. avio_wl32(pb, au_scale); /* scale */
  363. avio_wl32(pb, au_byterate); /* rate */
  364. avio_wl32(pb, 0); /* start */
  365. /* remember this offset to fill later */
  366. avist->frames_hdr_strm = avio_tell(pb);
  367. if (!(pb->seekable & AVIO_SEEKABLE_NORMAL))
  368. /* FIXME: this may be broken, but who cares */
  369. avio_wl32(pb, AVI_MAX_RIFF_SIZE);
  370. else
  371. avio_wl32(pb, 0); /* length, XXX: filled later */
  372. /* suggested buffer size, is set to largest chunk size in avi_write_trailer */
  373. if (par->codec_type == AVMEDIA_TYPE_VIDEO)
  374. avio_wl32(pb, 1024 * 1024);
  375. else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
  376. avio_wl32(pb, 12 * 1024);
  377. else
  378. avio_wl32(pb, 0);
  379. avio_wl32(pb, -1); /* quality */
  380. avio_wl32(pb, au_ssize); /* sample size */
  381. avio_wl32(pb, 0);
  382. avio_wl16(pb, par->width);
  383. avio_wl16(pb, par->height);
  384. ff_end_tag(pb, strh);
  385. if (par->codec_type != AVMEDIA_TYPE_DATA) {
  386. int ret, flags;
  387. enum AVPixelFormat pix_fmt;
  388. strf = ff_start_tag(pb, "strf");
  389. switch (par->codec_type) {
  390. case AVMEDIA_TYPE_SUBTITLE:
  391. /* XSUB subtitles behave like video tracks, other subtitles
  392. * are not (yet) supported. */
  393. if (par->codec_id != AV_CODEC_ID_XSUB)
  394. break;
  395. case AVMEDIA_TYPE_VIDEO:
  396. /* WMP expects RGB 5:5:5 rawvideo in avi to have bpp set to 16. */
  397. if ( !par->codec_tag
  398. && par->codec_id == AV_CODEC_ID_RAWVIDEO
  399. && par->format == AV_PIX_FMT_RGB555LE
  400. && par->bits_per_coded_sample == 15)
  401. par->bits_per_coded_sample = 16;
  402. avist->pal_offset = avio_tell(pb) + 40;
  403. ff_put_bmp_header(pb, par, 0, 0);
  404. pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_avi,
  405. par->bits_per_coded_sample);
  406. if ( !par->codec_tag
  407. && par->codec_id == AV_CODEC_ID_RAWVIDEO
  408. && par->format != pix_fmt
  409. && par->format != AV_PIX_FMT_NONE)
  410. av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to avi, output file will be unreadable\n",
  411. av_get_pix_fmt_name(par->format));
  412. break;
  413. case AVMEDIA_TYPE_AUDIO:
  414. flags = (avi->write_channel_mask == 0) ? FF_PUT_WAV_HEADER_SKIP_CHANNELMASK : 0;
  415. if ((ret = ff_put_wav_header(s, pb, par, flags)) < 0)
  416. return ret;
  417. break;
  418. default:
  419. av_log(s, AV_LOG_ERROR,
  420. "Invalid or not supported codec type '%s' found in the input\n",
  421. (char *)av_x_if_null(av_get_media_type_string(par->codec_type), "?"));
  422. return AVERROR(EINVAL);
  423. }
  424. ff_end_tag(pb, strf);
  425. if ((t = av_dict_get(st->metadata, "title", NULL, 0))) {
  426. ff_riff_write_info_tag(s->pb, "strn", t->value);
  427. t = NULL;
  428. }
  429. if (par->codec_id == AV_CODEC_ID_XSUB
  430. && (t = av_dict_get(s->streams[i]->metadata, "language", NULL, 0))) {
  431. const char* langstr = ff_convert_lang_to(t->value, AV_LANG_ISO639_1);
  432. t = NULL;
  433. if (langstr) {
  434. char* str = av_asprintf("Subtitle - %s-xx;02", langstr);
  435. if (!str)
  436. return AVERROR(ENOMEM);
  437. ff_riff_write_info_tag(s->pb, "strn", str);
  438. av_free(str);
  439. }
  440. }
  441. }
  442. if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
  443. write_odml_master(s, i);
  444. }
  445. if (par->codec_type == AVMEDIA_TYPE_VIDEO &&
  446. st->sample_aspect_ratio.num > 0 &&
  447. st->sample_aspect_ratio.den > 0) {
  448. int vprp = ff_start_tag(pb, "vprp");
  449. AVRational dar = av_mul_q(st->sample_aspect_ratio,
  450. (AVRational) { par->width,
  451. par->height });
  452. int num, den, fields, i;
  453. av_reduce(&num, &den, dar.num, dar.den, 0xFFFF);
  454. if (par->field_order == AV_FIELD_TT || par->field_order == AV_FIELD_BB ||
  455. par->field_order == AV_FIELD_TB || par->field_order == AV_FIELD_BT) {
  456. fields = 2; // interlaced
  457. } else {
  458. fields = 1; // progressive
  459. }
  460. avio_wl32(pb, 0); // video format = unknown
  461. avio_wl32(pb, 0); // video standard = unknown
  462. // TODO: should be avg_frame_rate
  463. avio_wl32(pb, (2LL*st->time_base.den + st->time_base.num - 1) / (2LL * st->time_base.num));
  464. avio_wl32(pb, par->width);
  465. avio_wl32(pb, par->height);
  466. avio_wl16(pb, den);
  467. avio_wl16(pb, num);
  468. avio_wl32(pb, par->width);
  469. avio_wl32(pb, par->height);
  470. avio_wl32(pb, fields); // fields per frame
  471. for (i = 0; i < fields; i++) {
  472. int start_line;
  473. // OpenDML v1.02 is not very specific on what value to use for
  474. // start_line when frame data is not coming from a capturing device,
  475. // so just use 0/1 depending on the field order for interlaced frames
  476. if (par->field_order == AV_FIELD_TT || par->field_order == AV_FIELD_TB) {
  477. start_line = (i == 0) ? 0 : 1;
  478. } else if (par->field_order == AV_FIELD_BB || par->field_order == AV_FIELD_BT) {
  479. start_line = (i == 0) ? 1 : 0;
  480. } else {
  481. start_line = 0;
  482. }
  483. avio_wl32(pb, par->height / fields); // compressed bitmap height
  484. avio_wl32(pb, par->width); // compressed bitmap width
  485. avio_wl32(pb, par->height / fields); // valid bitmap height
  486. avio_wl32(pb, par->width); // valid bitmap width
  487. avio_wl32(pb, 0); // valid bitmap X offset
  488. avio_wl32(pb, 0); // valid bitmap Y offset
  489. avio_wl32(pb, 0); // valid X offset in T
  490. avio_wl32(pb, start_line); // valid Y start line
  491. }
  492. ff_end_tag(pb, vprp);
  493. }
  494. ff_end_tag(pb, list2);
  495. }
  496. if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
  497. /* AVI could become an OpenDML one, if it grows beyond 2Gb range */
  498. avi->odml_list = ff_start_tag(pb, "JUNK");
  499. ffio_wfourcc(pb, "odml");
  500. ffio_wfourcc(pb, "dmlh");
  501. avio_wl32(pb, 248);
  502. for (i = 0; i < 248; i += 4)
  503. avio_wl32(pb, 0);
  504. ff_end_tag(pb, avi->odml_list);
  505. }
  506. ff_end_tag(pb, list1);
  507. ff_riff_write_info(s);
  508. padding = s->metadata_header_padding;
  509. if (padding < 0)
  510. padding = 1016;
  511. /* some padding for easier tag editing */
  512. if (padding) {
  513. list2 = ff_start_tag(pb, "JUNK");
  514. for (i = padding; i > 0; i -= 4)
  515. avio_wl32(pb, 0);
  516. ff_end_tag(pb, list2);
  517. }
  518. avi->movi_list = ff_start_tag(pb, "LIST");
  519. ffio_wfourcc(pb, "movi");
  520. return 0;
  521. }
  522. static void update_odml_entry(AVFormatContext *s, int stream_index, int64_t ix, int size)
  523. {
  524. AVIOContext *pb = s->pb;
  525. AVIContext *avi = s->priv_data;
  526. AVIStream *avist = s->streams[stream_index]->priv_data;
  527. int64_t pos;
  528. int au_byterate, au_ssize, au_scale;
  529. pos = avio_tell(pb);
  530. /* Updating one entry in the AVI OpenDML master index */
  531. avio_seek(pb, avist->indexes.indx_start - 8, SEEK_SET);
  532. ffio_wfourcc(pb, "indx"); /* enabling this entry */
  533. avio_skip(pb, 8);
  534. avio_wl32(pb, avi->riff_id - avist->indexes.master_odml_riff_id_base); /* nEntriesInUse */
  535. avio_skip(pb, 16 * (avi->riff_id - avist->indexes.master_odml_riff_id_base));
  536. avio_wl64(pb, ix); /* qwOffset */
  537. avio_wl32(pb, size); /* dwSize */
  538. ff_parse_specific_params(s->streams[stream_index], &au_byterate, &au_ssize, &au_scale);
  539. if (s->streams[stream_index]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && au_ssize > 0) {
  540. uint32_t audio_segm_size = (avist->audio_strm_length - avist->indexes.audio_strm_offset);
  541. if ((audio_segm_size % au_ssize > 0) && !avist->sample_requested) {
  542. avpriv_request_sample(s, "OpenDML index duration for audio packets with partial frames");
  543. avist->sample_requested = 1;
  544. }
  545. avio_wl32(pb, audio_segm_size / au_ssize); /* dwDuration (sample count) */
  546. } else
  547. avio_wl32(pb, avist->indexes.entry); /* dwDuration (packet count) */
  548. avio_seek(pb, pos, SEEK_SET);
  549. }
  550. static int avi_write_ix(AVFormatContext *s)
  551. {
  552. AVIOContext *pb = s->pb;
  553. AVIContext *avi = s->priv_data;
  554. char tag[5];
  555. char ix_tag[] = "ix00";
  556. int i, j;
  557. av_assert0(pb->seekable & AVIO_SEEKABLE_NORMAL);
  558. for (i = 0; i < s->nb_streams; i++) {
  559. AVIStream *avist = s->streams[i]->priv_data;
  560. if (avi->riff_id - avist->indexes.master_odml_riff_id_base == avi->master_index_max_size) {
  561. int64_t pos;
  562. int size = AVI_MASTER_INDEX_PREFIX_SIZE + AVI_MASTER_INDEX_ENTRY_SIZE * avi->master_index_max_size;
  563. pos = avio_tell(pb);
  564. update_odml_entry(s, i, pos, size);
  565. write_odml_master(s, i);
  566. av_assert1(avio_tell(pb) - pos == size);
  567. avist->indexes.master_odml_riff_id_base = avi->riff_id - 1;
  568. }
  569. av_assert0(avi->riff_id - avist->indexes.master_odml_riff_id_base < avi->master_index_max_size);
  570. }
  571. for (i = 0; i < s->nb_streams; i++) {
  572. AVIStream *avist = s->streams[i]->priv_data;
  573. int64_t ix;
  574. avi_stream2fourcc(tag, i, s->streams[i]->codecpar->codec_type);
  575. ix_tag[3] = '0' + i;
  576. /* Writing AVI OpenDML leaf index chunk */
  577. ix = avio_tell(pb);
  578. ffio_wfourcc(pb, ix_tag); /* ix?? */
  579. avio_wl32(pb, avist->indexes.entry * 8 + 24);
  580. /* chunk size */
  581. avio_wl16(pb, 2); /* wLongsPerEntry */
  582. avio_w8(pb, 0); /* bIndexSubType (0 == frame index) */
  583. avio_w8(pb, 1); /* bIndexType (1 == AVI_INDEX_OF_CHUNKS) */
  584. avio_wl32(pb, avist->indexes.entry);
  585. /* nEntriesInUse */
  586. ffio_wfourcc(pb, tag); /* dwChunkId */
  587. avio_wl64(pb, avi->movi_list); /* qwBaseOffset */
  588. avio_wl32(pb, 0); /* dwReserved_3 (must be 0) */
  589. for (j = 0; j < avist->indexes.entry; j++) {
  590. AVIIentry *ie = avi_get_ientry(&avist->indexes, j);
  591. avio_wl32(pb, ie->pos + 8);
  592. avio_wl32(pb, ((uint32_t) ie->len & ~0x80000000) |
  593. (ie->flags & 0x10 ? 0 : 0x80000000));
  594. }
  595. update_odml_entry(s, i, ix, avio_tell(pb) - ix);
  596. }
  597. return 0;
  598. }
  599. static int avi_write_idx1(AVFormatContext *s)
  600. {
  601. AVIOContext *pb = s->pb;
  602. AVIContext *avi = s->priv_data;
  603. int64_t idx_chunk;
  604. int i;
  605. char tag[5];
  606. if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
  607. AVIStream *avist;
  608. AVIIentry *ie = 0, *tie;
  609. int empty, stream_id = -1;
  610. idx_chunk = ff_start_tag(pb, "idx1");
  611. for (i = 0; i < s->nb_streams; i++) {
  612. avist = s->streams[i]->priv_data;
  613. avist->entry = 0;
  614. }
  615. do {
  616. empty = 1;
  617. for (i = 0; i < s->nb_streams; i++) {
  618. avist = s->streams[i]->priv_data;
  619. if (avist->indexes.entry <= avist->entry)
  620. continue;
  621. tie = avi_get_ientry(&avist->indexes, avist->entry);
  622. if (empty || tie->pos < ie->pos) {
  623. ie = tie;
  624. stream_id = i;
  625. }
  626. empty = 0;
  627. }
  628. if (!empty) {
  629. avist = s->streams[stream_id]->priv_data;
  630. if (*ie->tag)
  631. ffio_wfourcc(pb, ie->tag);
  632. else {
  633. avi_stream2fourcc(tag, stream_id,
  634. s->streams[stream_id]->codecpar->codec_type);
  635. ffio_wfourcc(pb, tag);
  636. }
  637. avio_wl32(pb, ie->flags);
  638. avio_wl32(pb, ie->pos);
  639. avio_wl32(pb, ie->len);
  640. avist->entry++;
  641. }
  642. } while (!empty);
  643. ff_end_tag(pb, idx_chunk);
  644. avi_write_counters(s, avi->riff_id);
  645. }
  646. return 0;
  647. }
  648. static int write_skip_frames(AVFormatContext *s, int stream_index, int64_t dts)
  649. {
  650. AVIStream *avist = s->streams[stream_index]->priv_data;
  651. AVCodecParameters *par = s->streams[stream_index]->codecpar;
  652. ff_dlog(s, "dts:%s packet_count:%d stream_index:%d\n", av_ts2str(dts), avist->packet_count, stream_index);
  653. while (par->block_align == 0 && dts != AV_NOPTS_VALUE &&
  654. dts > avist->packet_count && par->codec_id != AV_CODEC_ID_XSUB && avist->packet_count) {
  655. AVPacket empty_packet;
  656. if (dts - avist->packet_count > 60000) {
  657. av_log(s, AV_LOG_ERROR, "Too large number of skipped frames %"PRId64" > 60000\n", dts - avist->packet_count);
  658. return AVERROR(EINVAL);
  659. }
  660. av_init_packet(&empty_packet);
  661. empty_packet.size = 0;
  662. empty_packet.data = NULL;
  663. empty_packet.stream_index = stream_index;
  664. avi_write_packet_internal(s, &empty_packet);
  665. ff_dlog(s, "dup dts:%s packet_count:%d\n", av_ts2str(dts), avist->packet_count);
  666. }
  667. return 0;
  668. }
  669. static int avi_write_packet(AVFormatContext *s, AVPacket *pkt)
  670. {
  671. const int stream_index = pkt->stream_index;
  672. AVCodecParameters *par = s->streams[stream_index]->codecpar;
  673. int ret;
  674. if (par->codec_id == AV_CODEC_ID_H264 && par->codec_tag == MKTAG('H','2','6','4') && pkt->size) {
  675. ret = ff_check_h264_startcode(s, s->streams[stream_index], pkt);
  676. if (ret < 0)
  677. return ret;
  678. }
  679. if ((ret = write_skip_frames(s, stream_index, pkt->dts)) < 0)
  680. return ret;
  681. if (!pkt->size)
  682. return avi_write_packet_internal(s, pkt); /* Passthrough */
  683. if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
  684. AVIStream *avist = s->streams[stream_index]->priv_data;
  685. AVIOContext *pb = s->pb;
  686. AVPacket *opkt = pkt;
  687. int reshuffle_ret;
  688. if (par->codec_id == AV_CODEC_ID_RAWVIDEO && par->codec_tag == 0) {
  689. int64_t bpc = par->bits_per_coded_sample != 15 ? par->bits_per_coded_sample : 16;
  690. int expected_stride = ((par->width * bpc + 31) >> 5)*4;
  691. reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, par, expected_stride);
  692. if (reshuffle_ret < 0)
  693. return reshuffle_ret;
  694. } else
  695. reshuffle_ret = 0;
  696. if (par->format == AV_PIX_FMT_PAL8) {
  697. ret = ff_get_packet_palette(s, opkt, reshuffle_ret, avist->palette);
  698. if (ret < 0)
  699. goto fail;
  700. if (ret) {
  701. int pal_size = 1 << par->bits_per_coded_sample;
  702. int pc_tag, i;
  703. av_assert0(par->bits_per_coded_sample >= 0 && par->bits_per_coded_sample <= 8);
  704. if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && avist->pal_offset) {
  705. int64_t cur_offset = avio_tell(pb);
  706. avio_seek(pb, avist->pal_offset, SEEK_SET);
  707. for (i = 0; i < pal_size; i++) {
  708. uint32_t v = avist->palette[i];
  709. avio_wl32(pb, v & 0xffffff);
  710. }
  711. avio_seek(pb, cur_offset, SEEK_SET);
  712. memcpy(avist->old_palette, avist->palette, pal_size * 4);
  713. avist->pal_offset = 0;
  714. }
  715. if (memcmp(avist->palette, avist->old_palette, pal_size * 4)) {
  716. unsigned char tag[5];
  717. avi_stream2fourcc(tag, stream_index, par->codec_type);
  718. tag[2] = 'p'; tag[3] = 'c';
  719. if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
  720. if (avist->strh_flags_offset) {
  721. int64_t cur_offset = avio_tell(pb);
  722. avio_seek(pb, avist->strh_flags_offset, SEEK_SET);
  723. avio_wl32(pb, AVISF_VIDEO_PALCHANGES);
  724. avio_seek(pb, cur_offset, SEEK_SET);
  725. avist->strh_flags_offset = 0;
  726. }
  727. ret = avi_add_ientry(s, stream_index, tag, AVIIF_NO_TIME,
  728. pal_size * 4 + 4);
  729. if (ret < 0)
  730. goto fail;
  731. }
  732. pc_tag = ff_start_tag(pb, tag);
  733. avio_w8(pb, 0);
  734. avio_w8(pb, pal_size & 0xFF);
  735. avio_wl16(pb, 0); // reserved
  736. for (i = 0; i < pal_size; i++) {
  737. uint32_t v = avist->palette[i];
  738. avio_wb32(pb, v<<8);
  739. }
  740. ff_end_tag(pb, pc_tag);
  741. memcpy(avist->old_palette, avist->palette, pal_size * 4);
  742. }
  743. }
  744. }
  745. if (reshuffle_ret) {
  746. ret = avi_write_packet_internal(s, pkt);
  747. fail:
  748. if (reshuffle_ret)
  749. av_packet_free(&pkt);
  750. return ret;
  751. }
  752. }
  753. return avi_write_packet_internal(s, pkt);
  754. }
  755. static int avi_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
  756. {
  757. unsigned char tag[5];
  758. unsigned int flags = 0;
  759. const int stream_index = pkt->stream_index;
  760. int size = pkt->size;
  761. AVIContext *avi = s->priv_data;
  762. AVIOContext *pb = s->pb;
  763. AVIStream *avist = s->streams[stream_index]->priv_data;
  764. AVCodecParameters *par = s->streams[stream_index]->codecpar;
  765. if (pkt->dts != AV_NOPTS_VALUE)
  766. avist->last_dts = pkt->dts + pkt->duration;
  767. avist->packet_count++;
  768. // Make sure to put an OpenDML chunk when the file size exceeds the limits
  769. if ((pb->seekable & AVIO_SEEKABLE_NORMAL) &&
  770. (avio_tell(pb) - avi->riff_start > AVI_MAX_RIFF_SIZE)) {
  771. avi_write_ix(s);
  772. ff_end_tag(pb, avi->movi_list);
  773. if (avi->riff_id == 1)
  774. avi_write_idx1(s);
  775. ff_end_tag(pb, avi->riff_start);
  776. avi->movi_list = avi_start_new_riff(s, pb, "AVIX", "movi");
  777. }
  778. avi_stream2fourcc(tag, stream_index, par->codec_type);
  779. if (pkt->flags & AV_PKT_FLAG_KEY)
  780. flags = 0x10;
  781. if (par->codec_type == AVMEDIA_TYPE_AUDIO)
  782. avist->audio_strm_length += size;
  783. if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
  784. int ret;
  785. ret = avi_add_ientry(s, stream_index, NULL, flags, size);
  786. if (ret < 0)
  787. return ret;
  788. }
  789. avio_write(pb, tag, 4);
  790. avio_wl32(pb, size);
  791. avio_write(pb, pkt->data, size);
  792. if (size & 1)
  793. avio_w8(pb, 0);
  794. return 0;
  795. }
  796. static int avi_write_trailer(AVFormatContext *s)
  797. {
  798. AVIContext *avi = s->priv_data;
  799. AVIOContext *pb = s->pb;
  800. int res = 0;
  801. int i, n, nb_frames;
  802. int64_t file_size;
  803. for (i = 0; i < s->nb_streams; i++) {
  804. AVIStream *avist = s->streams[i]->priv_data;
  805. write_skip_frames(s, i, avist->last_dts);
  806. }
  807. if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
  808. if (avi->riff_id == 1) {
  809. ff_end_tag(pb, avi->movi_list);
  810. res = avi_write_idx1(s);
  811. ff_end_tag(pb, avi->riff_start);
  812. } else {
  813. avi_write_ix(s);
  814. ff_end_tag(pb, avi->movi_list);
  815. ff_end_tag(pb, avi->riff_start);
  816. file_size = avio_tell(pb);
  817. avio_seek(pb, avi->odml_list - 8, SEEK_SET);
  818. ffio_wfourcc(pb, "LIST"); /* Making this AVI OpenDML one */
  819. avio_skip(pb, 16);
  820. for (n = nb_frames = 0; n < s->nb_streams; n++) {
  821. AVCodecParameters *par = s->streams[n]->codecpar;
  822. AVIStream *avist = s->streams[n]->priv_data;
  823. if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
  824. if (nb_frames < avist->packet_count)
  825. nb_frames = avist->packet_count;
  826. } else {
  827. if (par->codec_id == AV_CODEC_ID_MP2 ||
  828. par->codec_id == AV_CODEC_ID_MP3)
  829. nb_frames += avist->packet_count;
  830. }
  831. }
  832. avio_wl32(pb, nb_frames);
  833. avio_seek(pb, file_size, SEEK_SET);
  834. avi_write_counters(s, avi->riff_id);
  835. }
  836. }
  837. if (avi->riff_id >= avi->master_index_max_size) {
  838. int index_space = AVI_MASTER_INDEX_PREFIX_SIZE +
  839. AVI_MASTER_INDEX_ENTRY_SIZE * avi->riff_id;
  840. av_log(s, AV_LOG_WARNING, "Output file not strictly OpenDML compliant, "
  841. "consider re-muxing with 'reserve_index_space' option value >= %d\n",
  842. index_space);
  843. }
  844. for (i = 0; i < s->nb_streams; i++) {
  845. AVIStream *avist = s->streams[i]->priv_data;
  846. if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
  847. avio_seek(pb, avist->frames_hdr_strm + 4, SEEK_SET);
  848. avio_wl32(pb, avist->max_size);
  849. }
  850. }
  851. return res;
  852. }
  853. static void avi_deinit(AVFormatContext *s)
  854. {
  855. for (int i = 0; i < s->nb_streams; i++) {
  856. AVIStream *avist = s->streams[i]->priv_data;
  857. if (!avist)
  858. continue;
  859. for (int j = 0; j < avist->indexes.ents_allocated / AVI_INDEX_CLUSTER_SIZE; j++)
  860. av_freep(&avist->indexes.cluster[j]);
  861. av_freep(&avist->indexes.cluster);
  862. avist->indexes.ents_allocated = avist->indexes.entry = 0;
  863. }
  864. }
  865. #define OFFSET(x) offsetof(AVIContext, x)
  866. #define ENC AV_OPT_FLAG_ENCODING_PARAM
  867. static const AVOption options[] = {
  868. { "reserve_index_space", "reserve space (in bytes) at the beginning of the file for each stream index", OFFSET(reserve_index_space), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, ENC },
  869. { "write_channel_mask", "write channel mask into wave format header", OFFSET(write_channel_mask), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, ENC },
  870. { NULL },
  871. };
  872. static const AVClass avi_muxer_class = {
  873. .class_name = "AVI muxer",
  874. .item_name = av_default_item_name,
  875. .option = options,
  876. .version = LIBAVUTIL_VERSION_INT,
  877. };
  878. AVOutputFormat ff_avi_muxer = {
  879. .name = "avi",
  880. .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
  881. .mime_type = "video/x-msvideo",
  882. .extensions = "avi",
  883. .priv_data_size = sizeof(AVIContext),
  884. .audio_codec = CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_AC3,
  885. .video_codec = AV_CODEC_ID_MPEG4,
  886. .init = avi_init,
  887. .deinit = avi_deinit,
  888. .write_header = avi_write_header,
  889. .write_packet = avi_write_packet,
  890. .write_trailer = avi_write_trailer,
  891. .codec_tag = (const AVCodecTag * const []) {
  892. ff_codec_bmp_tags, ff_codec_wav_tags, 0
  893. },
  894. .priv_class = &avi_muxer_class,
  895. };