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.

1998 lines
66KB

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