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.

2016 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, 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, 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,
  747. AVPacket *outpkt, const AVPacket *inpkt)
  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. AVPacket tmp;
  755. #endif
  756. if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
  757. return 0;
  758. #if CONFIG_ICONV
  759. cd = iconv_open("UTF-8", avctx->sub_charenc);
  760. av_assert0(cd != (iconv_t)-1);
  761. inb = inpkt->data;
  762. inl = inpkt->size;
  763. if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
  764. av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
  765. ret = AVERROR(ENOMEM);
  766. goto end;
  767. }
  768. ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
  769. if (ret < 0)
  770. goto end;
  771. outpkt->buf = tmp.buf;
  772. outpkt->data = tmp.data;
  773. outpkt->size = tmp.size;
  774. outb = outpkt->data;
  775. outl = outpkt->size;
  776. if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
  777. iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
  778. outl >= outpkt->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. av_packet_unref(&tmp);
  783. goto end;
  784. }
  785. outpkt->size -= outl;
  786. memset(outpkt->data + outpkt->size, 0, outl);
  787. end:
  788. if (cd != (iconv_t)-1)
  789. iconv_close(cd);
  790. return ret;
  791. #else
  792. av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
  793. return AVERROR(EINVAL);
  794. #endif
  795. }
  796. static int utf8_check(const uint8_t *str)
  797. {
  798. const uint8_t *byte;
  799. uint32_t codepoint, min;
  800. while (*str) {
  801. byte = str;
  802. GET_UTF8(codepoint, *(byte++), return 0;);
  803. min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
  804. 1 << (5 * (byte - str) - 4);
  805. if (codepoint < min || codepoint >= 0x110000 ||
  806. codepoint == 0xFFFE /* BOM */ ||
  807. codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
  808. return 0;
  809. str = byte;
  810. }
  811. return 1;
  812. }
  813. #if FF_API_ASS_TIMING
  814. static void insert_ts(AVBPrint *buf, int ts)
  815. {
  816. if (ts == -1) {
  817. av_bprintf(buf, "9:59:59.99,");
  818. } else {
  819. int h, m, s;
  820. h = ts/360000; ts -= 360000*h;
  821. m = ts/ 6000; ts -= 6000*m;
  822. s = ts/ 100; ts -= 100*s;
  823. av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
  824. }
  825. }
  826. static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
  827. {
  828. int i;
  829. AVBPrint buf;
  830. av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
  831. for (i = 0; i < sub->num_rects; i++) {
  832. char *final_dialog;
  833. const char *dialog;
  834. AVSubtitleRect *rect = sub->rects[i];
  835. int ts_start, ts_duration = -1;
  836. long int layer;
  837. if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
  838. continue;
  839. av_bprint_clear(&buf);
  840. /* skip ReadOrder */
  841. dialog = strchr(rect->ass, ',');
  842. if (!dialog)
  843. continue;
  844. dialog++;
  845. /* extract Layer or Marked */
  846. layer = strtol(dialog, (char**)&dialog, 10);
  847. if (*dialog != ',')
  848. continue;
  849. dialog++;
  850. /* rescale timing to ASS time base (ms) */
  851. ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
  852. if (pkt->duration != -1)
  853. ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
  854. sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
  855. /* construct ASS (standalone file form with timestamps) string */
  856. av_bprintf(&buf, "Dialogue: %ld,", layer);
  857. insert_ts(&buf, ts_start);
  858. insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
  859. av_bprintf(&buf, "%s\r\n", dialog);
  860. final_dialog = av_strdup(buf.str);
  861. if (!av_bprint_is_complete(&buf) || !final_dialog) {
  862. av_freep(&final_dialog);
  863. av_bprint_finalize(&buf, NULL);
  864. return AVERROR(ENOMEM);
  865. }
  866. av_freep(&rect->ass);
  867. rect->ass = final_dialog;
  868. }
  869. av_bprint_finalize(&buf, NULL);
  870. return 0;
  871. }
  872. #endif
  873. int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
  874. int *got_sub_ptr,
  875. AVPacket *avpkt)
  876. {
  877. int i, ret = 0;
  878. if (!avpkt->data && avpkt->size) {
  879. av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
  880. return AVERROR(EINVAL);
  881. }
  882. if (!avctx->codec)
  883. return AVERROR(EINVAL);
  884. if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
  885. av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
  886. return AVERROR(EINVAL);
  887. }
  888. *got_sub_ptr = 0;
  889. get_subtitle_defaults(sub);
  890. if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
  891. AVPacket pkt_recoded = *avpkt;
  892. ret = recode_subtitle(avctx, &pkt_recoded, avpkt);
  893. if (ret < 0) {
  894. *got_sub_ptr = 0;
  895. } else {
  896. ret = extract_packet_props(avctx->internal, &pkt_recoded);
  897. if (ret < 0)
  898. return ret;
  899. if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
  900. sub->pts = av_rescale_q(avpkt->pts,
  901. avctx->pkt_timebase, AV_TIME_BASE_Q);
  902. ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
  903. av_assert1((ret >= 0) >= !!*got_sub_ptr &&
  904. !!*got_sub_ptr >= !!sub->num_rects);
  905. #if FF_API_ASS_TIMING
  906. if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
  907. && *got_sub_ptr && sub->num_rects) {
  908. const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
  909. : avctx->time_base;
  910. int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
  911. if (err < 0)
  912. ret = err;
  913. }
  914. #endif
  915. if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
  916. avctx->pkt_timebase.num) {
  917. AVRational ms = { 1, 1000 };
  918. sub->end_display_time = av_rescale_q(avpkt->duration,
  919. avctx->pkt_timebase, ms);
  920. }
  921. if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
  922. sub->format = 0;
  923. else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
  924. sub->format = 1;
  925. for (i = 0; i < sub->num_rects; i++) {
  926. if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_IGNORE &&
  927. sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
  928. av_log(avctx, AV_LOG_ERROR,
  929. "Invalid UTF-8 in decoded subtitles text; "
  930. "maybe missing -sub_charenc option\n");
  931. avsubtitle_free(sub);
  932. ret = AVERROR_INVALIDDATA;
  933. break;
  934. }
  935. }
  936. if (avpkt->data != pkt_recoded.data) { // did we recode?
  937. /* prevent from destroying side data from original packet */
  938. pkt_recoded.side_data = NULL;
  939. pkt_recoded.side_data_elems = 0;
  940. av_packet_unref(&pkt_recoded);
  941. }
  942. }
  943. if (*got_sub_ptr)
  944. avctx->frame_number++;
  945. }
  946. return ret;
  947. }
  948. enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
  949. const enum AVPixelFormat *fmt)
  950. {
  951. const AVPixFmtDescriptor *desc;
  952. const AVCodecHWConfig *config;
  953. int i, n;
  954. // If a device was supplied when the codec was opened, assume that the
  955. // user wants to use it.
  956. if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
  957. AVHWDeviceContext *device_ctx =
  958. (AVHWDeviceContext*)avctx->hw_device_ctx->data;
  959. for (i = 0;; i++) {
  960. config = &avctx->codec->hw_configs[i]->public;
  961. if (!config)
  962. break;
  963. if (!(config->methods &
  964. AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
  965. continue;
  966. if (device_ctx->type != config->device_type)
  967. continue;
  968. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
  969. if (config->pix_fmt == fmt[n])
  970. return fmt[n];
  971. }
  972. }
  973. }
  974. // No device or other setup, so we have to choose from things which
  975. // don't any other external information.
  976. // If the last element of the list is a software format, choose it
  977. // (this should be best software format if any exist).
  978. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
  979. desc = av_pix_fmt_desc_get(fmt[n - 1]);
  980. if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
  981. return fmt[n - 1];
  982. // Finally, traverse the list in order and choose the first entry
  983. // with no external dependencies (if there is no hardware configuration
  984. // information available then this just picks the first entry).
  985. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
  986. for (i = 0;; i++) {
  987. config = avcodec_get_hw_config(avctx->codec, i);
  988. if (!config)
  989. break;
  990. if (config->pix_fmt == fmt[n])
  991. break;
  992. }
  993. if (!config) {
  994. // No specific config available, so the decoder must be able
  995. // to handle this format without any additional setup.
  996. return fmt[n];
  997. }
  998. if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
  999. // Usable with only internal setup.
  1000. return fmt[n];
  1001. }
  1002. }
  1003. // Nothing is usable, give up.
  1004. return AV_PIX_FMT_NONE;
  1005. }
  1006. int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
  1007. enum AVHWDeviceType dev_type)
  1008. {
  1009. AVHWDeviceContext *device_ctx;
  1010. AVHWFramesContext *frames_ctx;
  1011. int ret;
  1012. if (!avctx->hwaccel)
  1013. return AVERROR(ENOSYS);
  1014. if (avctx->hw_frames_ctx)
  1015. return 0;
  1016. if (!avctx->hw_device_ctx) {
  1017. av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
  1018. "required for hardware accelerated decoding.\n");
  1019. return AVERROR(EINVAL);
  1020. }
  1021. device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
  1022. if (device_ctx->type != dev_type) {
  1023. av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
  1024. "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
  1025. av_hwdevice_get_type_name(device_ctx->type));
  1026. return AVERROR(EINVAL);
  1027. }
  1028. ret = avcodec_get_hw_frames_parameters(avctx,
  1029. avctx->hw_device_ctx,
  1030. avctx->hwaccel->pix_fmt,
  1031. &avctx->hw_frames_ctx);
  1032. if (ret < 0)
  1033. return ret;
  1034. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  1035. if (frames_ctx->initial_pool_size) {
  1036. // We guarantee 4 base work surfaces. The function above guarantees 1
  1037. // (the absolute minimum), so add the missing count.
  1038. frames_ctx->initial_pool_size += 3;
  1039. }
  1040. ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
  1041. if (ret < 0) {
  1042. av_buffer_unref(&avctx->hw_frames_ctx);
  1043. return ret;
  1044. }
  1045. return 0;
  1046. }
  1047. int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
  1048. AVBufferRef *device_ref,
  1049. enum AVPixelFormat hw_pix_fmt,
  1050. AVBufferRef **out_frames_ref)
  1051. {
  1052. AVBufferRef *frames_ref = NULL;
  1053. const AVCodecHWConfigInternal *hw_config;
  1054. const AVHWAccel *hwa;
  1055. int i, ret;
  1056. for (i = 0;; i++) {
  1057. hw_config = avctx->codec->hw_configs[i];
  1058. if (!hw_config)
  1059. return AVERROR(ENOENT);
  1060. if (hw_config->public.pix_fmt == hw_pix_fmt)
  1061. break;
  1062. }
  1063. hwa = hw_config->hwaccel;
  1064. if (!hwa || !hwa->frame_params)
  1065. return AVERROR(ENOENT);
  1066. frames_ref = av_hwframe_ctx_alloc(device_ref);
  1067. if (!frames_ref)
  1068. return AVERROR(ENOMEM);
  1069. ret = hwa->frame_params(avctx, frames_ref);
  1070. if (ret >= 0) {
  1071. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
  1072. if (frames_ctx->initial_pool_size) {
  1073. // If the user has requested that extra output surfaces be
  1074. // available then add them here.
  1075. if (avctx->extra_hw_frames > 0)
  1076. frames_ctx->initial_pool_size += avctx->extra_hw_frames;
  1077. // If frame threading is enabled then an extra surface per thread
  1078. // is also required.
  1079. if (avctx->active_thread_type & FF_THREAD_FRAME)
  1080. frames_ctx->initial_pool_size += avctx->thread_count;
  1081. }
  1082. *out_frames_ref = frames_ref;
  1083. } else {
  1084. av_buffer_unref(&frames_ref);
  1085. }
  1086. return ret;
  1087. }
  1088. static int hwaccel_init(AVCodecContext *avctx,
  1089. const AVCodecHWConfigInternal *hw_config)
  1090. {
  1091. const AVHWAccel *hwaccel;
  1092. int err;
  1093. hwaccel = hw_config->hwaccel;
  1094. if (hwaccel->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
  1095. avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  1096. av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
  1097. hwaccel->name);
  1098. return AVERROR_PATCHWELCOME;
  1099. }
  1100. if (hwaccel->priv_data_size) {
  1101. avctx->internal->hwaccel_priv_data =
  1102. av_mallocz(hwaccel->priv_data_size);
  1103. if (!avctx->internal->hwaccel_priv_data)
  1104. return AVERROR(ENOMEM);
  1105. }
  1106. avctx->hwaccel = hwaccel;
  1107. if (hwaccel->init) {
  1108. err = hwaccel->init(avctx);
  1109. if (err < 0) {
  1110. av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
  1111. "hwaccel initialisation returned error.\n",
  1112. av_get_pix_fmt_name(hw_config->public.pix_fmt));
  1113. av_freep(&avctx->internal->hwaccel_priv_data);
  1114. avctx->hwaccel = NULL;
  1115. return err;
  1116. }
  1117. }
  1118. return 0;
  1119. }
  1120. static void hwaccel_uninit(AVCodecContext *avctx)
  1121. {
  1122. if (avctx->hwaccel && avctx->hwaccel->uninit)
  1123. avctx->hwaccel->uninit(avctx);
  1124. av_freep(&avctx->internal->hwaccel_priv_data);
  1125. avctx->hwaccel = NULL;
  1126. av_buffer_unref(&avctx->hw_frames_ctx);
  1127. }
  1128. int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
  1129. {
  1130. const AVPixFmtDescriptor *desc;
  1131. enum AVPixelFormat *choices;
  1132. enum AVPixelFormat ret, user_choice;
  1133. const AVCodecHWConfigInternal *hw_config;
  1134. const AVCodecHWConfig *config;
  1135. int i, n, err;
  1136. // Find end of list.
  1137. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
  1138. // Must contain at least one entry.
  1139. av_assert0(n >= 1);
  1140. // If a software format is available, it must be the last entry.
  1141. desc = av_pix_fmt_desc_get(fmt[n - 1]);
  1142. if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
  1143. // No software format is available.
  1144. } else {
  1145. avctx->sw_pix_fmt = fmt[n - 1];
  1146. }
  1147. choices = av_malloc_array(n + 1, sizeof(*choices));
  1148. if (!choices)
  1149. return AV_PIX_FMT_NONE;
  1150. memcpy(choices, fmt, (n + 1) * sizeof(*choices));
  1151. for (;;) {
  1152. // Remove the previous hwaccel, if there was one.
  1153. hwaccel_uninit(avctx);
  1154. user_choice = avctx->get_format(avctx, choices);
  1155. if (user_choice == AV_PIX_FMT_NONE) {
  1156. // Explicitly chose nothing, give up.
  1157. ret = AV_PIX_FMT_NONE;
  1158. break;
  1159. }
  1160. desc = av_pix_fmt_desc_get(user_choice);
  1161. if (!desc) {
  1162. av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
  1163. "get_format() callback.\n");
  1164. ret = AV_PIX_FMT_NONE;
  1165. break;
  1166. }
  1167. av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
  1168. desc->name);
  1169. for (i = 0; i < n; i++) {
  1170. if (choices[i] == user_choice)
  1171. break;
  1172. }
  1173. if (i == n) {
  1174. av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
  1175. "%s not in possible list.\n", desc->name);
  1176. ret = AV_PIX_FMT_NONE;
  1177. break;
  1178. }
  1179. if (avctx->codec->hw_configs) {
  1180. for (i = 0;; i++) {
  1181. hw_config = avctx->codec->hw_configs[i];
  1182. if (!hw_config)
  1183. break;
  1184. if (hw_config->public.pix_fmt == user_choice)
  1185. break;
  1186. }
  1187. } else {
  1188. hw_config = NULL;
  1189. }
  1190. if (!hw_config) {
  1191. // No config available, so no extra setup required.
  1192. ret = user_choice;
  1193. break;
  1194. }
  1195. config = &hw_config->public;
  1196. if (config->methods &
  1197. AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
  1198. avctx->hw_frames_ctx) {
  1199. const AVHWFramesContext *frames_ctx =
  1200. (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  1201. if (frames_ctx->format != user_choice) {
  1202. av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
  1203. "does not match the format of the provided frames "
  1204. "context.\n", desc->name);
  1205. goto try_again;
  1206. }
  1207. } else if (config->methods &
  1208. AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
  1209. avctx->hw_device_ctx) {
  1210. const AVHWDeviceContext *device_ctx =
  1211. (AVHWDeviceContext*)avctx->hw_device_ctx->data;
  1212. if (device_ctx->type != config->device_type) {
  1213. av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
  1214. "does not match the type of the provided device "
  1215. "context.\n", desc->name);
  1216. goto try_again;
  1217. }
  1218. } else if (config->methods &
  1219. AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
  1220. // Internal-only setup, no additional configuration.
  1221. } else if (config->methods &
  1222. AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
  1223. // Some ad-hoc configuration we can't see and can't check.
  1224. } else {
  1225. av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
  1226. "missing configuration.\n", desc->name);
  1227. goto try_again;
  1228. }
  1229. if (hw_config->hwaccel) {
  1230. av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
  1231. "initialisation.\n", desc->name);
  1232. err = hwaccel_init(avctx, hw_config);
  1233. if (err < 0)
  1234. goto try_again;
  1235. }
  1236. ret = user_choice;
  1237. break;
  1238. try_again:
  1239. av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
  1240. "get_format() without it.\n", desc->name);
  1241. for (i = 0; i < n; i++) {
  1242. if (choices[i] == user_choice)
  1243. break;
  1244. }
  1245. for (; i + 1 < n; i++)
  1246. choices[i] = choices[i + 1];
  1247. --n;
  1248. }
  1249. av_freep(&choices);
  1250. return ret;
  1251. }
  1252. static void frame_pool_free(void *opaque, uint8_t *data)
  1253. {
  1254. FramePool *pool = (FramePool*)data;
  1255. int i;
  1256. for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
  1257. av_buffer_pool_uninit(&pool->pools[i]);
  1258. av_freep(&data);
  1259. }
  1260. static AVBufferRef *frame_pool_alloc(void)
  1261. {
  1262. FramePool *pool = av_mallocz(sizeof(*pool));
  1263. AVBufferRef *buf;
  1264. if (!pool)
  1265. return NULL;
  1266. buf = av_buffer_create((uint8_t*)pool, sizeof(*pool),
  1267. frame_pool_free, NULL, 0);
  1268. if (!buf) {
  1269. av_freep(&pool);
  1270. return NULL;
  1271. }
  1272. return buf;
  1273. }
  1274. static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
  1275. {
  1276. FramePool *pool = avctx->internal->pool ?
  1277. (FramePool*)avctx->internal->pool->data : NULL;
  1278. AVBufferRef *pool_buf;
  1279. int i, ret, ch, planes;
  1280. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  1281. int planar = av_sample_fmt_is_planar(frame->format);
  1282. ch = frame->channels;
  1283. planes = planar ? ch : 1;
  1284. }
  1285. if (pool && pool->format == frame->format) {
  1286. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
  1287. pool->width == frame->width && pool->height == frame->height)
  1288. return 0;
  1289. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pool->planes == planes &&
  1290. pool->channels == ch && frame->nb_samples == pool->samples)
  1291. return 0;
  1292. }
  1293. pool_buf = frame_pool_alloc();
  1294. if (!pool_buf)
  1295. return AVERROR(ENOMEM);
  1296. pool = (FramePool*)pool_buf->data;
  1297. switch (avctx->codec_type) {
  1298. case AVMEDIA_TYPE_VIDEO: {
  1299. int linesize[4];
  1300. int w = frame->width;
  1301. int h = frame->height;
  1302. int unaligned;
  1303. ptrdiff_t linesize1[4];
  1304. size_t size[4];
  1305. avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
  1306. do {
  1307. // NOTE: do not align linesizes individually, this breaks e.g. assumptions
  1308. // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
  1309. ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
  1310. if (ret < 0)
  1311. goto fail;
  1312. // increase alignment of w for next try (rhs gives the lowest bit set in w)
  1313. w += w & ~(w - 1);
  1314. unaligned = 0;
  1315. for (i = 0; i < 4; i++)
  1316. unaligned |= linesize[i] % pool->stride_align[i];
  1317. } while (unaligned);
  1318. for (i = 0; i < 4; i++)
  1319. linesize1[i] = linesize[i];
  1320. ret = av_image_fill_plane_sizes(size, avctx->pix_fmt, h, linesize1);
  1321. if (ret < 0)
  1322. goto fail;
  1323. for (i = 0; i < 4; i++) {
  1324. pool->linesize[i] = linesize[i];
  1325. if (size[i]) {
  1326. if (size[i] > INT_MAX - (16 + STRIDE_ALIGN - 1)) {
  1327. ret = AVERROR(EINVAL);
  1328. goto fail;
  1329. }
  1330. pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
  1331. CONFIG_MEMORY_POISONING ?
  1332. NULL :
  1333. av_buffer_allocz);
  1334. if (!pool->pools[i]) {
  1335. ret = AVERROR(ENOMEM);
  1336. goto fail;
  1337. }
  1338. }
  1339. }
  1340. pool->format = frame->format;
  1341. pool->width = frame->width;
  1342. pool->height = frame->height;
  1343. break;
  1344. }
  1345. case AVMEDIA_TYPE_AUDIO: {
  1346. ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
  1347. frame->nb_samples, frame->format, 0);
  1348. if (ret < 0)
  1349. goto fail;
  1350. pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
  1351. if (!pool->pools[0]) {
  1352. ret = AVERROR(ENOMEM);
  1353. goto fail;
  1354. }
  1355. pool->format = frame->format;
  1356. pool->planes = planes;
  1357. pool->channels = ch;
  1358. pool->samples = frame->nb_samples;
  1359. break;
  1360. }
  1361. default: av_assert0(0);
  1362. }
  1363. av_buffer_unref(&avctx->internal->pool);
  1364. avctx->internal->pool = pool_buf;
  1365. return 0;
  1366. fail:
  1367. av_buffer_unref(&pool_buf);
  1368. return ret;
  1369. }
  1370. static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
  1371. {
  1372. FramePool *pool = (FramePool*)avctx->internal->pool->data;
  1373. int planes = pool->planes;
  1374. int i;
  1375. frame->linesize[0] = pool->linesize[0];
  1376. if (planes > AV_NUM_DATA_POINTERS) {
  1377. frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
  1378. frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
  1379. frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
  1380. sizeof(*frame->extended_buf));
  1381. if (!frame->extended_data || !frame->extended_buf) {
  1382. av_freep(&frame->extended_data);
  1383. av_freep(&frame->extended_buf);
  1384. return AVERROR(ENOMEM);
  1385. }
  1386. } else {
  1387. frame->extended_data = frame->data;
  1388. av_assert0(frame->nb_extended_buf == 0);
  1389. }
  1390. for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
  1391. frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
  1392. if (!frame->buf[i])
  1393. goto fail;
  1394. frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
  1395. }
  1396. for (i = 0; i < frame->nb_extended_buf; i++) {
  1397. frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
  1398. if (!frame->extended_buf[i])
  1399. goto fail;
  1400. frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
  1401. }
  1402. if (avctx->debug & FF_DEBUG_BUFFERS)
  1403. av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
  1404. return 0;
  1405. fail:
  1406. av_frame_unref(frame);
  1407. return AVERROR(ENOMEM);
  1408. }
  1409. static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
  1410. {
  1411. FramePool *pool = (FramePool*)s->internal->pool->data;
  1412. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
  1413. int i;
  1414. if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
  1415. av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
  1416. return -1;
  1417. }
  1418. if (!desc) {
  1419. av_log(s, AV_LOG_ERROR,
  1420. "Unable to get pixel format descriptor for format %s\n",
  1421. av_get_pix_fmt_name(pic->format));
  1422. return AVERROR(EINVAL);
  1423. }
  1424. memset(pic->data, 0, sizeof(pic->data));
  1425. pic->extended_data = pic->data;
  1426. for (i = 0; i < 4 && pool->pools[i]; i++) {
  1427. pic->linesize[i] = pool->linesize[i];
  1428. pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
  1429. if (!pic->buf[i])
  1430. goto fail;
  1431. pic->data[i] = pic->buf[i]->data;
  1432. }
  1433. for (; i < AV_NUM_DATA_POINTERS; i++) {
  1434. pic->data[i] = NULL;
  1435. pic->linesize[i] = 0;
  1436. }
  1437. if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
  1438. ((desc->flags & FF_PSEUDOPAL) && pic->data[1]))
  1439. avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
  1440. if (s->debug & FF_DEBUG_BUFFERS)
  1441. av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
  1442. return 0;
  1443. fail:
  1444. av_frame_unref(pic);
  1445. return AVERROR(ENOMEM);
  1446. }
  1447. int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
  1448. {
  1449. int ret;
  1450. if (avctx->hw_frames_ctx) {
  1451. ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
  1452. frame->width = avctx->coded_width;
  1453. frame->height = avctx->coded_height;
  1454. return ret;
  1455. }
  1456. if ((ret = update_frame_pool(avctx, frame)) < 0)
  1457. return ret;
  1458. switch (avctx->codec_type) {
  1459. case AVMEDIA_TYPE_VIDEO:
  1460. return video_get_buffer(avctx, frame);
  1461. case AVMEDIA_TYPE_AUDIO:
  1462. return audio_get_buffer(avctx, frame);
  1463. default:
  1464. return -1;
  1465. }
  1466. }
  1467. static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
  1468. {
  1469. int size;
  1470. const uint8_t *side_metadata;
  1471. AVDictionary **frame_md = &frame->metadata;
  1472. side_metadata = av_packet_get_side_data(avpkt,
  1473. AV_PKT_DATA_STRINGS_METADATA, &size);
  1474. return av_packet_unpack_dictionary(side_metadata, size, frame_md);
  1475. }
  1476. int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
  1477. {
  1478. AVPacket *pkt = avctx->internal->last_pkt_props;
  1479. int i;
  1480. static const struct {
  1481. enum AVPacketSideDataType packet;
  1482. enum AVFrameSideDataType frame;
  1483. } sd[] = {
  1484. { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
  1485. { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
  1486. { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
  1487. { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
  1488. { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
  1489. { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
  1490. { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
  1491. { AV_PKT_DATA_A53_CC, AV_FRAME_DATA_A53_CC },
  1492. { AV_PKT_DATA_ICC_PROFILE, AV_FRAME_DATA_ICC_PROFILE },
  1493. { AV_PKT_DATA_S12M_TIMECODE, AV_FRAME_DATA_S12M_TIMECODE },
  1494. };
  1495. if (IS_EMPTY(pkt) && av_fifo_size(avctx->internal->pkt_props) >= sizeof(*pkt))
  1496. av_fifo_generic_read(avctx->internal->pkt_props,
  1497. pkt, sizeof(*pkt), NULL);
  1498. if (pkt) {
  1499. frame->pts = pkt->pts;
  1500. #if FF_API_PKT_PTS
  1501. FF_DISABLE_DEPRECATION_WARNINGS
  1502. frame->pkt_pts = pkt->pts;
  1503. FF_ENABLE_DEPRECATION_WARNINGS
  1504. #endif
  1505. frame->pkt_pos = pkt->pos;
  1506. frame->pkt_duration = pkt->duration;
  1507. frame->pkt_size = pkt->size;
  1508. for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
  1509. int size;
  1510. uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
  1511. if (packet_sd) {
  1512. AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
  1513. sd[i].frame,
  1514. size);
  1515. if (!frame_sd)
  1516. return AVERROR(ENOMEM);
  1517. memcpy(frame_sd->data, packet_sd, size);
  1518. }
  1519. }
  1520. add_metadata_from_side_data(pkt, frame);
  1521. if (pkt->flags & AV_PKT_FLAG_DISCARD) {
  1522. frame->flags |= AV_FRAME_FLAG_DISCARD;
  1523. } else {
  1524. frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
  1525. }
  1526. }
  1527. frame->reordered_opaque = avctx->reordered_opaque;
  1528. if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
  1529. frame->color_primaries = avctx->color_primaries;
  1530. if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
  1531. frame->color_trc = avctx->color_trc;
  1532. if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
  1533. frame->colorspace = avctx->colorspace;
  1534. if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
  1535. frame->color_range = avctx->color_range;
  1536. if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
  1537. frame->chroma_location = avctx->chroma_sample_location;
  1538. switch (avctx->codec->type) {
  1539. case AVMEDIA_TYPE_VIDEO:
  1540. frame->format = avctx->pix_fmt;
  1541. if (!frame->sample_aspect_ratio.num)
  1542. frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
  1543. if (frame->width && frame->height &&
  1544. av_image_check_sar(frame->width, frame->height,
  1545. frame->sample_aspect_ratio) < 0) {
  1546. av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
  1547. frame->sample_aspect_ratio.num,
  1548. frame->sample_aspect_ratio.den);
  1549. frame->sample_aspect_ratio = (AVRational){ 0, 1 };
  1550. }
  1551. break;
  1552. case AVMEDIA_TYPE_AUDIO:
  1553. if (!frame->sample_rate)
  1554. frame->sample_rate = avctx->sample_rate;
  1555. if (frame->format < 0)
  1556. frame->format = avctx->sample_fmt;
  1557. if (!frame->channel_layout) {
  1558. if (avctx->channel_layout) {
  1559. if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
  1560. avctx->channels) {
  1561. av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
  1562. "configuration.\n");
  1563. return AVERROR(EINVAL);
  1564. }
  1565. frame->channel_layout = avctx->channel_layout;
  1566. } else {
  1567. if (avctx->channels > FF_SANE_NB_CHANNELS) {
  1568. av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
  1569. avctx->channels);
  1570. return AVERROR(ENOSYS);
  1571. }
  1572. }
  1573. }
  1574. frame->channels = avctx->channels;
  1575. break;
  1576. }
  1577. return 0;
  1578. }
  1579. static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
  1580. {
  1581. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  1582. int i;
  1583. int num_planes = av_pix_fmt_count_planes(frame->format);
  1584. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
  1585. int flags = desc ? desc->flags : 0;
  1586. if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
  1587. num_planes = 2;
  1588. if ((flags & FF_PSEUDOPAL) && frame->data[1])
  1589. num_planes = 2;
  1590. for (i = 0; i < num_planes; i++) {
  1591. av_assert0(frame->data[i]);
  1592. }
  1593. // For formats without data like hwaccel allow unused pointers to be non-NULL.
  1594. for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
  1595. if (frame->data[i])
  1596. av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
  1597. frame->data[i] = NULL;
  1598. }
  1599. }
  1600. }
  1601. static void decode_data_free(void *opaque, uint8_t *data)
  1602. {
  1603. FrameDecodeData *fdd = (FrameDecodeData*)data;
  1604. if (fdd->post_process_opaque_free)
  1605. fdd->post_process_opaque_free(fdd->post_process_opaque);
  1606. if (fdd->hwaccel_priv_free)
  1607. fdd->hwaccel_priv_free(fdd->hwaccel_priv);
  1608. av_freep(&fdd);
  1609. }
  1610. int ff_attach_decode_data(AVFrame *frame)
  1611. {
  1612. AVBufferRef *fdd_buf;
  1613. FrameDecodeData *fdd;
  1614. av_assert1(!frame->private_ref);
  1615. av_buffer_unref(&frame->private_ref);
  1616. fdd = av_mallocz(sizeof(*fdd));
  1617. if (!fdd)
  1618. return AVERROR(ENOMEM);
  1619. fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
  1620. NULL, AV_BUFFER_FLAG_READONLY);
  1621. if (!fdd_buf) {
  1622. av_freep(&fdd);
  1623. return AVERROR(ENOMEM);
  1624. }
  1625. frame->private_ref = fdd_buf;
  1626. return 0;
  1627. }
  1628. int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
  1629. {
  1630. const AVHWAccel *hwaccel = avctx->hwaccel;
  1631. int override_dimensions = 1;
  1632. int ret;
  1633. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  1634. if ((unsigned)avctx->width > INT_MAX - STRIDE_ALIGN ||
  1635. (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) {
  1636. av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
  1637. ret = AVERROR(EINVAL);
  1638. goto fail;
  1639. }
  1640. if (frame->width <= 0 || frame->height <= 0) {
  1641. frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
  1642. frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
  1643. override_dimensions = 0;
  1644. }
  1645. if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
  1646. av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
  1647. ret = AVERROR(EINVAL);
  1648. goto fail;
  1649. }
  1650. } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  1651. if (frame->nb_samples * (int64_t)avctx->channels > avctx->max_samples) {
  1652. av_log(avctx, AV_LOG_ERROR, "samples per frame %d, exceeds max_samples %"PRId64"\n", frame->nb_samples, avctx->max_samples);
  1653. ret = AVERROR(EINVAL);
  1654. goto fail;
  1655. }
  1656. }
  1657. ret = ff_decode_frame_props(avctx, frame);
  1658. if (ret < 0)
  1659. goto fail;
  1660. if (hwaccel) {
  1661. if (hwaccel->alloc_frame) {
  1662. ret = hwaccel->alloc_frame(avctx, frame);
  1663. goto end;
  1664. }
  1665. } else
  1666. avctx->sw_pix_fmt = avctx->pix_fmt;
  1667. ret = avctx->get_buffer2(avctx, frame, flags);
  1668. if (ret < 0)
  1669. goto fail;
  1670. validate_avframe_allocation(avctx, frame);
  1671. ret = ff_attach_decode_data(frame);
  1672. if (ret < 0)
  1673. goto fail;
  1674. end:
  1675. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
  1676. !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
  1677. frame->width = avctx->width;
  1678. frame->height = avctx->height;
  1679. }
  1680. fail:
  1681. if (ret < 0) {
  1682. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  1683. av_frame_unref(frame);
  1684. }
  1685. return ret;
  1686. }
  1687. static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
  1688. {
  1689. AVFrame *tmp;
  1690. int ret;
  1691. av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
  1692. if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
  1693. av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
  1694. frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
  1695. av_frame_unref(frame);
  1696. }
  1697. if (!frame->data[0])
  1698. return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
  1699. if ((flags & FF_REGET_BUFFER_FLAG_READONLY) || av_frame_is_writable(frame))
  1700. return ff_decode_frame_props(avctx, frame);
  1701. tmp = av_frame_alloc();
  1702. if (!tmp)
  1703. return AVERROR(ENOMEM);
  1704. av_frame_move_ref(tmp, frame);
  1705. ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
  1706. if (ret < 0) {
  1707. av_frame_free(&tmp);
  1708. return ret;
  1709. }
  1710. av_frame_copy(frame, tmp);
  1711. av_frame_free(&tmp);
  1712. return 0;
  1713. }
  1714. int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
  1715. {
  1716. int ret = reget_buffer_internal(avctx, frame, flags);
  1717. if (ret < 0)
  1718. av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
  1719. return ret;
  1720. }