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.

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