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.

2062 lines
68KB

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