mux.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. /*
  2. * muxing functions for use within FFmpeg
  3. * Copyright (c) 2000, 2001, 2002 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 "avformat.h"
  22. #include "avio_internal.h"
  23. #include "internal.h"
  24. #include "libavcodec/internal.h"
  25. #include "libavcodec/bytestream.h"
  26. #include "libavutil/opt.h"
  27. #include "libavutil/dict.h"
  28. #include "libavutil/pixdesc.h"
  29. #include "libavutil/timestamp.h"
  30. #include "metadata.h"
  31. #include "id3v2.h"
  32. #include "libavutil/avassert.h"
  33. #include "libavutil/avstring.h"
  34. #include "libavutil/internal.h"
  35. #include "libavutil/mathematics.h"
  36. #include "libavutil/parseutils.h"
  37. #include "libavutil/time.h"
  38. #include "riff.h"
  39. #include "audiointerleave.h"
  40. #include "url.h"
  41. #include <stdarg.h>
  42. #if CONFIG_NETWORK
  43. #include "network.h"
  44. #endif
  45. #undef NDEBUG
  46. #include <assert.h>
  47. /**
  48. * @file
  49. * muxing functions for use within libavformat
  50. */
  51. /* fraction handling */
  52. /**
  53. * f = val + (num / den) + 0.5.
  54. *
  55. * 'num' is normalized so that it is such as 0 <= num < den.
  56. *
  57. * @param f fractional number
  58. * @param val integer value
  59. * @param num must be >= 0
  60. * @param den must be >= 1
  61. */
  62. static void frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
  63. {
  64. num += (den >> 1);
  65. if (num >= den) {
  66. val += num / den;
  67. num = num % den;
  68. }
  69. f->val = val;
  70. f->num = num;
  71. f->den = den;
  72. }
  73. /**
  74. * Fractional addition to f: f = f + (incr / f->den).
  75. *
  76. * @param f fractional number
  77. * @param incr increment, can be positive or negative
  78. */
  79. static void frac_add(AVFrac *f, int64_t incr)
  80. {
  81. int64_t num, den;
  82. num = f->num + incr;
  83. den = f->den;
  84. if (num < 0) {
  85. f->val += num / den;
  86. num = num % den;
  87. if (num < 0) {
  88. num += den;
  89. f->val--;
  90. }
  91. } else if (num >= den) {
  92. f->val += num / den;
  93. num = num % den;
  94. }
  95. f->num = num;
  96. }
  97. AVRational ff_choose_timebase(AVFormatContext *s, AVStream *st, int min_precission)
  98. {
  99. AVRational q;
  100. int j;
  101. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  102. q = (AVRational){1, st->codec->sample_rate};
  103. } else {
  104. q = st->codec->time_base;
  105. }
  106. for (j=2; j<14; j+= 1+(j>2))
  107. while (q.den / q.num < min_precission && q.num % j == 0)
  108. q.num /= j;
  109. while (q.den / q.num < min_precission && q.den < (1<<24))
  110. q.den <<= 1;
  111. return q;
  112. }
  113. int avformat_alloc_output_context2(AVFormatContext **avctx, AVOutputFormat *oformat,
  114. const char *format, const char *filename)
  115. {
  116. AVFormatContext *s = avformat_alloc_context();
  117. int ret = 0;
  118. *avctx = NULL;
  119. if (!s)
  120. goto nomem;
  121. if (!oformat) {
  122. if (format) {
  123. oformat = av_guess_format(format, NULL, NULL);
  124. if (!oformat) {
  125. av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
  126. ret = AVERROR(EINVAL);
  127. goto error;
  128. }
  129. } else {
  130. oformat = av_guess_format(NULL, filename, NULL);
  131. if (!oformat) {
  132. ret = AVERROR(EINVAL);
  133. av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
  134. filename);
  135. goto error;
  136. }
  137. }
  138. }
  139. s->oformat = oformat;
  140. if (s->oformat->priv_data_size > 0) {
  141. s->priv_data = av_mallocz(s->oformat->priv_data_size);
  142. if (!s->priv_data)
  143. goto nomem;
  144. if (s->oformat->priv_class) {
  145. *(const AVClass**)s->priv_data= s->oformat->priv_class;
  146. av_opt_set_defaults(s->priv_data);
  147. }
  148. } else
  149. s->priv_data = NULL;
  150. if (filename)
  151. av_strlcpy(s->filename, filename, sizeof(s->filename));
  152. *avctx = s;
  153. return 0;
  154. nomem:
  155. av_log(s, AV_LOG_ERROR, "Out of memory\n");
  156. ret = AVERROR(ENOMEM);
  157. error:
  158. avformat_free_context(s);
  159. return ret;
  160. }
  161. #if FF_API_ALLOC_OUTPUT_CONTEXT
  162. AVFormatContext *avformat_alloc_output_context(const char *format,
  163. AVOutputFormat *oformat, const char *filename)
  164. {
  165. AVFormatContext *avctx;
  166. int ret = avformat_alloc_output_context2(&avctx, oformat, format, filename);
  167. return ret < 0 ? NULL : avctx;
  168. }
  169. #endif
  170. static int validate_codec_tag(AVFormatContext *s, AVStream *st)
  171. {
  172. const AVCodecTag *avctag;
  173. int n;
  174. enum AVCodecID id = AV_CODEC_ID_NONE;
  175. int64_t tag = -1;
  176. /**
  177. * Check that tag + id is in the table
  178. * If neither is in the table -> OK
  179. * If tag is in the table with another id -> FAIL
  180. * If id is in the table with another tag -> FAIL unless strict < normal
  181. */
  182. for (n = 0; s->oformat->codec_tag[n]; n++) {
  183. avctag = s->oformat->codec_tag[n];
  184. while (avctag->id != AV_CODEC_ID_NONE) {
  185. if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codec->codec_tag)) {
  186. id = avctag->id;
  187. if (id == st->codec->codec_id)
  188. return 1;
  189. }
  190. if (avctag->id == st->codec->codec_id)
  191. tag = avctag->tag;
  192. avctag++;
  193. }
  194. }
  195. if (id != AV_CODEC_ID_NONE)
  196. return 0;
  197. if (tag >= 0 && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
  198. return 0;
  199. return 1;
  200. }
  201. static int init_muxer(AVFormatContext *s, AVDictionary **options)
  202. {
  203. int ret = 0, i;
  204. AVStream *st;
  205. AVDictionary *tmp = NULL;
  206. AVCodecContext *codec = NULL;
  207. AVOutputFormat *of = s->oformat;
  208. if (options)
  209. av_dict_copy(&tmp, *options, 0);
  210. if ((ret = av_opt_set_dict(s, &tmp)) < 0)
  211. goto fail;
  212. if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&
  213. (ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
  214. goto fail;
  215. // some sanity checks
  216. if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
  217. av_log(s, AV_LOG_ERROR, "No streams to mux were specified\n");
  218. ret = AVERROR(EINVAL);
  219. goto fail;
  220. }
  221. for (i = 0; i < s->nb_streams; i++) {
  222. st = s->streams[i];
  223. codec = st->codec;
  224. switch (codec->codec_type) {
  225. case AVMEDIA_TYPE_AUDIO:
  226. if (codec->sample_rate <= 0) {
  227. av_log(s, AV_LOG_ERROR, "sample rate not set\n");
  228. ret = AVERROR(EINVAL);
  229. goto fail;
  230. }
  231. if (!codec->block_align)
  232. codec->block_align = codec->channels *
  233. av_get_bits_per_sample(codec->codec_id) >> 3;
  234. break;
  235. case AVMEDIA_TYPE_VIDEO:
  236. if (codec->time_base.num <= 0 ||
  237. codec->time_base.den <= 0) { //FIXME audio too?
  238. av_log(s, AV_LOG_ERROR, "time base not set\n");
  239. ret = AVERROR(EINVAL);
  240. goto fail;
  241. }
  242. if ((codec->width <= 0 || codec->height <= 0) &&
  243. !(of->flags & AVFMT_NODIMENSIONS)) {
  244. av_log(s, AV_LOG_ERROR, "dimensions not set\n");
  245. ret = AVERROR(EINVAL);
  246. goto fail;
  247. }
  248. if (av_cmp_q(st->sample_aspect_ratio, codec->sample_aspect_ratio)
  249. && FFABS(av_q2d(st->sample_aspect_ratio) - av_q2d(codec->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
  250. ) {
  251. if (st->sample_aspect_ratio.num != 0 &&
  252. st->sample_aspect_ratio.den != 0 &&
  253. codec->sample_aspect_ratio.den != 0 &&
  254. codec->sample_aspect_ratio.den != 0) {
  255. av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
  256. "(%d/%d) and encoder layer (%d/%d)\n",
  257. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  258. codec->sample_aspect_ratio.num,
  259. codec->sample_aspect_ratio.den);
  260. ret = AVERROR(EINVAL);
  261. goto fail;
  262. }
  263. }
  264. break;
  265. }
  266. if (of->codec_tag) {
  267. if ( codec->codec_tag
  268. && codec->codec_id == AV_CODEC_ID_RAWVIDEO
  269. && ( av_codec_get_tag(of->codec_tag, codec->codec_id) == 0
  270. || av_codec_get_tag(of->codec_tag, codec->codec_id) == MKTAG('r', 'a', 'w', ' '))
  271. && !validate_codec_tag(s, st)) {
  272. // the current rawvideo encoding system ends up setting
  273. // the wrong codec_tag for avi/mov, we override it here
  274. codec->codec_tag = 0;
  275. }
  276. if (codec->codec_tag) {
  277. if (!validate_codec_tag(s, st)) {
  278. char tagbuf[32], tagbuf2[32];
  279. av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
  280. av_get_codec_tag_string(tagbuf2, sizeof(tagbuf2), av_codec_get_tag(s->oformat->codec_tag, codec->codec_id));
  281. av_log(s, AV_LOG_ERROR,
  282. "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",
  283. tagbuf, codec->codec_tag, codec->codec_id, tagbuf2);
  284. ret = AVERROR_INVALIDDATA;
  285. goto fail;
  286. }
  287. } else
  288. codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
  289. }
  290. if (of->flags & AVFMT_GLOBALHEADER &&
  291. !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
  292. av_log(s, AV_LOG_WARNING,
  293. "Codec for stream %d does not use global headers "
  294. "but container format requires global headers\n", i);
  295. if (codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
  296. s->internal->nb_interleaved_streams++;
  297. }
  298. if (!s->priv_data && of->priv_data_size > 0) {
  299. s->priv_data = av_mallocz(of->priv_data_size);
  300. if (!s->priv_data) {
  301. ret = AVERROR(ENOMEM);
  302. goto fail;
  303. }
  304. if (of->priv_class) {
  305. *(const AVClass **)s->priv_data = of->priv_class;
  306. av_opt_set_defaults(s->priv_data);
  307. if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
  308. goto fail;
  309. }
  310. }
  311. /* set muxer identification string */
  312. if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
  313. av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
  314. } else {
  315. av_dict_set(&s->metadata, "encoder", NULL, 0);
  316. }
  317. if (options) {
  318. av_dict_free(options);
  319. *options = tmp;
  320. }
  321. return 0;
  322. fail:
  323. av_dict_free(&tmp);
  324. return ret;
  325. }
  326. static int init_pts(AVFormatContext *s)
  327. {
  328. int i;
  329. AVStream *st;
  330. /* init PTS generation */
  331. for (i = 0; i < s->nb_streams; i++) {
  332. int64_t den = AV_NOPTS_VALUE;
  333. st = s->streams[i];
  334. switch (st->codec->codec_type) {
  335. case AVMEDIA_TYPE_AUDIO:
  336. den = (int64_t)st->time_base.num * st->codec->sample_rate;
  337. break;
  338. case AVMEDIA_TYPE_VIDEO:
  339. den = (int64_t)st->time_base.num * st->codec->time_base.den;
  340. break;
  341. default:
  342. break;
  343. }
  344. if (den != AV_NOPTS_VALUE) {
  345. if (den <= 0)
  346. return AVERROR_INVALIDDATA;
  347. frac_init(&st->pts, 0, 0, den);
  348. }
  349. }
  350. return 0;
  351. }
  352. int avformat_write_header(AVFormatContext *s, AVDictionary **options)
  353. {
  354. int ret = 0;
  355. if (ret = init_muxer(s, options))
  356. return ret;
  357. if (s->oformat->write_header) {
  358. ret = s->oformat->write_header(s);
  359. if (ret >= 0 && s->pb && s->pb->error < 0)
  360. ret = s->pb->error;
  361. if (ret < 0)
  362. return ret;
  363. }
  364. if ((ret = init_pts(s)) < 0)
  365. return ret;
  366. if (s->avoid_negative_ts < 0) {
  367. if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
  368. s->avoid_negative_ts = 0;
  369. } else
  370. s->avoid_negative_ts = 1;
  371. }
  372. return 0;
  373. }
  374. //FIXME merge with compute_pkt_fields
  375. static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
  376. {
  377. int delay = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames > 0);
  378. int num, den, frame_size, i;
  379. av_dlog(s, "compute_pkt_fields2: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
  380. av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
  381. /* duration field */
  382. if (pkt->duration == 0) {
  383. ff_compute_frame_duration(&num, &den, st, NULL, pkt);
  384. if (den && num) {
  385. pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
  386. }
  387. }
  388. if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
  389. pkt->pts = pkt->dts;
  390. //XXX/FIXME this is a temporary hack until all encoders output pts
  391. if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
  392. static int warned;
  393. if (!warned) {
  394. av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
  395. warned = 1;
  396. }
  397. pkt->dts =
  398. // pkt->pts= st->cur_dts;
  399. pkt->pts = st->pts.val;
  400. }
  401. //calculate dts from pts
  402. if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
  403. st->pts_buffer[0] = pkt->pts;
  404. for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
  405. st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
  406. for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
  407. FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
  408. pkt->dts = st->pts_buffer[0];
  409. }
  410. if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
  411. ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
  412. st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
  413. av_log(s, AV_LOG_ERROR,
  414. "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
  415. st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
  416. return AVERROR(EINVAL);
  417. }
  418. if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
  419. av_log(s, AV_LOG_ERROR, "pts (%s) < dts (%s) in stream %d\n",
  420. av_ts2str(pkt->pts), av_ts2str(pkt->dts), st->index);
  421. return AVERROR(EINVAL);
  422. }
  423. av_dlog(s, "av_write_frame: pts2:%s dts2:%s\n",
  424. av_ts2str(pkt->pts), av_ts2str(pkt->dts));
  425. st->cur_dts = pkt->dts;
  426. st->pts.val = pkt->dts;
  427. /* update pts */
  428. switch (st->codec->codec_type) {
  429. case AVMEDIA_TYPE_AUDIO:
  430. frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 1);
  431. /* HACK/FIXME, we skip the initial 0 size packets as they are most
  432. * likely equal to the encoder delay, but it would be better if we
  433. * had the real timestamps from the encoder */
  434. if (frame_size >= 0 && (pkt->size || st->pts.num != st->pts.den >> 1 || st->pts.val)) {
  435. frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
  436. }
  437. break;
  438. case AVMEDIA_TYPE_VIDEO:
  439. frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
  440. break;
  441. default:
  442. break;
  443. }
  444. return 0;
  445. }
  446. /**
  447. * Make timestamps non negative, move side data from payload to internal struct, call muxer, and restore
  448. * sidedata.
  449. *
  450. * FIXME: this function should NEVER get undefined pts/dts beside when the
  451. * AVFMT_NOTIMESTAMPS is set.
  452. * Those additional safety checks should be dropped once the correct checks
  453. * are set in the callers.
  454. */
  455. static int write_packet(AVFormatContext *s, AVPacket *pkt)
  456. {
  457. int ret, did_split;
  458. if (s->output_ts_offset) {
  459. AVStream *st = s->streams[pkt->stream_index];
  460. int64_t offset = av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
  461. if (pkt->dts != AV_NOPTS_VALUE)
  462. pkt->dts += offset;
  463. if (pkt->pts != AV_NOPTS_VALUE)
  464. pkt->pts += offset;
  465. }
  466. if (s->avoid_negative_ts > 0) {
  467. AVStream *st = s->streams[pkt->stream_index];
  468. int64_t offset = st->mux_ts_offset;
  469. if (pkt->dts < 0 && pkt->dts != AV_NOPTS_VALUE && !s->offset) {
  470. s->offset = -pkt->dts;
  471. s->offset_timebase = st->time_base;
  472. }
  473. if (s->offset && !offset) {
  474. offset = st->mux_ts_offset =
  475. av_rescale_q_rnd(s->offset,
  476. s->offset_timebase,
  477. st->time_base,
  478. AV_ROUND_UP);
  479. }
  480. if (pkt->dts != AV_NOPTS_VALUE)
  481. pkt->dts += offset;
  482. if (pkt->pts != AV_NOPTS_VALUE)
  483. pkt->pts += offset;
  484. av_assert2(pkt->dts == AV_NOPTS_VALUE || pkt->dts >= 0);
  485. }
  486. did_split = av_packet_split_side_data(pkt);
  487. ret = s->oformat->write_packet(s, pkt);
  488. if (s->flush_packets && s->pb && ret >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
  489. avio_flush(s->pb);
  490. if (did_split)
  491. av_packet_merge_side_data(pkt);
  492. return ret;
  493. }
  494. static int check_packet(AVFormatContext *s, AVPacket *pkt)
  495. {
  496. if (!pkt)
  497. return 0;
  498. if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
  499. av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
  500. pkt->stream_index);
  501. return AVERROR(EINVAL);
  502. }
  503. if (s->streams[pkt->stream_index]->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
  504. av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
  505. return AVERROR(EINVAL);
  506. }
  507. return 0;
  508. }
  509. int av_write_frame(AVFormatContext *s, AVPacket *pkt)
  510. {
  511. int ret;
  512. ret = check_packet(s, pkt);
  513. if (ret < 0)
  514. return ret;
  515. if (!pkt) {
  516. if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
  517. ret = s->oformat->write_packet(s, NULL);
  518. if (s->flush_packets && s->pb && s->pb->error >= 0)
  519. avio_flush(s->pb);
  520. if (ret >= 0 && s->pb && s->pb->error < 0)
  521. ret = s->pb->error;
  522. return ret;
  523. }
  524. return 1;
  525. }
  526. ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
  527. if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  528. return ret;
  529. ret = write_packet(s, pkt);
  530. if (ret >= 0 && s->pb && s->pb->error < 0)
  531. ret = s->pb->error;
  532. if (ret >= 0)
  533. s->streams[pkt->stream_index]->nb_frames++;
  534. return ret;
  535. }
  536. #define CHUNK_START 0x1000
  537. int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
  538. int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
  539. {
  540. AVPacketList **next_point, *this_pktl;
  541. AVStream *st = s->streams[pkt->stream_index];
  542. int chunked = s->max_chunk_size || s->max_chunk_duration;
  543. this_pktl = av_mallocz(sizeof(AVPacketList));
  544. if (!this_pktl)
  545. return AVERROR(ENOMEM);
  546. this_pktl->pkt = *pkt;
  547. #if FF_API_DESTRUCT_PACKET
  548. FF_DISABLE_DEPRECATION_WARNINGS
  549. pkt->destruct = NULL; // do not free original but only the copy
  550. FF_ENABLE_DEPRECATION_WARNINGS
  551. #endif
  552. pkt->buf = NULL;
  553. av_dup_packet(&this_pktl->pkt); // duplicate the packet if it uses non-allocated memory
  554. av_copy_packet_side_data(&this_pktl->pkt, &this_pktl->pkt); // copy side data
  555. if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
  556. next_point = &(st->last_in_packet_buffer->next);
  557. } else {
  558. next_point = &s->packet_buffer;
  559. }
  560. if (chunked) {
  561. uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
  562. st->interleaver_chunk_size += pkt->size;
  563. st->interleaver_chunk_duration += pkt->duration;
  564. if ( (s->max_chunk_size && st->interleaver_chunk_size > s->max_chunk_size)
  565. || (max && st->interleaver_chunk_duration > max)) {
  566. st->interleaver_chunk_size = 0;
  567. this_pktl->pkt.flags |= CHUNK_START;
  568. if (max && st->interleaver_chunk_duration > max) {
  569. int64_t syncoffset = (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
  570. int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;
  571. st->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
  572. } else
  573. st->interleaver_chunk_duration = 0;
  574. }
  575. }
  576. if (*next_point) {
  577. if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
  578. goto next_non_null;
  579. if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
  580. while ( *next_point
  581. && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
  582. || !compare(s, &(*next_point)->pkt, pkt)))
  583. next_point = &(*next_point)->next;
  584. if (*next_point)
  585. goto next_non_null;
  586. } else {
  587. next_point = &(s->packet_buffer_end->next);
  588. }
  589. }
  590. av_assert1(!*next_point);
  591. s->packet_buffer_end = this_pktl;
  592. next_non_null:
  593. this_pktl->next = *next_point;
  594. s->streams[pkt->stream_index]->last_in_packet_buffer =
  595. *next_point = this_pktl;
  596. return 0;
  597. }
  598. static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
  599. AVPacket *pkt)
  600. {
  601. AVStream *st = s->streams[pkt->stream_index];
  602. AVStream *st2 = s->streams[next->stream_index];
  603. int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
  604. st->time_base);
  605. if (s->audio_preload && ((st->codec->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codec->codec_type == AVMEDIA_TYPE_AUDIO))) {
  606. int64_t ts = av_rescale_q(pkt ->dts, st ->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO);
  607. int64_t ts2= av_rescale_q(next->dts, st2->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO);
  608. if (ts == ts2) {
  609. ts= ( pkt ->dts* st->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO)* st->time_base.den)*st2->time_base.den
  610. -( next->dts*st2->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO)*st2->time_base.den)* st->time_base.den;
  611. ts2=0;
  612. }
  613. comp= (ts>ts2) - (ts<ts2);
  614. }
  615. if (comp == 0)
  616. return pkt->stream_index < next->stream_index;
  617. return comp > 0;
  618. }
  619. int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
  620. AVPacket *pkt, int flush)
  621. {
  622. AVPacketList *pktl;
  623. int stream_count = 0, noninterleaved_count = 0;
  624. int i, ret;
  625. if (pkt) {
  626. ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts);
  627. if (ret < 0)
  628. return ret;
  629. }
  630. for (i = 0; i < s->nb_streams; i++) {
  631. if (s->streams[i]->last_in_packet_buffer) {
  632. ++stream_count;
  633. } else if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  634. ++noninterleaved_count;
  635. }
  636. }
  637. if (s->internal->nb_interleaved_streams == stream_count)
  638. flush = 1;
  639. if (s->max_interleave_delta > 0 && s->packet_buffer && !flush) {
  640. AVPacket *top_pkt = &s->packet_buffer->pkt;
  641. int64_t delta_dts = INT64_MIN;
  642. int64_t top_dts = av_rescale_q(top_pkt->dts,
  643. s->streams[top_pkt->stream_index]->time_base,
  644. AV_TIME_BASE_Q);
  645. for (i = 0; i < s->nb_streams; i++) {
  646. int64_t last_dts;
  647. const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
  648. if (!last)
  649. continue;
  650. last_dts = av_rescale_q(last->pkt.dts,
  651. s->streams[i]->time_base,
  652. AV_TIME_BASE_Q);
  653. delta_dts = FFMAX(delta_dts, last_dts - top_dts);
  654. }
  655. if (delta_dts > s->max_interleave_delta) {
  656. av_log(s, AV_LOG_DEBUG,
  657. "Delay between the first packet and last packet in the "
  658. "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
  659. delta_dts, s->max_interleave_delta);
  660. flush = 1;
  661. }
  662. }
  663. if (stream_count && flush) {
  664. AVStream *st;
  665. pktl = s->packet_buffer;
  666. *out = pktl->pkt;
  667. st = s->streams[out->stream_index];
  668. s->packet_buffer = pktl->next;
  669. if (!s->packet_buffer)
  670. s->packet_buffer_end = NULL;
  671. if (st->last_in_packet_buffer == pktl)
  672. st->last_in_packet_buffer = NULL;
  673. av_freep(&pktl);
  674. return 1;
  675. } else {
  676. av_init_packet(out);
  677. return 0;
  678. }
  679. }
  680. /**
  681. * Interleave an AVPacket correctly so it can be muxed.
  682. * @param out the interleaved packet will be output here
  683. * @param in the input packet
  684. * @param flush 1 if no further packets are available as input and all
  685. * remaining packets should be output
  686. * @return 1 if a packet was output, 0 if no packet could be output,
  687. * < 0 if an error occurred
  688. */
  689. static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
  690. {
  691. if (s->oformat->interleave_packet) {
  692. int ret = s->oformat->interleave_packet(s, out, in, flush);
  693. if (in)
  694. av_free_packet(in);
  695. return ret;
  696. } else
  697. return ff_interleave_packet_per_dts(s, out, in, flush);
  698. }
  699. int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
  700. {
  701. int ret, flush = 0;
  702. ret = check_packet(s, pkt);
  703. if (ret < 0)
  704. goto fail;
  705. if (pkt) {
  706. AVStream *st = s->streams[pkt->stream_index];
  707. //FIXME/XXX/HACK drop zero sized packets
  708. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size == 0) {
  709. ret = 0;
  710. goto fail;
  711. }
  712. av_dlog(s, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
  713. pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
  714. if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  715. goto fail;
  716. if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
  717. ret = AVERROR(EINVAL);
  718. goto fail;
  719. }
  720. } else {
  721. av_dlog(s, "av_interleaved_write_frame FLUSH\n");
  722. flush = 1;
  723. }
  724. for (;; ) {
  725. AVPacket opkt;
  726. int ret = interleave_packet(s, &opkt, pkt, flush);
  727. if (pkt) {
  728. memset(pkt, 0, sizeof(*pkt));
  729. av_init_packet(pkt);
  730. pkt = NULL;
  731. }
  732. if (ret <= 0) //FIXME cleanup needed for ret<0 ?
  733. return ret;
  734. ret = write_packet(s, &opkt);
  735. if (ret >= 0)
  736. s->streams[opkt.stream_index]->nb_frames++;
  737. av_free_packet(&opkt);
  738. if (ret < 0)
  739. return ret;
  740. if(s->pb && s->pb->error)
  741. return s->pb->error;
  742. }
  743. fail:
  744. av_packet_unref(pkt);
  745. return ret;
  746. }
  747. int av_write_trailer(AVFormatContext *s)
  748. {
  749. int ret, i;
  750. for (;; ) {
  751. AVPacket pkt;
  752. ret = interleave_packet(s, &pkt, NULL, 1);
  753. if (ret < 0) //FIXME cleanup needed for ret<0 ?
  754. goto fail;
  755. if (!ret)
  756. break;
  757. ret = write_packet(s, &pkt);
  758. if (ret >= 0)
  759. s->streams[pkt.stream_index]->nb_frames++;
  760. av_free_packet(&pkt);
  761. if (ret < 0)
  762. goto fail;
  763. if(s->pb && s->pb->error)
  764. goto fail;
  765. }
  766. if (s->oformat->write_trailer)
  767. ret = s->oformat->write_trailer(s);
  768. fail:
  769. if (s->pb)
  770. avio_flush(s->pb);
  771. if (ret == 0)
  772. ret = s->pb ? s->pb->error : 0;
  773. for (i = 0; i < s->nb_streams; i++) {
  774. av_freep(&s->streams[i]->priv_data);
  775. av_freep(&s->streams[i]->index_entries);
  776. }
  777. if (s->oformat->priv_class)
  778. av_opt_free(s->priv_data);
  779. av_freep(&s->priv_data);
  780. return ret;
  781. }
  782. int av_get_output_timestamp(struct AVFormatContext *s, int stream,
  783. int64_t *dts, int64_t *wall)
  784. {
  785. if (!s->oformat || !s->oformat->get_output_timestamp)
  786. return AVERROR(ENOSYS);
  787. s->oformat->get_output_timestamp(s, stream, dts, wall);
  788. return 0;
  789. }
  790. int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
  791. AVFormatContext *src)
  792. {
  793. AVPacket local_pkt;
  794. local_pkt = *pkt;
  795. local_pkt.stream_index = dst_stream;
  796. if (pkt->pts != AV_NOPTS_VALUE)
  797. local_pkt.pts = av_rescale_q(pkt->pts,
  798. src->streams[pkt->stream_index]->time_base,
  799. dst->streams[dst_stream]->time_base);
  800. if (pkt->dts != AV_NOPTS_VALUE)
  801. local_pkt.dts = av_rescale_q(pkt->dts,
  802. src->streams[pkt->stream_index]->time_base,
  803. dst->streams[dst_stream]->time_base);
  804. if (pkt->duration)
  805. local_pkt.duration = av_rescale_q(pkt->duration,
  806. src->streams[pkt->stream_index]->time_base,
  807. dst->streams[dst_stream]->time_base);
  808. return av_write_frame(dst, &local_pkt);
  809. }