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.

1968 lines
64KB

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