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.

2021 lines
66KB

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