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.

1992 lines
66KB

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