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.

2054 lines
67KB

  1. /*
  2. * generic decoding-related code
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include <stdint.h>
  21. #include <string.h>
  22. #include "config.h"
  23. #if CONFIG_ICONV
  24. # include <iconv.h>
  25. #endif
  26. #include "libavutil/avassert.h"
  27. #include "libavutil/avstring.h"
  28. #include "libavutil/bprint.h"
  29. #include "libavutil/common.h"
  30. #include "libavutil/frame.h"
  31. #include "libavutil/hwcontext.h"
  32. #include "libavutil/imgutils.h"
  33. #include "libavutil/internal.h"
  34. #include "libavutil/intmath.h"
  35. #include "libavutil/opt.h"
  36. #include "avcodec.h"
  37. #include "bytestream.h"
  38. #include "decode.h"
  39. #include "hwconfig.h"
  40. #include "internal.h"
  41. #include "thread.h"
  42. typedef struct FramePool {
  43. /**
  44. * Pools for each data plane. For audio all the planes have the same size,
  45. * so only pools[0] is used.
  46. */
  47. AVBufferPool *pools[4];
  48. /*
  49. * Pool parameters
  50. */
  51. int format;
  52. int width, height;
  53. int stride_align[AV_NUM_DATA_POINTERS];
  54. int linesize[4];
  55. int planes;
  56. int channels;
  57. int samples;
  58. } FramePool;
  59. static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
  60. {
  61. int ret;
  62. buffer_size_t size;
  63. const uint8_t *data;
  64. uint32_t flags;
  65. int64_t val;
  66. data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
  67. if (!data)
  68. return 0;
  69. if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
  70. av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
  71. "changes, but PARAM_CHANGE side data was sent to it.\n");
  72. ret = AVERROR(EINVAL);
  73. goto fail2;
  74. }
  75. if (size < 4)
  76. goto fail;
  77. flags = bytestream_get_le32(&data);
  78. size -= 4;
  79. if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
  80. if (size < 4)
  81. goto fail;
  82. val = bytestream_get_le32(&data);
  83. if (val <= 0 || val > INT_MAX) {
  84. av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
  85. ret = AVERROR_INVALIDDATA;
  86. goto fail2;
  87. }
  88. avctx->channels = val;
  89. size -= 4;
  90. }
  91. if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
  92. if (size < 8)
  93. goto fail;
  94. avctx->channel_layout = bytestream_get_le64(&data);
  95. size -= 8;
  96. }
  97. if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
  98. if (size < 4)
  99. goto fail;
  100. val = bytestream_get_le32(&data);
  101. if (val <= 0 || val > INT_MAX) {
  102. av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
  103. ret = AVERROR_INVALIDDATA;
  104. goto fail2;
  105. }
  106. avctx->sample_rate = val;
  107. size -= 4;
  108. }
  109. if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
  110. if (size < 8)
  111. goto fail;
  112. avctx->width = bytestream_get_le32(&data);
  113. avctx->height = bytestream_get_le32(&data);
  114. size -= 8;
  115. ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
  116. if (ret < 0)
  117. goto fail2;
  118. }
  119. return 0;
  120. fail:
  121. av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
  122. ret = AVERROR_INVALIDDATA;
  123. fail2:
  124. if (ret < 0) {
  125. av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
  126. if (avctx->err_recognition & AV_EF_EXPLODE)
  127. return ret;
  128. }
  129. return 0;
  130. }
  131. #define IS_EMPTY(pkt) (!(pkt)->data)
  132. static int copy_packet_props(AVPacket *dst, const AVPacket *src)
  133. {
  134. int ret = av_packet_copy_props(dst, src);
  135. if (ret < 0)
  136. return ret;
  137. dst->size = src->size; // HACK: Needed for ff_decode_frame_props().
  138. dst->data = (void*)1; // HACK: Needed for IS_EMPTY().
  139. return 0;
  140. }
  141. static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
  142. {
  143. AVPacket tmp = { 0 };
  144. int ret = 0;
  145. if (IS_EMPTY(avci->last_pkt_props)) {
  146. if (av_fifo_size(avci->pkt_props) >= sizeof(*pkt)) {
  147. av_fifo_generic_read(avci->pkt_props, avci->last_pkt_props,
  148. sizeof(*avci->last_pkt_props), NULL);
  149. } else
  150. return copy_packet_props(avci->last_pkt_props, pkt);
  151. }
  152. if (av_fifo_space(avci->pkt_props) < sizeof(*pkt)) {
  153. ret = av_fifo_grow(avci->pkt_props, sizeof(*pkt));
  154. if (ret < 0)
  155. return ret;
  156. }
  157. ret = copy_packet_props(&tmp, pkt);
  158. if (ret < 0)
  159. return ret;
  160. av_fifo_generic_write(avci->pkt_props, &tmp, sizeof(tmp), NULL);
  161. return 0;
  162. }
  163. static int decode_bsfs_init(AVCodecContext *avctx)
  164. {
  165. AVCodecInternal *avci = avctx->internal;
  166. int ret;
  167. if (avci->bsf)
  168. return 0;
  169. ret = av_bsf_list_parse_str(avctx->codec->bsfs, &avci->bsf);
  170. if (ret < 0) {
  171. av_log(avctx, AV_LOG_ERROR, "Error parsing decoder bitstream filters '%s': %s\n", avctx->codec->bsfs, av_err2str(ret));
  172. if (ret != AVERROR(ENOMEM))
  173. ret = AVERROR_BUG;
  174. goto fail;
  175. }
  176. /* We do not currently have an API for passing the input timebase into decoders,
  177. * but no filters used here should actually need it.
  178. * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
  179. avci->bsf->time_base_in = (AVRational){ 1, 90000 };
  180. ret = avcodec_parameters_from_context(avci->bsf->par_in, avctx);
  181. if (ret < 0)
  182. goto fail;
  183. ret = av_bsf_init(avci->bsf);
  184. if (ret < 0)
  185. goto fail;
  186. return 0;
  187. fail:
  188. av_bsf_free(&avci->bsf);
  189. return ret;
  190. }
  191. int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
  192. {
  193. AVCodecInternal *avci = avctx->internal;
  194. int ret;
  195. if (avci->draining)
  196. return AVERROR_EOF;
  197. ret = av_bsf_receive_packet(avci->bsf, pkt);
  198. if (ret == AVERROR_EOF)
  199. avci->draining = 1;
  200. if (ret < 0)
  201. return ret;
  202. ret = extract_packet_props(avctx->internal, pkt);
  203. if (ret < 0)
  204. goto finish;
  205. ret = apply_param_change(avctx, pkt);
  206. if (ret < 0)
  207. goto finish;
  208. #if FF_API_OLD_ENCDEC
  209. if (avctx->codec->receive_frame)
  210. avci->compat_decode_consumed += pkt->size;
  211. #endif
  212. return 0;
  213. finish:
  214. av_packet_unref(pkt);
  215. return ret;
  216. }
  217. /**
  218. * Attempt to guess proper monotonic timestamps for decoded video frames
  219. * which might have incorrect times. Input timestamps may wrap around, in
  220. * which case the output will as well.
  221. *
  222. * @param pts the pts field of the decoded AVPacket, as passed through
  223. * AVFrame.pts
  224. * @param dts the dts field of the decoded AVPacket
  225. * @return one of the input values, may be AV_NOPTS_VALUE
  226. */
  227. static int64_t guess_correct_pts(AVCodecContext *ctx,
  228. int64_t reordered_pts, int64_t dts)
  229. {
  230. int64_t pts = AV_NOPTS_VALUE;
  231. if (dts != AV_NOPTS_VALUE) {
  232. ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
  233. ctx->pts_correction_last_dts = dts;
  234. } else if (reordered_pts != AV_NOPTS_VALUE)
  235. ctx->pts_correction_last_dts = reordered_pts;
  236. if (reordered_pts != AV_NOPTS_VALUE) {
  237. ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
  238. ctx->pts_correction_last_pts = reordered_pts;
  239. } else if(dts != AV_NOPTS_VALUE)
  240. ctx->pts_correction_last_pts = dts;
  241. if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
  242. && reordered_pts != AV_NOPTS_VALUE)
  243. pts = reordered_pts;
  244. else
  245. pts = dts;
  246. return pts;
  247. }
  248. /*
  249. * The core of the receive_frame_wrapper for the decoders implementing
  250. * the simple API. Certain decoders might consume partial packets without
  251. * returning any output, so this function needs to be called in a loop until it
  252. * returns EAGAIN.
  253. **/
  254. static inline int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame, int64_t *discarded_samples)
  255. {
  256. AVCodecInternal *avci = avctx->internal;
  257. DecodeSimpleContext *ds = &avci->ds;
  258. AVPacket *pkt = ds->in_pkt;
  259. 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. buffer_size_t 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 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. 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);
  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 (unsigned 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 (*got_sub_ptr)
  937. avctx->frame_number++;
  938. if (pkt == avci->buffer_pkt) // did we recode?
  939. av_packet_unref(avci->buffer_pkt);
  940. }
  941. return ret;
  942. }
  943. enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
  944. const enum AVPixelFormat *fmt)
  945. {
  946. const AVPixFmtDescriptor *desc;
  947. const AVCodecHWConfig *config;
  948. int i, n;
  949. // If a device was supplied when the codec was opened, assume that the
  950. // user wants to use it.
  951. if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
  952. AVHWDeviceContext *device_ctx =
  953. (AVHWDeviceContext*)avctx->hw_device_ctx->data;
  954. for (i = 0;; i++) {
  955. config = &avctx->codec->hw_configs[i]->public;
  956. if (!config)
  957. break;
  958. if (!(config->methods &
  959. AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
  960. continue;
  961. if (device_ctx->type != config->device_type)
  962. continue;
  963. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
  964. if (config->pix_fmt == fmt[n])
  965. return fmt[n];
  966. }
  967. }
  968. }
  969. // No device or other setup, so we have to choose from things which
  970. // don't any other external information.
  971. // If the last element of the list is a software format, choose it
  972. // (this should be best software format if any exist).
  973. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
  974. desc = av_pix_fmt_desc_get(fmt[n - 1]);
  975. if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
  976. return fmt[n - 1];
  977. // Finally, traverse the list in order and choose the first entry
  978. // with no external dependencies (if there is no hardware configuration
  979. // information available then this just picks the first entry).
  980. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
  981. for (i = 0;; i++) {
  982. config = avcodec_get_hw_config(avctx->codec, i);
  983. if (!config)
  984. break;
  985. if (config->pix_fmt == fmt[n])
  986. break;
  987. }
  988. if (!config) {
  989. // No specific config available, so the decoder must be able
  990. // to handle this format without any additional setup.
  991. return fmt[n];
  992. }
  993. if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
  994. // Usable with only internal setup.
  995. return fmt[n];
  996. }
  997. }
  998. // Nothing is usable, give up.
  999. return AV_PIX_FMT_NONE;
  1000. }
  1001. int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
  1002. enum AVHWDeviceType dev_type)
  1003. {
  1004. AVHWDeviceContext *device_ctx;
  1005. AVHWFramesContext *frames_ctx;
  1006. int ret;
  1007. if (!avctx->hwaccel)
  1008. return AVERROR(ENOSYS);
  1009. if (avctx->hw_frames_ctx)
  1010. return 0;
  1011. if (!avctx->hw_device_ctx) {
  1012. av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
  1013. "required for hardware accelerated decoding.\n");
  1014. return AVERROR(EINVAL);
  1015. }
  1016. device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
  1017. if (device_ctx->type != dev_type) {
  1018. av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
  1019. "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
  1020. av_hwdevice_get_type_name(device_ctx->type));
  1021. return AVERROR(EINVAL);
  1022. }
  1023. ret = avcodec_get_hw_frames_parameters(avctx,
  1024. avctx->hw_device_ctx,
  1025. avctx->hwaccel->pix_fmt,
  1026. &avctx->hw_frames_ctx);
  1027. if (ret < 0)
  1028. return ret;
  1029. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  1030. if (frames_ctx->initial_pool_size) {
  1031. // We guarantee 4 base work surfaces. The function above guarantees 1
  1032. // (the absolute minimum), so add the missing count.
  1033. frames_ctx->initial_pool_size += 3;
  1034. }
  1035. ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
  1036. if (ret < 0) {
  1037. av_buffer_unref(&avctx->hw_frames_ctx);
  1038. return ret;
  1039. }
  1040. return 0;
  1041. }
  1042. int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
  1043. AVBufferRef *device_ref,
  1044. enum AVPixelFormat hw_pix_fmt,
  1045. AVBufferRef **out_frames_ref)
  1046. {
  1047. AVBufferRef *frames_ref = NULL;
  1048. const AVCodecHWConfigInternal *hw_config;
  1049. const AVHWAccel *hwa;
  1050. int i, ret;
  1051. for (i = 0;; i++) {
  1052. hw_config = avctx->codec->hw_configs[i];
  1053. if (!hw_config)
  1054. return AVERROR(ENOENT);
  1055. if (hw_config->public.pix_fmt == hw_pix_fmt)
  1056. break;
  1057. }
  1058. hwa = hw_config->hwaccel;
  1059. if (!hwa || !hwa->frame_params)
  1060. return AVERROR(ENOENT);
  1061. frames_ref = av_hwframe_ctx_alloc(device_ref);
  1062. if (!frames_ref)
  1063. return AVERROR(ENOMEM);
  1064. ret = hwa->frame_params(avctx, frames_ref);
  1065. if (ret >= 0) {
  1066. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
  1067. if (frames_ctx->initial_pool_size) {
  1068. // If the user has requested that extra output surfaces be
  1069. // available then add them here.
  1070. if (avctx->extra_hw_frames > 0)
  1071. frames_ctx->initial_pool_size += avctx->extra_hw_frames;
  1072. // If frame threading is enabled then an extra surface per thread
  1073. // is also required.
  1074. if (avctx->active_thread_type & FF_THREAD_FRAME)
  1075. frames_ctx->initial_pool_size += avctx->thread_count;
  1076. }
  1077. *out_frames_ref = frames_ref;
  1078. } else {
  1079. av_buffer_unref(&frames_ref);
  1080. }
  1081. return ret;
  1082. }
  1083. static int hwaccel_init(AVCodecContext *avctx,
  1084. const AVCodecHWConfigInternal *hw_config)
  1085. {
  1086. const AVHWAccel *hwaccel;
  1087. int err;
  1088. hwaccel = hw_config->hwaccel;
  1089. if (hwaccel->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
  1090. avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  1091. av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
  1092. hwaccel->name);
  1093. return AVERROR_PATCHWELCOME;
  1094. }
  1095. if (hwaccel->priv_data_size) {
  1096. avctx->internal->hwaccel_priv_data =
  1097. av_mallocz(hwaccel->priv_data_size);
  1098. if (!avctx->internal->hwaccel_priv_data)
  1099. return AVERROR(ENOMEM);
  1100. }
  1101. avctx->hwaccel = hwaccel;
  1102. if (hwaccel->init) {
  1103. err = hwaccel->init(avctx);
  1104. if (err < 0) {
  1105. av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
  1106. "hwaccel initialisation returned error.\n",
  1107. av_get_pix_fmt_name(hw_config->public.pix_fmt));
  1108. av_freep(&avctx->internal->hwaccel_priv_data);
  1109. avctx->hwaccel = NULL;
  1110. return err;
  1111. }
  1112. }
  1113. return 0;
  1114. }
  1115. static void hwaccel_uninit(AVCodecContext *avctx)
  1116. {
  1117. if (avctx->hwaccel && avctx->hwaccel->uninit)
  1118. avctx->hwaccel->uninit(avctx);
  1119. av_freep(&avctx->internal->hwaccel_priv_data);
  1120. avctx->hwaccel = NULL;
  1121. av_buffer_unref(&avctx->hw_frames_ctx);
  1122. }
  1123. int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
  1124. {
  1125. const AVPixFmtDescriptor *desc;
  1126. enum AVPixelFormat *choices;
  1127. enum AVPixelFormat ret, user_choice;
  1128. const AVCodecHWConfigInternal *hw_config;
  1129. const AVCodecHWConfig *config;
  1130. int i, n, err;
  1131. // Find end of list.
  1132. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
  1133. // Must contain at least one entry.
  1134. av_assert0(n >= 1);
  1135. // If a software format is available, it must be the last entry.
  1136. desc = av_pix_fmt_desc_get(fmt[n - 1]);
  1137. if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
  1138. // No software format is available.
  1139. } else {
  1140. avctx->sw_pix_fmt = fmt[n - 1];
  1141. }
  1142. choices = av_malloc_array(n + 1, sizeof(*choices));
  1143. if (!choices)
  1144. return AV_PIX_FMT_NONE;
  1145. memcpy(choices, fmt, (n + 1) * sizeof(*choices));
  1146. for (;;) {
  1147. // Remove the previous hwaccel, if there was one.
  1148. hwaccel_uninit(avctx);
  1149. user_choice = avctx->get_format(avctx, choices);
  1150. if (user_choice == AV_PIX_FMT_NONE) {
  1151. // Explicitly chose nothing, give up.
  1152. ret = AV_PIX_FMT_NONE;
  1153. break;
  1154. }
  1155. desc = av_pix_fmt_desc_get(user_choice);
  1156. if (!desc) {
  1157. av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
  1158. "get_format() callback.\n");
  1159. ret = AV_PIX_FMT_NONE;
  1160. break;
  1161. }
  1162. av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
  1163. desc->name);
  1164. for (i = 0; i < n; i++) {
  1165. if (choices[i] == user_choice)
  1166. break;
  1167. }
  1168. if (i == n) {
  1169. av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
  1170. "%s not in possible list.\n", desc->name);
  1171. ret = AV_PIX_FMT_NONE;
  1172. break;
  1173. }
  1174. if (avctx->codec->hw_configs) {
  1175. for (i = 0;; i++) {
  1176. hw_config = avctx->codec->hw_configs[i];
  1177. if (!hw_config)
  1178. break;
  1179. if (hw_config->public.pix_fmt == user_choice)
  1180. break;
  1181. }
  1182. } else {
  1183. hw_config = NULL;
  1184. }
  1185. if (!hw_config) {
  1186. // No config available, so no extra setup required.
  1187. ret = user_choice;
  1188. break;
  1189. }
  1190. config = &hw_config->public;
  1191. if (config->methods &
  1192. AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
  1193. avctx->hw_frames_ctx) {
  1194. const AVHWFramesContext *frames_ctx =
  1195. (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  1196. if (frames_ctx->format != user_choice) {
  1197. av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
  1198. "does not match the format of the provided frames "
  1199. "context.\n", desc->name);
  1200. goto try_again;
  1201. }
  1202. } else if (config->methods &
  1203. AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
  1204. avctx->hw_device_ctx) {
  1205. const AVHWDeviceContext *device_ctx =
  1206. (AVHWDeviceContext*)avctx->hw_device_ctx->data;
  1207. if (device_ctx->type != config->device_type) {
  1208. av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
  1209. "does not match the type of the provided device "
  1210. "context.\n", desc->name);
  1211. goto try_again;
  1212. }
  1213. } else if (config->methods &
  1214. AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
  1215. // Internal-only setup, no additional configuration.
  1216. } else if (config->methods &
  1217. AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
  1218. // Some ad-hoc configuration we can't see and can't check.
  1219. } else {
  1220. av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
  1221. "missing configuration.\n", desc->name);
  1222. goto try_again;
  1223. }
  1224. if (hw_config->hwaccel) {
  1225. av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
  1226. "initialisation.\n", desc->name);
  1227. err = hwaccel_init(avctx, hw_config);
  1228. if (err < 0)
  1229. goto try_again;
  1230. }
  1231. ret = user_choice;
  1232. break;
  1233. try_again:
  1234. av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
  1235. "get_format() without it.\n", desc->name);
  1236. for (i = 0; i < n; i++) {
  1237. if (choices[i] == user_choice)
  1238. break;
  1239. }
  1240. for (; i + 1 < n; i++)
  1241. choices[i] = choices[i + 1];
  1242. --n;
  1243. }
  1244. av_freep(&choices);
  1245. return ret;
  1246. }
  1247. static void frame_pool_free(void *opaque, uint8_t *data)
  1248. {
  1249. FramePool *pool = (FramePool*)data;
  1250. int i;
  1251. for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
  1252. av_buffer_pool_uninit(&pool->pools[i]);
  1253. av_freep(&data);
  1254. }
  1255. static AVBufferRef *frame_pool_alloc(void)
  1256. {
  1257. FramePool *pool = av_mallocz(sizeof(*pool));
  1258. AVBufferRef *buf;
  1259. if (!pool)
  1260. return NULL;
  1261. buf = av_buffer_create((uint8_t*)pool, sizeof(*pool),
  1262. frame_pool_free, NULL, 0);
  1263. if (!buf) {
  1264. av_freep(&pool);
  1265. return NULL;
  1266. }
  1267. return buf;
  1268. }
  1269. static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
  1270. {
  1271. FramePool *pool = avctx->internal->pool ?
  1272. (FramePool*)avctx->internal->pool->data : NULL;
  1273. AVBufferRef *pool_buf;
  1274. int i, ret, ch, planes;
  1275. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  1276. int planar = av_sample_fmt_is_planar(frame->format);
  1277. ch = frame->channels;
  1278. planes = planar ? ch : 1;
  1279. }
  1280. if (pool && pool->format == frame->format) {
  1281. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
  1282. pool->width == frame->width && pool->height == frame->height)
  1283. return 0;
  1284. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pool->planes == planes &&
  1285. pool->channels == ch && frame->nb_samples == pool->samples)
  1286. return 0;
  1287. }
  1288. pool_buf = frame_pool_alloc();
  1289. if (!pool_buf)
  1290. return AVERROR(ENOMEM);
  1291. pool = (FramePool*)pool_buf->data;
  1292. switch (avctx->codec_type) {
  1293. case AVMEDIA_TYPE_VIDEO: {
  1294. int linesize[4];
  1295. int w = frame->width;
  1296. int h = frame->height;
  1297. int unaligned;
  1298. ptrdiff_t linesize1[4];
  1299. size_t size[4];
  1300. avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
  1301. do {
  1302. // NOTE: do not align linesizes individually, this breaks e.g. assumptions
  1303. // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
  1304. ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
  1305. if (ret < 0)
  1306. goto fail;
  1307. // increase alignment of w for next try (rhs gives the lowest bit set in w)
  1308. w += w & ~(w - 1);
  1309. unaligned = 0;
  1310. for (i = 0; i < 4; i++)
  1311. unaligned |= linesize[i] % pool->stride_align[i];
  1312. } while (unaligned);
  1313. for (i = 0; i < 4; i++)
  1314. linesize1[i] = linesize[i];
  1315. ret = av_image_fill_plane_sizes(size, avctx->pix_fmt, h, linesize1);
  1316. if (ret < 0)
  1317. goto fail;
  1318. for (i = 0; i < 4; i++) {
  1319. pool->linesize[i] = linesize[i];
  1320. if (size[i]) {
  1321. if (size[i] > INT_MAX - (16 + STRIDE_ALIGN - 1)) {
  1322. ret = AVERROR(EINVAL);
  1323. goto fail;
  1324. }
  1325. pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
  1326. CONFIG_MEMORY_POISONING ?
  1327. NULL :
  1328. av_buffer_allocz);
  1329. if (!pool->pools[i]) {
  1330. ret = AVERROR(ENOMEM);
  1331. goto fail;
  1332. }
  1333. }
  1334. }
  1335. pool->format = frame->format;
  1336. pool->width = frame->width;
  1337. pool->height = frame->height;
  1338. break;
  1339. }
  1340. case AVMEDIA_TYPE_AUDIO: {
  1341. ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
  1342. frame->nb_samples, frame->format, 0);
  1343. if (ret < 0)
  1344. goto fail;
  1345. pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
  1346. if (!pool->pools[0]) {
  1347. ret = AVERROR(ENOMEM);
  1348. goto fail;
  1349. }
  1350. pool->format = frame->format;
  1351. pool->planes = planes;
  1352. pool->channels = ch;
  1353. pool->samples = frame->nb_samples;
  1354. break;
  1355. }
  1356. default: av_assert0(0);
  1357. }
  1358. av_buffer_unref(&avctx->internal->pool);
  1359. avctx->internal->pool = pool_buf;
  1360. return 0;
  1361. fail:
  1362. av_buffer_unref(&pool_buf);
  1363. return ret;
  1364. }
  1365. static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
  1366. {
  1367. FramePool *pool = (FramePool*)avctx->internal->pool->data;
  1368. int planes = pool->planes;
  1369. int i;
  1370. frame->linesize[0] = pool->linesize[0];
  1371. if (planes > AV_NUM_DATA_POINTERS) {
  1372. frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
  1373. frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
  1374. frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
  1375. sizeof(*frame->extended_buf));
  1376. if (!frame->extended_data || !frame->extended_buf) {
  1377. av_freep(&frame->extended_data);
  1378. av_freep(&frame->extended_buf);
  1379. return AVERROR(ENOMEM);
  1380. }
  1381. } else {
  1382. frame->extended_data = frame->data;
  1383. av_assert0(frame->nb_extended_buf == 0);
  1384. }
  1385. for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
  1386. frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
  1387. if (!frame->buf[i])
  1388. goto fail;
  1389. frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
  1390. }
  1391. for (i = 0; i < frame->nb_extended_buf; i++) {
  1392. frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
  1393. if (!frame->extended_buf[i])
  1394. goto fail;
  1395. frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
  1396. }
  1397. if (avctx->debug & FF_DEBUG_BUFFERS)
  1398. av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
  1399. return 0;
  1400. fail:
  1401. av_frame_unref(frame);
  1402. return AVERROR(ENOMEM);
  1403. }
  1404. static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
  1405. {
  1406. FramePool *pool = (FramePool*)s->internal->pool->data;
  1407. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
  1408. int i;
  1409. if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
  1410. av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
  1411. return -1;
  1412. }
  1413. if (!desc) {
  1414. av_log(s, AV_LOG_ERROR,
  1415. "Unable to get pixel format descriptor for format %s\n",
  1416. av_get_pix_fmt_name(pic->format));
  1417. return AVERROR(EINVAL);
  1418. }
  1419. memset(pic->data, 0, sizeof(pic->data));
  1420. pic->extended_data = pic->data;
  1421. for (i = 0; i < 4 && pool->pools[i]; i++) {
  1422. pic->linesize[i] = pool->linesize[i];
  1423. pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
  1424. if (!pic->buf[i])
  1425. goto fail;
  1426. pic->data[i] = pic->buf[i]->data;
  1427. }
  1428. for (; i < AV_NUM_DATA_POINTERS; i++) {
  1429. pic->data[i] = NULL;
  1430. pic->linesize[i] = 0;
  1431. }
  1432. if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
  1433. ((desc->flags & FF_PSEUDOPAL) && pic->data[1]))
  1434. avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
  1435. if (s->debug & FF_DEBUG_BUFFERS)
  1436. av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
  1437. return 0;
  1438. fail:
  1439. av_frame_unref(pic);
  1440. return AVERROR(ENOMEM);
  1441. }
  1442. int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
  1443. {
  1444. int ret;
  1445. if (avctx->hw_frames_ctx) {
  1446. ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
  1447. frame->width = avctx->coded_width;
  1448. frame->height = avctx->coded_height;
  1449. return ret;
  1450. }
  1451. if ((ret = update_frame_pool(avctx, frame)) < 0)
  1452. return ret;
  1453. switch (avctx->codec_type) {
  1454. case AVMEDIA_TYPE_VIDEO:
  1455. return video_get_buffer(avctx, frame);
  1456. case AVMEDIA_TYPE_AUDIO:
  1457. return audio_get_buffer(avctx, frame);
  1458. default:
  1459. return -1;
  1460. }
  1461. }
  1462. static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
  1463. {
  1464. buffer_size_t size;
  1465. const uint8_t *side_metadata;
  1466. AVDictionary **frame_md = &frame->metadata;
  1467. side_metadata = av_packet_get_side_data(avpkt,
  1468. AV_PKT_DATA_STRINGS_METADATA, &size);
  1469. return av_packet_unpack_dictionary(side_metadata, size, frame_md);
  1470. }
  1471. int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
  1472. {
  1473. AVPacket *pkt = avctx->internal->last_pkt_props;
  1474. static const struct {
  1475. enum AVPacketSideDataType packet;
  1476. enum AVFrameSideDataType frame;
  1477. } sd[] = {
  1478. { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
  1479. { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
  1480. { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
  1481. { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
  1482. { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
  1483. { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
  1484. { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
  1485. { AV_PKT_DATA_A53_CC, AV_FRAME_DATA_A53_CC },
  1486. { AV_PKT_DATA_ICC_PROFILE, AV_FRAME_DATA_ICC_PROFILE },
  1487. { AV_PKT_DATA_S12M_TIMECODE, AV_FRAME_DATA_S12M_TIMECODE },
  1488. };
  1489. if (IS_EMPTY(pkt) && av_fifo_size(avctx->internal->pkt_props) >= sizeof(*pkt))
  1490. av_fifo_generic_read(avctx->internal->pkt_props,
  1491. pkt, sizeof(*pkt), NULL);
  1492. frame->pts = pkt->pts;
  1493. #if FF_API_PKT_PTS
  1494. FF_DISABLE_DEPRECATION_WARNINGS
  1495. frame->pkt_pts = pkt->pts;
  1496. FF_ENABLE_DEPRECATION_WARNINGS
  1497. #endif
  1498. frame->pkt_pos = pkt->pos;
  1499. frame->pkt_duration = pkt->duration;
  1500. frame->pkt_size = pkt->size;
  1501. for (int i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
  1502. buffer_size_t size;
  1503. uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
  1504. if (packet_sd) {
  1505. AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
  1506. sd[i].frame,
  1507. size);
  1508. if (!frame_sd)
  1509. return AVERROR(ENOMEM);
  1510. memcpy(frame_sd->data, packet_sd, size);
  1511. }
  1512. }
  1513. add_metadata_from_side_data(pkt, frame);
  1514. if (pkt->flags & AV_PKT_FLAG_DISCARD) {
  1515. frame->flags |= AV_FRAME_FLAG_DISCARD;
  1516. } else {
  1517. frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
  1518. }
  1519. frame->reordered_opaque = avctx->reordered_opaque;
  1520. if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
  1521. frame->color_primaries = avctx->color_primaries;
  1522. if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
  1523. frame->color_trc = avctx->color_trc;
  1524. if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
  1525. frame->colorspace = avctx->colorspace;
  1526. if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
  1527. frame->color_range = avctx->color_range;
  1528. if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
  1529. frame->chroma_location = avctx->chroma_sample_location;
  1530. switch (avctx->codec->type) {
  1531. case AVMEDIA_TYPE_VIDEO:
  1532. frame->format = avctx->pix_fmt;
  1533. if (!frame->sample_aspect_ratio.num)
  1534. frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
  1535. if (frame->width && frame->height &&
  1536. av_image_check_sar(frame->width, frame->height,
  1537. frame->sample_aspect_ratio) < 0) {
  1538. av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
  1539. frame->sample_aspect_ratio.num,
  1540. frame->sample_aspect_ratio.den);
  1541. frame->sample_aspect_ratio = (AVRational){ 0, 1 };
  1542. }
  1543. break;
  1544. case AVMEDIA_TYPE_AUDIO:
  1545. if (!frame->sample_rate)
  1546. frame->sample_rate = avctx->sample_rate;
  1547. if (frame->format < 0)
  1548. frame->format = avctx->sample_fmt;
  1549. if (!frame->channel_layout) {
  1550. if (avctx->channel_layout) {
  1551. if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
  1552. avctx->channels) {
  1553. av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
  1554. "configuration.\n");
  1555. return AVERROR(EINVAL);
  1556. }
  1557. frame->channel_layout = avctx->channel_layout;
  1558. } else {
  1559. if (avctx->channels > FF_SANE_NB_CHANNELS) {
  1560. av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
  1561. avctx->channels);
  1562. return AVERROR(ENOSYS);
  1563. }
  1564. }
  1565. }
  1566. frame->channels = avctx->channels;
  1567. break;
  1568. }
  1569. return 0;
  1570. }
  1571. static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
  1572. {
  1573. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  1574. int i;
  1575. int num_planes = av_pix_fmt_count_planes(frame->format);
  1576. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
  1577. int flags = desc ? desc->flags : 0;
  1578. if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
  1579. num_planes = 2;
  1580. if ((flags & FF_PSEUDOPAL) && frame->data[1])
  1581. num_planes = 2;
  1582. for (i = 0; i < num_planes; i++) {
  1583. av_assert0(frame->data[i]);
  1584. }
  1585. // For formats without data like hwaccel allow unused pointers to be non-NULL.
  1586. for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
  1587. if (frame->data[i])
  1588. av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
  1589. frame->data[i] = NULL;
  1590. }
  1591. }
  1592. }
  1593. static void decode_data_free(void *opaque, uint8_t *data)
  1594. {
  1595. FrameDecodeData *fdd = (FrameDecodeData*)data;
  1596. if (fdd->post_process_opaque_free)
  1597. fdd->post_process_opaque_free(fdd->post_process_opaque);
  1598. if (fdd->hwaccel_priv_free)
  1599. fdd->hwaccel_priv_free(fdd->hwaccel_priv);
  1600. av_freep(&fdd);
  1601. }
  1602. int ff_attach_decode_data(AVFrame *frame)
  1603. {
  1604. AVBufferRef *fdd_buf;
  1605. FrameDecodeData *fdd;
  1606. av_assert1(!frame->private_ref);
  1607. av_buffer_unref(&frame->private_ref);
  1608. fdd = av_mallocz(sizeof(*fdd));
  1609. if (!fdd)
  1610. return AVERROR(ENOMEM);
  1611. fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
  1612. NULL, AV_BUFFER_FLAG_READONLY);
  1613. if (!fdd_buf) {
  1614. av_freep(&fdd);
  1615. return AVERROR(ENOMEM);
  1616. }
  1617. frame->private_ref = fdd_buf;
  1618. return 0;
  1619. }
  1620. int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
  1621. {
  1622. const AVHWAccel *hwaccel = avctx->hwaccel;
  1623. int override_dimensions = 1;
  1624. int ret;
  1625. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  1626. if ((unsigned)avctx->width > INT_MAX - STRIDE_ALIGN ||
  1627. (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) {
  1628. av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
  1629. ret = AVERROR(EINVAL);
  1630. goto fail;
  1631. }
  1632. if (frame->width <= 0 || frame->height <= 0) {
  1633. frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
  1634. frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
  1635. override_dimensions = 0;
  1636. }
  1637. if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
  1638. av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
  1639. ret = AVERROR(EINVAL);
  1640. goto fail;
  1641. }
  1642. } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  1643. if (frame->nb_samples * (int64_t)avctx->channels > avctx->max_samples) {
  1644. av_log(avctx, AV_LOG_ERROR, "samples per frame %d, exceeds max_samples %"PRId64"\n", frame->nb_samples, avctx->max_samples);
  1645. ret = AVERROR(EINVAL);
  1646. goto fail;
  1647. }
  1648. }
  1649. ret = ff_decode_frame_props(avctx, frame);
  1650. if (ret < 0)
  1651. goto fail;
  1652. if (hwaccel) {
  1653. if (hwaccel->alloc_frame) {
  1654. ret = hwaccel->alloc_frame(avctx, frame);
  1655. goto end;
  1656. }
  1657. } else
  1658. avctx->sw_pix_fmt = avctx->pix_fmt;
  1659. ret = avctx->get_buffer2(avctx, frame, flags);
  1660. if (ret < 0)
  1661. goto fail;
  1662. validate_avframe_allocation(avctx, frame);
  1663. ret = ff_attach_decode_data(frame);
  1664. if (ret < 0)
  1665. goto fail;
  1666. end:
  1667. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
  1668. !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
  1669. frame->width = avctx->width;
  1670. frame->height = avctx->height;
  1671. }
  1672. fail:
  1673. if (ret < 0) {
  1674. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  1675. av_frame_unref(frame);
  1676. }
  1677. return ret;
  1678. }
  1679. static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
  1680. {
  1681. AVFrame *tmp;
  1682. int ret;
  1683. av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
  1684. if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
  1685. av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
  1686. frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
  1687. av_frame_unref(frame);
  1688. }
  1689. if (!frame->data[0])
  1690. return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
  1691. if ((flags & FF_REGET_BUFFER_FLAG_READONLY) || av_frame_is_writable(frame))
  1692. return ff_decode_frame_props(avctx, frame);
  1693. tmp = av_frame_alloc();
  1694. if (!tmp)
  1695. return AVERROR(ENOMEM);
  1696. av_frame_move_ref(tmp, frame);
  1697. ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
  1698. if (ret < 0) {
  1699. av_frame_free(&tmp);
  1700. return ret;
  1701. }
  1702. av_frame_copy(frame, tmp);
  1703. av_frame_free(&tmp);
  1704. return 0;
  1705. }
  1706. int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
  1707. {
  1708. int ret = reget_buffer_internal(avctx, frame, flags);
  1709. if (ret < 0)
  1710. av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
  1711. return ret;
  1712. }
  1713. int ff_decode_preinit(AVCodecContext *avctx)
  1714. {
  1715. int ret = 0;
  1716. /* if the decoder init function was already called previously,
  1717. * free the already allocated subtitle_header before overwriting it */
  1718. av_freep(&avctx->subtitle_header);
  1719. #if FF_API_THREAD_SAFE_CALLBACKS
  1720. FF_DISABLE_DEPRECATION_WARNINGS
  1721. if ((avctx->thread_type & FF_THREAD_FRAME) &&
  1722. avctx->get_buffer2 != avcodec_default_get_buffer2 &&
  1723. !avctx->thread_safe_callbacks) {
  1724. av_log(avctx, AV_LOG_WARNING, "Requested frame threading with a "
  1725. "custom get_buffer2() implementation which is not marked as "
  1726. "thread safe. This is not supported anymore, make your "
  1727. "callback thread-safe.\n");
  1728. }
  1729. FF_ENABLE_DEPRECATION_WARNINGS
  1730. #endif
  1731. if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
  1732. av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
  1733. avctx->codec->max_lowres);
  1734. avctx->lowres = avctx->codec->max_lowres;
  1735. }
  1736. avctx->pts_correction_num_faulty_pts =
  1737. avctx->pts_correction_num_faulty_dts = 0;
  1738. avctx->pts_correction_last_pts =
  1739. avctx->pts_correction_last_dts = INT64_MIN;
  1740. if ( !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY
  1741. && avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO)
  1742. av_log(avctx, AV_LOG_WARNING,
  1743. "gray decoding requested but not enabled at configuration time\n");
  1744. if (avctx->flags2 & AV_CODEC_FLAG2_EXPORT_MVS) {
  1745. avctx->export_side_data |= AV_CODEC_EXPORT_DATA_MVS;
  1746. }
  1747. ret = decode_bsfs_init(avctx);
  1748. if (ret < 0)
  1749. return ret;
  1750. return 0;
  1751. }