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.

1694 lines
54KB

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