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.

1985 lines
65KB

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