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.

1747 lines
56KB

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