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.

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