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.

2011 lines
65KB

  1. /*
  2. * generic decoding-related code
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include <stdint.h>
  21. #include <string.h>
  22. #include "config.h"
  23. #if CONFIG_ICONV
  24. # include <iconv.h>
  25. #endif
  26. #include "libavutil/avassert.h"
  27. #include "libavutil/avstring.h"
  28. #include "libavutil/bprint.h"
  29. #include "libavutil/common.h"
  30. #include "libavutil/frame.h"
  31. #include "libavutil/hwcontext.h"
  32. #include "libavutil/imgutils.h"
  33. #include "libavutil/internal.h"
  34. #include "libavutil/intmath.h"
  35. #include "libavutil/opt.h"
  36. #include "avcodec.h"
  37. #include "bytestream.h"
  38. #include "decode.h"
  39. #include "hwconfig.h"
  40. #include "internal.h"
  41. #include "thread.h"
  42. typedef struct FramePool {
  43. /**
  44. * Pools for each data plane. For audio all the planes have the same size,
  45. * so only pools[0] is used.
  46. */
  47. AVBufferPool *pools[4];
  48. /*
  49. * Pool parameters
  50. */
  51. int format;
  52. int width, height;
  53. int stride_align[AV_NUM_DATA_POINTERS];
  54. int linesize[4];
  55. int planes;
  56. int channels;
  57. int samples;
  58. } FramePool;
  59. static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
  60. {
  61. int ret;
  62. buffer_size_t size;
  63. const uint8_t *data;
  64. uint32_t flags;
  65. int64_t val;
  66. data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
  67. if (!data)
  68. return 0;
  69. if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
  70. av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
  71. "changes, but PARAM_CHANGE side data was sent to it.\n");
  72. ret = AVERROR(EINVAL);
  73. goto fail2;
  74. }
  75. if (size < 4)
  76. goto fail;
  77. flags = bytestream_get_le32(&data);
  78. size -= 4;
  79. if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
  80. if (size < 4)
  81. goto fail;
  82. val = bytestream_get_le32(&data);
  83. if (val <= 0 || val > INT_MAX) {
  84. av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
  85. ret = AVERROR_INVALIDDATA;
  86. goto fail2;
  87. }
  88. avctx->channels = val;
  89. size -= 4;
  90. }
  91. if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
  92. if (size < 8)
  93. goto fail;
  94. avctx->channel_layout = bytestream_get_le64(&data);
  95. size -= 8;
  96. }
  97. if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
  98. if (size < 4)
  99. goto fail;
  100. val = bytestream_get_le32(&data);
  101. if (val <= 0 || val > INT_MAX) {
  102. av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
  103. ret = AVERROR_INVALIDDATA;
  104. goto fail2;
  105. }
  106. avctx->sample_rate = val;
  107. size -= 4;
  108. }
  109. if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
  110. if (size < 8)
  111. goto fail;
  112. avctx->width = bytestream_get_le32(&data);
  113. avctx->height = bytestream_get_le32(&data);
  114. size -= 8;
  115. ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
  116. if (ret < 0)
  117. goto fail2;
  118. }
  119. return 0;
  120. fail:
  121. av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
  122. ret = AVERROR_INVALIDDATA;
  123. fail2:
  124. if (ret < 0) {
  125. av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
  126. if (avctx->err_recognition & AV_EF_EXPLODE)
  127. return ret;
  128. }
  129. return 0;
  130. }
  131. #define IS_EMPTY(pkt) (!(pkt)->data)
  132. static int copy_packet_props(AVPacket *dst, const AVPacket *src)
  133. {
  134. int ret = av_packet_copy_props(dst, src);
  135. if (ret < 0)
  136. return ret;
  137. dst->size = src->size; // HACK: Needed for ff_decode_frame_props().
  138. dst->data = (void*)1; // HACK: Needed for IS_EMPTY().
  139. return 0;
  140. }
  141. static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
  142. {
  143. AVPacket tmp = { 0 };
  144. int ret = 0;
  145. if (IS_EMPTY(avci->last_pkt_props)) {
  146. if (av_fifo_size(avci->pkt_props) >= sizeof(*pkt)) {
  147. av_fifo_generic_read(avci->pkt_props, avci->last_pkt_props,
  148. sizeof(*avci->last_pkt_props), NULL);
  149. } else
  150. return copy_packet_props(avci->last_pkt_props, pkt);
  151. }
  152. if (av_fifo_space(avci->pkt_props) < sizeof(*pkt)) {
  153. ret = av_fifo_grow(avci->pkt_props, sizeof(*pkt));
  154. if (ret < 0)
  155. return ret;
  156. }
  157. ret = copy_packet_props(&tmp, pkt);
  158. if (ret < 0)
  159. return ret;
  160. av_fifo_generic_write(avci->pkt_props, &tmp, sizeof(tmp), NULL);
  161. return 0;
  162. }
  163. int ff_decode_bsfs_init(AVCodecContext *avctx)
  164. {
  165. AVCodecInternal *avci = avctx->internal;
  166. int ret;
  167. if (avci->bsf)
  168. return 0;
  169. ret = av_bsf_list_parse_str(avctx->codec->bsfs, &avci->bsf);
  170. if (ret < 0) {
  171. av_log(avctx, AV_LOG_ERROR, "Error parsing decoder bitstream filters '%s': %s\n", avctx->codec->bsfs, av_err2str(ret));
  172. if (ret != AVERROR(ENOMEM))
  173. ret = AVERROR_BUG;
  174. goto fail;
  175. }
  176. /* We do not currently have an API for passing the input timebase into decoders,
  177. * but no filters used here should actually need it.
  178. * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
  179. avci->bsf->time_base_in = (AVRational){ 1, 90000 };
  180. ret = avcodec_parameters_from_context(avci->bsf->par_in, avctx);
  181. if (ret < 0)
  182. goto fail;
  183. ret = av_bsf_init(avci->bsf);
  184. if (ret < 0)
  185. goto fail;
  186. return 0;
  187. fail:
  188. av_bsf_free(&avci->bsf);
  189. return ret;
  190. }
  191. int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
  192. {
  193. AVCodecInternal *avci = avctx->internal;
  194. int ret;
  195. if (avci->draining)
  196. return AVERROR_EOF;
  197. ret = av_bsf_receive_packet(avci->bsf, pkt);
  198. if (ret == AVERROR_EOF)
  199. avci->draining = 1;
  200. if (ret < 0)
  201. return ret;
  202. ret = extract_packet_props(avctx->internal, pkt);
  203. if (ret < 0)
  204. goto finish;
  205. ret = apply_param_change(avctx, pkt);
  206. if (ret < 0)
  207. goto finish;
  208. #if FF_API_OLD_ENCDEC
  209. if (avctx->codec->receive_frame)
  210. avci->compat_decode_consumed += pkt->size;
  211. #endif
  212. return 0;
  213. finish:
  214. av_packet_unref(pkt);
  215. return ret;
  216. }
  217. /**
  218. * Attempt to guess proper monotonic timestamps for decoded video frames
  219. * which might have incorrect times. Input timestamps may wrap around, in
  220. * which case the output will as well.
  221. *
  222. * @param pts the pts field of the decoded AVPacket, as passed through
  223. * AVFrame.pts
  224. * @param dts the dts field of the decoded AVPacket
  225. * @return one of the input values, may be AV_NOPTS_VALUE
  226. */
  227. static int64_t guess_correct_pts(AVCodecContext *ctx,
  228. int64_t reordered_pts, int64_t dts)
  229. {
  230. int64_t pts = AV_NOPTS_VALUE;
  231. if (dts != AV_NOPTS_VALUE) {
  232. ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
  233. ctx->pts_correction_last_dts = dts;
  234. } else if (reordered_pts != AV_NOPTS_VALUE)
  235. ctx->pts_correction_last_dts = reordered_pts;
  236. if (reordered_pts != AV_NOPTS_VALUE) {
  237. ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
  238. ctx->pts_correction_last_pts = reordered_pts;
  239. } else if(dts != AV_NOPTS_VALUE)
  240. ctx->pts_correction_last_pts = dts;
  241. if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
  242. && reordered_pts != AV_NOPTS_VALUE)
  243. pts = reordered_pts;
  244. else
  245. pts = dts;
  246. return pts;
  247. }
  248. /*
  249. * The core of the receive_frame_wrapper for the decoders implementing
  250. * the simple API. Certain decoders might consume partial packets without
  251. * returning any output, so this function needs to be called in a loop until it
  252. * returns EAGAIN.
  253. **/
  254. static inline int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame, int64_t *discarded_samples)
  255. {
  256. AVCodecInternal *avci = avctx->internal;
  257. DecodeSimpleContext *ds = &avci->ds;
  258. AVPacket *pkt = ds->in_pkt;
  259. // copy to ensure we do not change pkt
  260. int got_frame, actual_got_frame;
  261. int ret;
  262. if (!pkt->data && !avci->draining) {
  263. av_packet_unref(pkt);
  264. ret = ff_decode_get_packet(avctx, pkt);
  265. if (ret < 0 && ret != AVERROR_EOF)
  266. return ret;
  267. }
  268. // Some codecs (at least wma lossless) will crash when feeding drain packets
  269. // after EOF was signaled.
  270. if (avci->draining_done)
  271. return AVERROR_EOF;
  272. if (!pkt->data &&
  273. !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
  274. avctx->active_thread_type & FF_THREAD_FRAME))
  275. return AVERROR_EOF;
  276. got_frame = 0;
  277. if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
  278. ret = ff_thread_decode_frame(avctx, frame, &got_frame, pkt);
  279. } else {
  280. ret = avctx->codec->decode(avctx, frame, &got_frame, pkt);
  281. if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
  282. frame->pkt_dts = pkt->dts;
  283. if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
  284. if(!avctx->has_b_frames)
  285. frame->pkt_pos = pkt->pos;
  286. //FIXME these should be under if(!avctx->has_b_frames)
  287. /* get_buffer is supposed to set frame parameters */
  288. if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
  289. if (!frame->sample_aspect_ratio.num) frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
  290. if (!frame->width) frame->width = avctx->width;
  291. if (!frame->height) frame->height = avctx->height;
  292. if (frame->format == AV_PIX_FMT_NONE) frame->format = avctx->pix_fmt;
  293. }
  294. }
  295. }
  296. emms_c();
  297. actual_got_frame = got_frame;
  298. if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
  299. if (frame->flags & AV_FRAME_FLAG_DISCARD)
  300. got_frame = 0;
  301. } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
  302. uint8_t *side;
  303. buffer_size_t side_size;
  304. uint32_t discard_padding = 0;
  305. uint8_t skip_reason = 0;
  306. uint8_t discard_reason = 0;
  307. if (ret >= 0 && got_frame) {
  308. if (frame->format == AV_SAMPLE_FMT_NONE)
  309. frame->format = avctx->sample_fmt;
  310. if (!frame->channel_layout)
  311. frame->channel_layout = avctx->channel_layout;
  312. if (!frame->channels)
  313. frame->channels = avctx->channels;
  314. if (!frame->sample_rate)
  315. frame->sample_rate = avctx->sample_rate;
  316. }
  317. side= av_packet_get_side_data(avci->last_pkt_props, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
  318. if(side && side_size>=10) {
  319. avci->skip_samples = AV_RL32(side) * avci->skip_samples_multiplier;
  320. discard_padding = AV_RL32(side + 4);
  321. av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
  322. avci->skip_samples, (int)discard_padding);
  323. skip_reason = AV_RL8(side + 8);
  324. discard_reason = AV_RL8(side + 9);
  325. }
  326. if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
  327. !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
  328. avci->skip_samples = FFMAX(0, avci->skip_samples - frame->nb_samples);
  329. got_frame = 0;
  330. *discarded_samples += frame->nb_samples;
  331. }
  332. if (avci->skip_samples > 0 && got_frame &&
  333. !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
  334. if(frame->nb_samples <= avci->skip_samples){
  335. got_frame = 0;
  336. *discarded_samples += frame->nb_samples;
  337. avci->skip_samples -= frame->nb_samples;
  338. av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
  339. avci->skip_samples);
  340. } else {
  341. av_samples_copy(frame->extended_data, frame->extended_data, 0, avci->skip_samples,
  342. frame->nb_samples - avci->skip_samples, avctx->channels, frame->format);
  343. if(avctx->pkt_timebase.num && avctx->sample_rate) {
  344. int64_t diff_ts = av_rescale_q(avci->skip_samples,
  345. (AVRational){1, avctx->sample_rate},
  346. avctx->pkt_timebase);
  347. if(frame->pts!=AV_NOPTS_VALUE)
  348. frame->pts += diff_ts;
  349. #if FF_API_PKT_PTS
  350. FF_DISABLE_DEPRECATION_WARNINGS
  351. if(frame->pkt_pts!=AV_NOPTS_VALUE)
  352. frame->pkt_pts += diff_ts;
  353. FF_ENABLE_DEPRECATION_WARNINGS
  354. #endif
  355. if(frame->pkt_dts!=AV_NOPTS_VALUE)
  356. frame->pkt_dts += diff_ts;
  357. if (frame->pkt_duration >= diff_ts)
  358. frame->pkt_duration -= diff_ts;
  359. } else {
  360. av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
  361. }
  362. av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
  363. avci->skip_samples, frame->nb_samples);
  364. *discarded_samples += avci->skip_samples;
  365. frame->nb_samples -= avci->skip_samples;
  366. avci->skip_samples = 0;
  367. }
  368. }
  369. if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
  370. !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
  371. if (discard_padding == frame->nb_samples) {
  372. *discarded_samples += frame->nb_samples;
  373. got_frame = 0;
  374. } else {
  375. if(avctx->pkt_timebase.num && avctx->sample_rate) {
  376. int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
  377. (AVRational){1, avctx->sample_rate},
  378. avctx->pkt_timebase);
  379. frame->pkt_duration = diff_ts;
  380. } else {
  381. av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
  382. }
  383. av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
  384. (int)discard_padding, frame->nb_samples);
  385. frame->nb_samples -= discard_padding;
  386. }
  387. }
  388. if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
  389. AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
  390. if (fside) {
  391. AV_WL32(fside->data, avci->skip_samples);
  392. AV_WL32(fside->data + 4, discard_padding);
  393. AV_WL8(fside->data + 8, skip_reason);
  394. AV_WL8(fside->data + 9, discard_reason);
  395. avci->skip_samples = 0;
  396. }
  397. }
  398. }
  399. if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
  400. !avci->showed_multi_packet_warning &&
  401. ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
  402. av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
  403. avci->showed_multi_packet_warning = 1;
  404. }
  405. if (!got_frame)
  406. av_frame_unref(frame);
  407. if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
  408. ret = pkt->size;
  409. #if FF_API_AVCTX_TIMEBASE
  410. if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
  411. avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
  412. #endif
  413. /* do not stop draining when actual_got_frame != 0 or ret < 0 */
  414. /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
  415. if (avci->draining && !actual_got_frame) {
  416. if (ret < 0) {
  417. /* prevent infinite loop if a decoder wrongly always return error on draining */
  418. /* reasonable nb_errors_max = maximum b frames + thread count */
  419. int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
  420. avctx->thread_count : 1);
  421. if (avci->nb_draining_errors++ >= nb_errors_max) {
  422. av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
  423. "Stop draining and force EOF.\n");
  424. avci->draining_done = 1;
  425. ret = AVERROR_BUG;
  426. }
  427. } else {
  428. avci->draining_done = 1;
  429. }
  430. }
  431. #if FF_API_OLD_ENCDEC
  432. avci->compat_decode_consumed += ret;
  433. #endif
  434. if (ret >= pkt->size || ret < 0) {
  435. av_packet_unref(pkt);
  436. av_packet_unref(avci->last_pkt_props);
  437. } else {
  438. int consumed = ret;
  439. pkt->data += consumed;
  440. pkt->size -= consumed;
  441. avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
  442. pkt->pts = AV_NOPTS_VALUE;
  443. pkt->dts = AV_NOPTS_VALUE;
  444. avci->last_pkt_props->pts = AV_NOPTS_VALUE;
  445. avci->last_pkt_props->dts = AV_NOPTS_VALUE;
  446. }
  447. if (got_frame)
  448. av_assert0(frame->buf[0]);
  449. return ret < 0 ? ret : 0;
  450. }
  451. static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
  452. {
  453. int ret;
  454. int64_t discarded_samples = 0;
  455. while (!frame->buf[0]) {
  456. if (discarded_samples > avctx->max_samples)
  457. return AVERROR(EAGAIN);
  458. ret = decode_simple_internal(avctx, frame, &discarded_samples);
  459. if (ret < 0)
  460. return ret;
  461. }
  462. return 0;
  463. }
  464. static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
  465. {
  466. AVCodecInternal *avci = avctx->internal;
  467. int ret;
  468. av_assert0(!frame->buf[0]);
  469. if (avctx->codec->receive_frame) {
  470. ret = avctx->codec->receive_frame(avctx, frame);
  471. if (ret != AVERROR(EAGAIN))
  472. av_packet_unref(avci->last_pkt_props);
  473. } else
  474. ret = decode_simple_receive_frame(avctx, frame);
  475. if (ret == AVERROR_EOF)
  476. avci->draining_done = 1;
  477. if (!ret) {
  478. frame->best_effort_timestamp = guess_correct_pts(avctx,
  479. frame->pts,
  480. frame->pkt_dts);
  481. /* the only case where decode data is not set should be decoders
  482. * that do not call ff_get_buffer() */
  483. av_assert0((frame->private_ref && frame->private_ref->size == sizeof(FrameDecodeData)) ||
  484. !(avctx->codec->capabilities & AV_CODEC_CAP_DR1));
  485. if (frame->private_ref) {
  486. FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
  487. if (fdd->post_process) {
  488. ret = fdd->post_process(avctx, frame);
  489. if (ret < 0) {
  490. av_frame_unref(frame);
  491. return ret;
  492. }
  493. }
  494. }
  495. }
  496. /* free the per-frame decode data */
  497. av_buffer_unref(&frame->private_ref);
  498. return ret;
  499. }
  500. int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
  501. {
  502. AVCodecInternal *avci = avctx->internal;
  503. int ret;
  504. if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
  505. return AVERROR(EINVAL);
  506. if (avctx->internal->draining)
  507. return AVERROR_EOF;
  508. if (avpkt && !avpkt->size && avpkt->data)
  509. return AVERROR(EINVAL);
  510. av_packet_unref(avci->buffer_pkt);
  511. if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
  512. ret = av_packet_ref(avci->buffer_pkt, avpkt);
  513. if (ret < 0)
  514. return ret;
  515. }
  516. ret = av_bsf_send_packet(avci->bsf, avci->buffer_pkt);
  517. if (ret < 0) {
  518. av_packet_unref(avci->buffer_pkt);
  519. return ret;
  520. }
  521. if (!avci->buffer_frame->buf[0]) {
  522. ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
  523. if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
  524. return ret;
  525. }
  526. return 0;
  527. }
  528. static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
  529. {
  530. /* make sure we are noisy about decoders returning invalid cropping data */
  531. if (frame->crop_left >= INT_MAX - frame->crop_right ||
  532. frame->crop_top >= INT_MAX - frame->crop_bottom ||
  533. (frame->crop_left + frame->crop_right) >= frame->width ||
  534. (frame->crop_top + frame->crop_bottom) >= frame->height) {
  535. av_log(avctx, AV_LOG_WARNING,
  536. "Invalid cropping information set by a decoder: "
  537. "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
  538. "(frame size %dx%d). This is a bug, please report it\n",
  539. frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
  540. frame->width, frame->height);
  541. frame->crop_left = 0;
  542. frame->crop_right = 0;
  543. frame->crop_top = 0;
  544. frame->crop_bottom = 0;
  545. return 0;
  546. }
  547. if (!avctx->apply_cropping)
  548. return 0;
  549. return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
  550. AV_FRAME_CROP_UNALIGNED : 0);
  551. }
  552. int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
  553. {
  554. AVCodecInternal *avci = avctx->internal;
  555. int ret, changed;
  556. av_frame_unref(frame);
  557. if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
  558. return AVERROR(EINVAL);
  559. if (avci->buffer_frame->buf[0]) {
  560. av_frame_move_ref(frame, avci->buffer_frame);
  561. } else {
  562. ret = decode_receive_frame_internal(avctx, frame);
  563. if (ret < 0)
  564. return ret;
  565. }
  566. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  567. ret = apply_cropping(avctx, frame);
  568. if (ret < 0) {
  569. av_frame_unref(frame);
  570. return ret;
  571. }
  572. }
  573. avctx->frame_number++;
  574. if (avctx->flags & AV_CODEC_FLAG_DROPCHANGED) {
  575. if (avctx->frame_number == 1) {
  576. avci->initial_format = frame->format;
  577. switch(avctx->codec_type) {
  578. case AVMEDIA_TYPE_VIDEO:
  579. avci->initial_width = frame->width;
  580. avci->initial_height = frame->height;
  581. break;
  582. case AVMEDIA_TYPE_AUDIO:
  583. avci->initial_sample_rate = frame->sample_rate ? frame->sample_rate :
  584. avctx->sample_rate;
  585. avci->initial_channels = frame->channels;
  586. avci->initial_channel_layout = frame->channel_layout;
  587. break;
  588. }
  589. }
  590. if (avctx->frame_number > 1) {
  591. changed = avci->initial_format != frame->format;
  592. switch(avctx->codec_type) {
  593. case AVMEDIA_TYPE_VIDEO:
  594. changed |= avci->initial_width != frame->width ||
  595. avci->initial_height != frame->height;
  596. break;
  597. case AVMEDIA_TYPE_AUDIO:
  598. changed |= avci->initial_sample_rate != frame->sample_rate ||
  599. avci->initial_sample_rate != avctx->sample_rate ||
  600. avci->initial_channels != frame->channels ||
  601. avci->initial_channel_layout != frame->channel_layout;
  602. break;
  603. }
  604. if (changed) {
  605. avci->changed_frames_dropped++;
  606. av_log(avctx, AV_LOG_INFO, "dropped changed frame #%d pts %"PRId64
  607. " drop count: %d \n",
  608. avctx->frame_number, frame->pts,
  609. avci->changed_frames_dropped);
  610. av_frame_unref(frame);
  611. return AVERROR_INPUT_CHANGED;
  612. }
  613. }
  614. }
  615. return 0;
  616. }
  617. #if FF_API_OLD_ENCDEC
  618. FF_DISABLE_DEPRECATION_WARNINGS
  619. static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
  620. {
  621. int ret;
  622. /* move the original frame to our backup */
  623. av_frame_unref(avci->to_free);
  624. av_frame_move_ref(avci->to_free, frame);
  625. /* now copy everything except the AVBufferRefs back
  626. * note that we make a COPY of the side data, so calling av_frame_free() on
  627. * the caller's frame will work properly */
  628. ret = av_frame_copy_props(frame, avci->to_free);
  629. if (ret < 0)
  630. return ret;
  631. memcpy(frame->data, avci->to_free->data, sizeof(frame->data));
  632. memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
  633. if (avci->to_free->extended_data != avci->to_free->data) {
  634. int planes = avci->to_free->channels;
  635. int size = planes * sizeof(*frame->extended_data);
  636. if (!size) {
  637. av_frame_unref(frame);
  638. return AVERROR_BUG;
  639. }
  640. frame->extended_data = av_malloc(size);
  641. if (!frame->extended_data) {
  642. av_frame_unref(frame);
  643. return AVERROR(ENOMEM);
  644. }
  645. memcpy(frame->extended_data, avci->to_free->extended_data,
  646. size);
  647. } else
  648. frame->extended_data = frame->data;
  649. frame->format = avci->to_free->format;
  650. frame->width = avci->to_free->width;
  651. frame->height = avci->to_free->height;
  652. frame->channel_layout = avci->to_free->channel_layout;
  653. frame->nb_samples = avci->to_free->nb_samples;
  654. frame->channels = avci->to_free->channels;
  655. return 0;
  656. }
  657. static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
  658. int *got_frame, const AVPacket *pkt)
  659. {
  660. AVCodecInternal *avci = avctx->internal;
  661. int ret = 0;
  662. av_assert0(avci->compat_decode_consumed == 0);
  663. if (avci->draining_done && pkt && pkt->size != 0) {
  664. av_log(avctx, AV_LOG_WARNING, "Got unexpected packet after EOF\n");
  665. avcodec_flush_buffers(avctx);
  666. }
  667. *got_frame = 0;
  668. if (avci->compat_decode_partial_size > 0 &&
  669. avci->compat_decode_partial_size != pkt->size) {
  670. av_log(avctx, AV_LOG_ERROR,
  671. "Got unexpected packet size after a partial decode\n");
  672. ret = AVERROR(EINVAL);
  673. goto finish;
  674. }
  675. if (!avci->compat_decode_partial_size) {
  676. ret = avcodec_send_packet(avctx, pkt);
  677. if (ret == AVERROR_EOF)
  678. ret = 0;
  679. else if (ret == AVERROR(EAGAIN)) {
  680. /* we fully drain all the output in each decode call, so this should not
  681. * ever happen */
  682. ret = AVERROR_BUG;
  683. goto finish;
  684. } else if (ret < 0)
  685. goto finish;
  686. }
  687. while (ret >= 0) {
  688. ret = avcodec_receive_frame(avctx, frame);
  689. if (ret < 0) {
  690. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  691. ret = 0;
  692. goto finish;
  693. }
  694. if (frame != avci->compat_decode_frame) {
  695. if (!avctx->refcounted_frames) {
  696. ret = unrefcount_frame(avci, frame);
  697. if (ret < 0)
  698. goto finish;
  699. }
  700. *got_frame = 1;
  701. frame = avci->compat_decode_frame;
  702. } else {
  703. if (!avci->compat_decode_warned) {
  704. av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
  705. "API cannot return all the frames for this decoder. "
  706. "Some frames will be dropped. Update your code to the "
  707. "new decoding API to fix this.\n");
  708. avci->compat_decode_warned = 1;
  709. }
  710. }
  711. if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
  712. break;
  713. }
  714. finish:
  715. if (ret == 0) {
  716. /* if there are any bsfs then assume full packet is always consumed */
  717. if (avctx->codec->bsfs)
  718. ret = pkt->size;
  719. else
  720. ret = FFMIN(avci->compat_decode_consumed, pkt->size);
  721. }
  722. avci->compat_decode_consumed = 0;
  723. avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
  724. return ret;
  725. }
  726. int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
  727. int *got_picture_ptr,
  728. const AVPacket *avpkt)
  729. {
  730. return compat_decode(avctx, picture, got_picture_ptr, avpkt);
  731. }
  732. int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
  733. AVFrame *frame,
  734. int *got_frame_ptr,
  735. const AVPacket *avpkt)
  736. {
  737. return compat_decode(avctx, frame, got_frame_ptr, avpkt);
  738. }
  739. FF_ENABLE_DEPRECATION_WARNINGS
  740. #endif
  741. static void get_subtitle_defaults(AVSubtitle *sub)
  742. {
  743. memset(sub, 0, sizeof(*sub));
  744. sub->pts = AV_NOPTS_VALUE;
  745. }
  746. #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
  747. static int recode_subtitle(AVCodecContext *avctx, AVPacket **outpkt,
  748. AVPacket *inpkt, AVPacket *buf_pkt)
  749. {
  750. #if CONFIG_ICONV
  751. iconv_t cd = (iconv_t)-1;
  752. int ret = 0;
  753. char *inb, *outb;
  754. size_t inl, outl;
  755. #endif
  756. if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0) {
  757. *outpkt = inpkt;
  758. return 0;
  759. }
  760. #if CONFIG_ICONV
  761. inb = inpkt->data;
  762. inl = inpkt->size;
  763. if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
  764. av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
  765. return AVERROR(ERANGE);
  766. }
  767. cd = iconv_open("UTF-8", avctx->sub_charenc);
  768. av_assert0(cd != (iconv_t)-1);
  769. ret = av_new_packet(buf_pkt, inl * UTF8_MAX_BYTES);
  770. if (ret < 0)
  771. goto end;
  772. ret = av_packet_copy_props(buf_pkt, inpkt);
  773. if (ret < 0)
  774. goto end;
  775. outb = buf_pkt->data;
  776. outl = buf_pkt->size;
  777. if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
  778. iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
  779. outl >= buf_pkt->size || inl != 0) {
  780. ret = FFMIN(AVERROR(errno), -1);
  781. av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
  782. "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
  783. goto end;
  784. }
  785. buf_pkt->size -= outl;
  786. memset(buf_pkt->data + buf_pkt->size, 0, outl);
  787. *outpkt = buf_pkt;
  788. ret = 0;
  789. end:
  790. if (ret < 0)
  791. av_packet_unref(buf_pkt);
  792. if (cd != (iconv_t)-1)
  793. iconv_close(cd);
  794. return ret;
  795. #else
  796. av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
  797. return AVERROR(EINVAL);
  798. #endif
  799. }
  800. static int utf8_check(const uint8_t *str)
  801. {
  802. const uint8_t *byte;
  803. uint32_t codepoint, min;
  804. while (*str) {
  805. byte = str;
  806. GET_UTF8(codepoint, *(byte++), return 0;);
  807. min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
  808. 1 << (5 * (byte - str) - 4);
  809. if (codepoint < min || codepoint >= 0x110000 ||
  810. codepoint == 0xFFFE /* BOM */ ||
  811. codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
  812. return 0;
  813. str = byte;
  814. }
  815. return 1;
  816. }
  817. #if FF_API_ASS_TIMING
  818. static void insert_ts(AVBPrint *buf, int ts)
  819. {
  820. if (ts == -1) {
  821. av_bprintf(buf, "9:59:59.99,");
  822. } else {
  823. int h, m, s;
  824. h = ts/360000; ts -= 360000*h;
  825. m = ts/ 6000; ts -= 6000*m;
  826. s = ts/ 100; ts -= 100*s;
  827. av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
  828. }
  829. }
  830. static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
  831. {
  832. int i;
  833. AVBPrint buf;
  834. av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
  835. for (i = 0; i < sub->num_rects; i++) {
  836. char *final_dialog;
  837. const char *dialog;
  838. AVSubtitleRect *rect = sub->rects[i];
  839. int ts_start, ts_duration = -1;
  840. long int layer;
  841. if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
  842. continue;
  843. av_bprint_clear(&buf);
  844. /* skip ReadOrder */
  845. dialog = strchr(rect->ass, ',');
  846. if (!dialog)
  847. continue;
  848. dialog++;
  849. /* extract Layer or Marked */
  850. layer = strtol(dialog, (char**)&dialog, 10);
  851. if (*dialog != ',')
  852. continue;
  853. dialog++;
  854. /* rescale timing to ASS time base (ms) */
  855. ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
  856. if (pkt->duration != -1)
  857. ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
  858. sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
  859. /* construct ASS (standalone file form with timestamps) string */
  860. av_bprintf(&buf, "Dialogue: %ld,", layer);
  861. insert_ts(&buf, ts_start);
  862. insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
  863. av_bprintf(&buf, "%s\r\n", dialog);
  864. final_dialog = av_strdup(buf.str);
  865. if (!av_bprint_is_complete(&buf) || !final_dialog) {
  866. av_freep(&final_dialog);
  867. av_bprint_finalize(&buf, NULL);
  868. return AVERROR(ENOMEM);
  869. }
  870. av_freep(&rect->ass);
  871. rect->ass = final_dialog;
  872. }
  873. av_bprint_finalize(&buf, NULL);
  874. return 0;
  875. }
  876. #endif
  877. int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
  878. int *got_sub_ptr,
  879. AVPacket *avpkt)
  880. {
  881. int ret = 0;
  882. if (!avpkt->data && avpkt->size) {
  883. av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
  884. return AVERROR(EINVAL);
  885. }
  886. if (!avctx->codec)
  887. return AVERROR(EINVAL);
  888. if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
  889. av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
  890. return AVERROR(EINVAL);
  891. }
  892. *got_sub_ptr = 0;
  893. get_subtitle_defaults(sub);
  894. if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
  895. AVCodecInternal *avci = avctx->internal;
  896. AVPacket *pkt;
  897. ret = recode_subtitle(avctx, &pkt, avpkt, avci->buffer_pkt);
  898. if (ret < 0)
  899. return ret;
  900. if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
  901. sub->pts = av_rescale_q(avpkt->pts,
  902. avctx->pkt_timebase, AV_TIME_BASE_Q);
  903. ret = avctx->codec->decode(avctx, sub, got_sub_ptr, pkt);
  904. av_assert1((ret >= 0) >= !!*got_sub_ptr &&
  905. !!*got_sub_ptr >= !!sub->num_rects);
  906. #if FF_API_ASS_TIMING
  907. if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
  908. && *got_sub_ptr && sub->num_rects) {
  909. const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
  910. : avctx->time_base;
  911. int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
  912. if (err < 0)
  913. ret = err;
  914. }
  915. #endif
  916. if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
  917. avctx->pkt_timebase.num) {
  918. AVRational ms = { 1, 1000 };
  919. sub->end_display_time = av_rescale_q(avpkt->duration,
  920. avctx->pkt_timebase, ms);
  921. }
  922. if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
  923. sub->format = 0;
  924. else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
  925. sub->format = 1;
  926. for (unsigned i = 0; i < sub->num_rects; i++) {
  927. if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_IGNORE &&
  928. sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
  929. av_log(avctx, AV_LOG_ERROR,
  930. "Invalid UTF-8 in decoded subtitles text; "
  931. "maybe missing -sub_charenc option\n");
  932. avsubtitle_free(sub);
  933. ret = AVERROR_INVALIDDATA;
  934. break;
  935. }
  936. }
  937. if (*got_sub_ptr)
  938. avctx->frame_number++;
  939. if (pkt == avci->buffer_pkt) // did we recode?
  940. av_packet_unref(avci->buffer_pkt);
  941. }
  942. return ret;
  943. }
  944. enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
  945. const enum AVPixelFormat *fmt)
  946. {
  947. const AVPixFmtDescriptor *desc;
  948. const AVCodecHWConfig *config;
  949. int i, n;
  950. // If a device was supplied when the codec was opened, assume that the
  951. // user wants to use it.
  952. if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
  953. AVHWDeviceContext *device_ctx =
  954. (AVHWDeviceContext*)avctx->hw_device_ctx->data;
  955. for (i = 0;; i++) {
  956. config = &avctx->codec->hw_configs[i]->public;
  957. if (!config)
  958. break;
  959. if (!(config->methods &
  960. AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
  961. continue;
  962. if (device_ctx->type != config->device_type)
  963. continue;
  964. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
  965. if (config->pix_fmt == fmt[n])
  966. return fmt[n];
  967. }
  968. }
  969. }
  970. // No device or other setup, so we have to choose from things which
  971. // don't any other external information.
  972. // If the last element of the list is a software format, choose it
  973. // (this should be best software format if any exist).
  974. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
  975. desc = av_pix_fmt_desc_get(fmt[n - 1]);
  976. if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
  977. return fmt[n - 1];
  978. // Finally, traverse the list in order and choose the first entry
  979. // with no external dependencies (if there is no hardware configuration
  980. // information available then this just picks the first entry).
  981. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
  982. for (i = 0;; i++) {
  983. config = avcodec_get_hw_config(avctx->codec, i);
  984. if (!config)
  985. break;
  986. if (config->pix_fmt == fmt[n])
  987. break;
  988. }
  989. if (!config) {
  990. // No specific config available, so the decoder must be able
  991. // to handle this format without any additional setup.
  992. return fmt[n];
  993. }
  994. if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
  995. // Usable with only internal setup.
  996. return fmt[n];
  997. }
  998. }
  999. // Nothing is usable, give up.
  1000. return AV_PIX_FMT_NONE;
  1001. }
  1002. int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
  1003. enum AVHWDeviceType dev_type)
  1004. {
  1005. AVHWDeviceContext *device_ctx;
  1006. AVHWFramesContext *frames_ctx;
  1007. int ret;
  1008. if (!avctx->hwaccel)
  1009. return AVERROR(ENOSYS);
  1010. if (avctx->hw_frames_ctx)
  1011. return 0;
  1012. if (!avctx->hw_device_ctx) {
  1013. av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
  1014. "required for hardware accelerated decoding.\n");
  1015. return AVERROR(EINVAL);
  1016. }
  1017. device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
  1018. if (device_ctx->type != dev_type) {
  1019. av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
  1020. "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
  1021. av_hwdevice_get_type_name(device_ctx->type));
  1022. return AVERROR(EINVAL);
  1023. }
  1024. ret = avcodec_get_hw_frames_parameters(avctx,
  1025. avctx->hw_device_ctx,
  1026. avctx->hwaccel->pix_fmt,
  1027. &avctx->hw_frames_ctx);
  1028. if (ret < 0)
  1029. return ret;
  1030. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  1031. if (frames_ctx->initial_pool_size) {
  1032. // We guarantee 4 base work surfaces. The function above guarantees 1
  1033. // (the absolute minimum), so add the missing count.
  1034. frames_ctx->initial_pool_size += 3;
  1035. }
  1036. ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
  1037. if (ret < 0) {
  1038. av_buffer_unref(&avctx->hw_frames_ctx);
  1039. return ret;
  1040. }
  1041. return 0;
  1042. }
  1043. int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
  1044. AVBufferRef *device_ref,
  1045. enum AVPixelFormat hw_pix_fmt,
  1046. AVBufferRef **out_frames_ref)
  1047. {
  1048. AVBufferRef *frames_ref = NULL;
  1049. const AVCodecHWConfigInternal *hw_config;
  1050. const AVHWAccel *hwa;
  1051. int i, ret;
  1052. for (i = 0;; i++) {
  1053. hw_config = avctx->codec->hw_configs[i];
  1054. if (!hw_config)
  1055. return AVERROR(ENOENT);
  1056. if (hw_config->public.pix_fmt == hw_pix_fmt)
  1057. break;
  1058. }
  1059. hwa = hw_config->hwaccel;
  1060. if (!hwa || !hwa->frame_params)
  1061. return AVERROR(ENOENT);
  1062. frames_ref = av_hwframe_ctx_alloc(device_ref);
  1063. if (!frames_ref)
  1064. return AVERROR(ENOMEM);
  1065. ret = hwa->frame_params(avctx, frames_ref);
  1066. if (ret >= 0) {
  1067. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
  1068. if (frames_ctx->initial_pool_size) {
  1069. // If the user has requested that extra output surfaces be
  1070. // available then add them here.
  1071. if (avctx->extra_hw_frames > 0)
  1072. frames_ctx->initial_pool_size += avctx->extra_hw_frames;
  1073. // If frame threading is enabled then an extra surface per thread
  1074. // is also required.
  1075. if (avctx->active_thread_type & FF_THREAD_FRAME)
  1076. frames_ctx->initial_pool_size += avctx->thread_count;
  1077. }
  1078. *out_frames_ref = frames_ref;
  1079. } else {
  1080. av_buffer_unref(&frames_ref);
  1081. }
  1082. return ret;
  1083. }
  1084. static int hwaccel_init(AVCodecContext *avctx,
  1085. const AVCodecHWConfigInternal *hw_config)
  1086. {
  1087. const AVHWAccel *hwaccel;
  1088. int err;
  1089. hwaccel = hw_config->hwaccel;
  1090. if (hwaccel->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
  1091. avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  1092. av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
  1093. hwaccel->name);
  1094. return AVERROR_PATCHWELCOME;
  1095. }
  1096. if (hwaccel->priv_data_size) {
  1097. avctx->internal->hwaccel_priv_data =
  1098. av_mallocz(hwaccel->priv_data_size);
  1099. if (!avctx->internal->hwaccel_priv_data)
  1100. return AVERROR(ENOMEM);
  1101. }
  1102. avctx->hwaccel = hwaccel;
  1103. if (hwaccel->init) {
  1104. err = hwaccel->init(avctx);
  1105. if (err < 0) {
  1106. av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
  1107. "hwaccel initialisation returned error.\n",
  1108. av_get_pix_fmt_name(hw_config->public.pix_fmt));
  1109. av_freep(&avctx->internal->hwaccel_priv_data);
  1110. avctx->hwaccel = NULL;
  1111. return err;
  1112. }
  1113. }
  1114. return 0;
  1115. }
  1116. static void hwaccel_uninit(AVCodecContext *avctx)
  1117. {
  1118. if (avctx->hwaccel && avctx->hwaccel->uninit)
  1119. avctx->hwaccel->uninit(avctx);
  1120. av_freep(&avctx->internal->hwaccel_priv_data);
  1121. avctx->hwaccel = NULL;
  1122. av_buffer_unref(&avctx->hw_frames_ctx);
  1123. }
  1124. int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
  1125. {
  1126. const AVPixFmtDescriptor *desc;
  1127. enum AVPixelFormat *choices;
  1128. enum AVPixelFormat ret, user_choice;
  1129. const AVCodecHWConfigInternal *hw_config;
  1130. const AVCodecHWConfig *config;
  1131. int i, n, err;
  1132. // Find end of list.
  1133. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
  1134. // Must contain at least one entry.
  1135. av_assert0(n >= 1);
  1136. // If a software format is available, it must be the last entry.
  1137. desc = av_pix_fmt_desc_get(fmt[n - 1]);
  1138. if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
  1139. // No software format is available.
  1140. } else {
  1141. avctx->sw_pix_fmt = fmt[n - 1];
  1142. }
  1143. choices = av_malloc_array(n + 1, sizeof(*choices));
  1144. if (!choices)
  1145. return AV_PIX_FMT_NONE;
  1146. memcpy(choices, fmt, (n + 1) * sizeof(*choices));
  1147. for (;;) {
  1148. // Remove the previous hwaccel, if there was one.
  1149. hwaccel_uninit(avctx);
  1150. user_choice = avctx->get_format(avctx, choices);
  1151. if (user_choice == AV_PIX_FMT_NONE) {
  1152. // Explicitly chose nothing, give up.
  1153. ret = AV_PIX_FMT_NONE;
  1154. break;
  1155. }
  1156. desc = av_pix_fmt_desc_get(user_choice);
  1157. if (!desc) {
  1158. av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
  1159. "get_format() callback.\n");
  1160. ret = AV_PIX_FMT_NONE;
  1161. break;
  1162. }
  1163. av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
  1164. desc->name);
  1165. for (i = 0; i < n; i++) {
  1166. if (choices[i] == user_choice)
  1167. break;
  1168. }
  1169. if (i == n) {
  1170. av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
  1171. "%s not in possible list.\n", desc->name);
  1172. ret = AV_PIX_FMT_NONE;
  1173. break;
  1174. }
  1175. if (avctx->codec->hw_configs) {
  1176. for (i = 0;; i++) {
  1177. hw_config = avctx->codec->hw_configs[i];
  1178. if (!hw_config)
  1179. break;
  1180. if (hw_config->public.pix_fmt == user_choice)
  1181. break;
  1182. }
  1183. } else {
  1184. hw_config = NULL;
  1185. }
  1186. if (!hw_config) {
  1187. // No config available, so no extra setup required.
  1188. ret = user_choice;
  1189. break;
  1190. }
  1191. config = &hw_config->public;
  1192. if (config->methods &
  1193. AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
  1194. avctx->hw_frames_ctx) {
  1195. const AVHWFramesContext *frames_ctx =
  1196. (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  1197. if (frames_ctx->format != user_choice) {
  1198. av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
  1199. "does not match the format of the provided frames "
  1200. "context.\n", desc->name);
  1201. goto try_again;
  1202. }
  1203. } else if (config->methods &
  1204. AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
  1205. avctx->hw_device_ctx) {
  1206. const AVHWDeviceContext *device_ctx =
  1207. (AVHWDeviceContext*)avctx->hw_device_ctx->data;
  1208. if (device_ctx->type != config->device_type) {
  1209. av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
  1210. "does not match the type of the provided device "
  1211. "context.\n", desc->name);
  1212. goto try_again;
  1213. }
  1214. } else if (config->methods &
  1215. AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
  1216. // Internal-only setup, no additional configuration.
  1217. } else if (config->methods &
  1218. AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
  1219. // Some ad-hoc configuration we can't see and can't check.
  1220. } else {
  1221. av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
  1222. "missing configuration.\n", desc->name);
  1223. goto try_again;
  1224. }
  1225. if (hw_config->hwaccel) {
  1226. av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
  1227. "initialisation.\n", desc->name);
  1228. err = hwaccel_init(avctx, hw_config);
  1229. if (err < 0)
  1230. goto try_again;
  1231. }
  1232. ret = user_choice;
  1233. break;
  1234. try_again:
  1235. av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
  1236. "get_format() without it.\n", desc->name);
  1237. for (i = 0; i < n; i++) {
  1238. if (choices[i] == user_choice)
  1239. break;
  1240. }
  1241. for (; i + 1 < n; i++)
  1242. choices[i] = choices[i + 1];
  1243. --n;
  1244. }
  1245. av_freep(&choices);
  1246. return ret;
  1247. }
  1248. static void frame_pool_free(void *opaque, uint8_t *data)
  1249. {
  1250. FramePool *pool = (FramePool*)data;
  1251. int i;
  1252. for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
  1253. av_buffer_pool_uninit(&pool->pools[i]);
  1254. av_freep(&data);
  1255. }
  1256. static AVBufferRef *frame_pool_alloc(void)
  1257. {
  1258. FramePool *pool = av_mallocz(sizeof(*pool));
  1259. AVBufferRef *buf;
  1260. if (!pool)
  1261. return NULL;
  1262. buf = av_buffer_create((uint8_t*)pool, sizeof(*pool),
  1263. frame_pool_free, NULL, 0);
  1264. if (!buf) {
  1265. av_freep(&pool);
  1266. return NULL;
  1267. }
  1268. return buf;
  1269. }
  1270. static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
  1271. {
  1272. FramePool *pool = avctx->internal->pool ?
  1273. (FramePool*)avctx->internal->pool->data : NULL;
  1274. AVBufferRef *pool_buf;
  1275. int i, ret, ch, planes;
  1276. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  1277. int planar = av_sample_fmt_is_planar(frame->format);
  1278. ch = frame->channels;
  1279. planes = planar ? ch : 1;
  1280. }
  1281. if (pool && pool->format == frame->format) {
  1282. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
  1283. pool->width == frame->width && pool->height == frame->height)
  1284. return 0;
  1285. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pool->planes == planes &&
  1286. pool->channels == ch && frame->nb_samples == pool->samples)
  1287. return 0;
  1288. }
  1289. pool_buf = frame_pool_alloc();
  1290. if (!pool_buf)
  1291. return AVERROR(ENOMEM);
  1292. pool = (FramePool*)pool_buf->data;
  1293. switch (avctx->codec_type) {
  1294. case AVMEDIA_TYPE_VIDEO: {
  1295. int linesize[4];
  1296. int w = frame->width;
  1297. int h = frame->height;
  1298. int unaligned;
  1299. ptrdiff_t linesize1[4];
  1300. size_t size[4];
  1301. avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
  1302. do {
  1303. // NOTE: do not align linesizes individually, this breaks e.g. assumptions
  1304. // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
  1305. ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
  1306. if (ret < 0)
  1307. goto fail;
  1308. // increase alignment of w for next try (rhs gives the lowest bit set in w)
  1309. w += w & ~(w - 1);
  1310. unaligned = 0;
  1311. for (i = 0; i < 4; i++)
  1312. unaligned |= linesize[i] % pool->stride_align[i];
  1313. } while (unaligned);
  1314. for (i = 0; i < 4; i++)
  1315. linesize1[i] = linesize[i];
  1316. ret = av_image_fill_plane_sizes(size, avctx->pix_fmt, h, linesize1);
  1317. if (ret < 0)
  1318. goto fail;
  1319. for (i = 0; i < 4; i++) {
  1320. pool->linesize[i] = linesize[i];
  1321. if (size[i]) {
  1322. if (size[i] > INT_MAX - (16 + STRIDE_ALIGN - 1)) {
  1323. ret = AVERROR(EINVAL);
  1324. goto fail;
  1325. }
  1326. pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
  1327. CONFIG_MEMORY_POISONING ?
  1328. NULL :
  1329. av_buffer_allocz);
  1330. if (!pool->pools[i]) {
  1331. ret = AVERROR(ENOMEM);
  1332. goto fail;
  1333. }
  1334. }
  1335. }
  1336. pool->format = frame->format;
  1337. pool->width = frame->width;
  1338. pool->height = frame->height;
  1339. break;
  1340. }
  1341. case AVMEDIA_TYPE_AUDIO: {
  1342. ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
  1343. frame->nb_samples, frame->format, 0);
  1344. if (ret < 0)
  1345. goto fail;
  1346. pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
  1347. if (!pool->pools[0]) {
  1348. ret = AVERROR(ENOMEM);
  1349. goto fail;
  1350. }
  1351. pool->format = frame->format;
  1352. pool->planes = planes;
  1353. pool->channels = ch;
  1354. pool->samples = frame->nb_samples;
  1355. break;
  1356. }
  1357. default: av_assert0(0);
  1358. }
  1359. av_buffer_unref(&avctx->internal->pool);
  1360. avctx->internal->pool = pool_buf;
  1361. return 0;
  1362. fail:
  1363. av_buffer_unref(&pool_buf);
  1364. return ret;
  1365. }
  1366. static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
  1367. {
  1368. FramePool *pool = (FramePool*)avctx->internal->pool->data;
  1369. int planes = pool->planes;
  1370. int i;
  1371. frame->linesize[0] = pool->linesize[0];
  1372. if (planes > AV_NUM_DATA_POINTERS) {
  1373. frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
  1374. frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
  1375. frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
  1376. sizeof(*frame->extended_buf));
  1377. if (!frame->extended_data || !frame->extended_buf) {
  1378. av_freep(&frame->extended_data);
  1379. av_freep(&frame->extended_buf);
  1380. return AVERROR(ENOMEM);
  1381. }
  1382. } else {
  1383. frame->extended_data = frame->data;
  1384. av_assert0(frame->nb_extended_buf == 0);
  1385. }
  1386. for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
  1387. frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
  1388. if (!frame->buf[i])
  1389. goto fail;
  1390. frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
  1391. }
  1392. for (i = 0; i < frame->nb_extended_buf; i++) {
  1393. frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
  1394. if (!frame->extended_buf[i])
  1395. goto fail;
  1396. frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
  1397. }
  1398. if (avctx->debug & FF_DEBUG_BUFFERS)
  1399. av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
  1400. return 0;
  1401. fail:
  1402. av_frame_unref(frame);
  1403. return AVERROR(ENOMEM);
  1404. }
  1405. static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
  1406. {
  1407. FramePool *pool = (FramePool*)s->internal->pool->data;
  1408. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
  1409. int i;
  1410. if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
  1411. av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
  1412. return -1;
  1413. }
  1414. if (!desc) {
  1415. av_log(s, AV_LOG_ERROR,
  1416. "Unable to get pixel format descriptor for format %s\n",
  1417. av_get_pix_fmt_name(pic->format));
  1418. return AVERROR(EINVAL);
  1419. }
  1420. memset(pic->data, 0, sizeof(pic->data));
  1421. pic->extended_data = pic->data;
  1422. for (i = 0; i < 4 && pool->pools[i]; i++) {
  1423. pic->linesize[i] = pool->linesize[i];
  1424. pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
  1425. if (!pic->buf[i])
  1426. goto fail;
  1427. pic->data[i] = pic->buf[i]->data;
  1428. }
  1429. for (; i < AV_NUM_DATA_POINTERS; i++) {
  1430. pic->data[i] = NULL;
  1431. pic->linesize[i] = 0;
  1432. }
  1433. if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
  1434. ((desc->flags & FF_PSEUDOPAL) && pic->data[1]))
  1435. avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
  1436. if (s->debug & FF_DEBUG_BUFFERS)
  1437. av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
  1438. return 0;
  1439. fail:
  1440. av_frame_unref(pic);
  1441. return AVERROR(ENOMEM);
  1442. }
  1443. int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
  1444. {
  1445. int ret;
  1446. if (avctx->hw_frames_ctx) {
  1447. ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
  1448. frame->width = avctx->coded_width;
  1449. frame->height = avctx->coded_height;
  1450. return ret;
  1451. }
  1452. if ((ret = update_frame_pool(avctx, frame)) < 0)
  1453. return ret;
  1454. switch (avctx->codec_type) {
  1455. case AVMEDIA_TYPE_VIDEO:
  1456. return video_get_buffer(avctx, frame);
  1457. case AVMEDIA_TYPE_AUDIO:
  1458. return audio_get_buffer(avctx, frame);
  1459. default:
  1460. return -1;
  1461. }
  1462. }
  1463. static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
  1464. {
  1465. buffer_size_t size;
  1466. const uint8_t *side_metadata;
  1467. AVDictionary **frame_md = &frame->metadata;
  1468. side_metadata = av_packet_get_side_data(avpkt,
  1469. AV_PKT_DATA_STRINGS_METADATA, &size);
  1470. return av_packet_unpack_dictionary(side_metadata, size, frame_md);
  1471. }
  1472. int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
  1473. {
  1474. AVPacket *pkt = avctx->internal->last_pkt_props;
  1475. int i;
  1476. static const struct {
  1477. enum AVPacketSideDataType packet;
  1478. enum AVFrameSideDataType frame;
  1479. } sd[] = {
  1480. { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
  1481. { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
  1482. { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
  1483. { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
  1484. { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
  1485. { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
  1486. { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
  1487. { AV_PKT_DATA_A53_CC, AV_FRAME_DATA_A53_CC },
  1488. { AV_PKT_DATA_ICC_PROFILE, AV_FRAME_DATA_ICC_PROFILE },
  1489. { AV_PKT_DATA_S12M_TIMECODE, AV_FRAME_DATA_S12M_TIMECODE },
  1490. };
  1491. if (IS_EMPTY(pkt) && av_fifo_size(avctx->internal->pkt_props) >= sizeof(*pkt))
  1492. av_fifo_generic_read(avctx->internal->pkt_props,
  1493. pkt, sizeof(*pkt), NULL);
  1494. if (pkt) {
  1495. frame->pts = pkt->pts;
  1496. #if FF_API_PKT_PTS
  1497. FF_DISABLE_DEPRECATION_WARNINGS
  1498. frame->pkt_pts = pkt->pts;
  1499. FF_ENABLE_DEPRECATION_WARNINGS
  1500. #endif
  1501. frame->pkt_pos = pkt->pos;
  1502. frame->pkt_duration = pkt->duration;
  1503. frame->pkt_size = pkt->size;
  1504. for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
  1505. buffer_size_t size;
  1506. uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
  1507. if (packet_sd) {
  1508. AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
  1509. sd[i].frame,
  1510. size);
  1511. if (!frame_sd)
  1512. return AVERROR(ENOMEM);
  1513. memcpy(frame_sd->data, packet_sd, size);
  1514. }
  1515. }
  1516. add_metadata_from_side_data(pkt, frame);
  1517. if (pkt->flags & AV_PKT_FLAG_DISCARD) {
  1518. frame->flags |= AV_FRAME_FLAG_DISCARD;
  1519. } else {
  1520. frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
  1521. }
  1522. }
  1523. frame->reordered_opaque = avctx->reordered_opaque;
  1524. if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
  1525. frame->color_primaries = avctx->color_primaries;
  1526. if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
  1527. frame->color_trc = avctx->color_trc;
  1528. if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
  1529. frame->colorspace = avctx->colorspace;
  1530. if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
  1531. frame->color_range = avctx->color_range;
  1532. if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
  1533. frame->chroma_location = avctx->chroma_sample_location;
  1534. switch (avctx->codec->type) {
  1535. case AVMEDIA_TYPE_VIDEO:
  1536. frame->format = avctx->pix_fmt;
  1537. if (!frame->sample_aspect_ratio.num)
  1538. frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
  1539. if (frame->width && frame->height &&
  1540. av_image_check_sar(frame->width, frame->height,
  1541. frame->sample_aspect_ratio) < 0) {
  1542. av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
  1543. frame->sample_aspect_ratio.num,
  1544. frame->sample_aspect_ratio.den);
  1545. frame->sample_aspect_ratio = (AVRational){ 0, 1 };
  1546. }
  1547. break;
  1548. case AVMEDIA_TYPE_AUDIO:
  1549. if (!frame->sample_rate)
  1550. frame->sample_rate = avctx->sample_rate;
  1551. if (frame->format < 0)
  1552. frame->format = avctx->sample_fmt;
  1553. if (!frame->channel_layout) {
  1554. if (avctx->channel_layout) {
  1555. if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
  1556. avctx->channels) {
  1557. av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
  1558. "configuration.\n");
  1559. return AVERROR(EINVAL);
  1560. }
  1561. frame->channel_layout = avctx->channel_layout;
  1562. } else {
  1563. if (avctx->channels > FF_SANE_NB_CHANNELS) {
  1564. av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
  1565. avctx->channels);
  1566. return AVERROR(ENOSYS);
  1567. }
  1568. }
  1569. }
  1570. frame->channels = avctx->channels;
  1571. break;
  1572. }
  1573. return 0;
  1574. }
  1575. static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
  1576. {
  1577. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  1578. int i;
  1579. int num_planes = av_pix_fmt_count_planes(frame->format);
  1580. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
  1581. int flags = desc ? desc->flags : 0;
  1582. if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
  1583. num_planes = 2;
  1584. if ((flags & FF_PSEUDOPAL) && frame->data[1])
  1585. num_planes = 2;
  1586. for (i = 0; i < num_planes; i++) {
  1587. av_assert0(frame->data[i]);
  1588. }
  1589. // For formats without data like hwaccel allow unused pointers to be non-NULL.
  1590. for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
  1591. if (frame->data[i])
  1592. av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
  1593. frame->data[i] = NULL;
  1594. }
  1595. }
  1596. }
  1597. static void decode_data_free(void *opaque, uint8_t *data)
  1598. {
  1599. FrameDecodeData *fdd = (FrameDecodeData*)data;
  1600. if (fdd->post_process_opaque_free)
  1601. fdd->post_process_opaque_free(fdd->post_process_opaque);
  1602. if (fdd->hwaccel_priv_free)
  1603. fdd->hwaccel_priv_free(fdd->hwaccel_priv);
  1604. av_freep(&fdd);
  1605. }
  1606. int ff_attach_decode_data(AVFrame *frame)
  1607. {
  1608. AVBufferRef *fdd_buf;
  1609. FrameDecodeData *fdd;
  1610. av_assert1(!frame->private_ref);
  1611. av_buffer_unref(&frame->private_ref);
  1612. fdd = av_mallocz(sizeof(*fdd));
  1613. if (!fdd)
  1614. return AVERROR(ENOMEM);
  1615. fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
  1616. NULL, AV_BUFFER_FLAG_READONLY);
  1617. if (!fdd_buf) {
  1618. av_freep(&fdd);
  1619. return AVERROR(ENOMEM);
  1620. }
  1621. frame->private_ref = fdd_buf;
  1622. return 0;
  1623. }
  1624. int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
  1625. {
  1626. const AVHWAccel *hwaccel = avctx->hwaccel;
  1627. int override_dimensions = 1;
  1628. int ret;
  1629. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  1630. if ((unsigned)avctx->width > INT_MAX - STRIDE_ALIGN ||
  1631. (ret = av_image_check_size2(FFALIGN(avctx->width, STRIDE_ALIGN), avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
  1632. av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
  1633. ret = AVERROR(EINVAL);
  1634. goto fail;
  1635. }
  1636. if (frame->width <= 0 || frame->height <= 0) {
  1637. frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
  1638. frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
  1639. override_dimensions = 0;
  1640. }
  1641. if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
  1642. av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
  1643. ret = AVERROR(EINVAL);
  1644. goto fail;
  1645. }
  1646. } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  1647. if (frame->nb_samples * (int64_t)avctx->channels > avctx->max_samples) {
  1648. av_log(avctx, AV_LOG_ERROR, "samples per frame %d, exceeds max_samples %"PRId64"\n", frame->nb_samples, avctx->max_samples);
  1649. ret = AVERROR(EINVAL);
  1650. goto fail;
  1651. }
  1652. }
  1653. ret = ff_decode_frame_props(avctx, frame);
  1654. if (ret < 0)
  1655. goto fail;
  1656. if (hwaccel) {
  1657. if (hwaccel->alloc_frame) {
  1658. ret = hwaccel->alloc_frame(avctx, frame);
  1659. goto end;
  1660. }
  1661. } else
  1662. avctx->sw_pix_fmt = avctx->pix_fmt;
  1663. ret = avctx->get_buffer2(avctx, frame, flags);
  1664. if (ret < 0)
  1665. goto fail;
  1666. validate_avframe_allocation(avctx, frame);
  1667. ret = ff_attach_decode_data(frame);
  1668. if (ret < 0)
  1669. goto fail;
  1670. end:
  1671. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
  1672. !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
  1673. frame->width = avctx->width;
  1674. frame->height = avctx->height;
  1675. }
  1676. fail:
  1677. if (ret < 0) {
  1678. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  1679. av_frame_unref(frame);
  1680. }
  1681. return ret;
  1682. }
  1683. static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
  1684. {
  1685. AVFrame *tmp;
  1686. int ret;
  1687. av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
  1688. if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
  1689. av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
  1690. frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
  1691. av_frame_unref(frame);
  1692. }
  1693. if (!frame->data[0])
  1694. return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
  1695. if ((flags & FF_REGET_BUFFER_FLAG_READONLY) || av_frame_is_writable(frame))
  1696. return ff_decode_frame_props(avctx, frame);
  1697. tmp = av_frame_alloc();
  1698. if (!tmp)
  1699. return AVERROR(ENOMEM);
  1700. av_frame_move_ref(tmp, frame);
  1701. ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
  1702. if (ret < 0) {
  1703. av_frame_free(&tmp);
  1704. return ret;
  1705. }
  1706. av_frame_copy(frame, tmp);
  1707. av_frame_free(&tmp);
  1708. return 0;
  1709. }
  1710. int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
  1711. {
  1712. int ret = reget_buffer_internal(avctx, frame, flags);
  1713. if (ret < 0)
  1714. av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
  1715. return ret;
  1716. }