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.

1712 lines
55KB

  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 = avci->to_free->channels;
  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. frame->channels = avci->to_free->channels;
  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, actual_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. frame->pkt_pos = 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. actual_got_frame = got_frame;
  377. if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
  378. if (frame->flags & AV_FRAME_FLAG_DISCARD)
  379. got_frame = 0;
  380. if (got_frame)
  381. frame->best_effort_timestamp = 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. frame->best_effort_timestamp = guess_correct_pts(avctx,
  392. frame->pts,
  393. frame->pkt_dts);
  394. if (frame->format == AV_SAMPLE_FMT_NONE)
  395. frame->format = avctx->sample_fmt;
  396. if (!frame->channel_layout)
  397. frame->channel_layout = avctx->channel_layout;
  398. if (!frame->channels)
  399. frame->channels = avctx->channels;
  400. if (!frame->sample_rate)
  401. frame->sample_rate = avctx->sample_rate;
  402. }
  403. side= av_packet_get_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
  404. if(side && side_size>=10) {
  405. avctx->internal->skip_samples = AV_RL32(side) * avctx->internal->skip_samples_multiplier;
  406. discard_padding = AV_RL32(side + 4);
  407. av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
  408. avctx->internal->skip_samples, (int)discard_padding);
  409. skip_reason = AV_RL8(side + 8);
  410. discard_reason = AV_RL8(side + 9);
  411. }
  412. if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
  413. !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
  414. avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples);
  415. got_frame = 0;
  416. }
  417. if (avctx->internal->skip_samples > 0 && got_frame &&
  418. !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
  419. if(frame->nb_samples <= avctx->internal->skip_samples){
  420. got_frame = 0;
  421. avctx->internal->skip_samples -= frame->nb_samples;
  422. av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
  423. avctx->internal->skip_samples);
  424. } else {
  425. av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
  426. frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
  427. if(avctx->pkt_timebase.num && avctx->sample_rate) {
  428. int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
  429. (AVRational){1, avctx->sample_rate},
  430. avctx->pkt_timebase);
  431. if(frame->pts!=AV_NOPTS_VALUE)
  432. frame->pts += diff_ts;
  433. #if FF_API_PKT_PTS
  434. FF_DISABLE_DEPRECATION_WARNINGS
  435. if(frame->pkt_pts!=AV_NOPTS_VALUE)
  436. frame->pkt_pts += diff_ts;
  437. FF_ENABLE_DEPRECATION_WARNINGS
  438. #endif
  439. if(frame->pkt_dts!=AV_NOPTS_VALUE)
  440. frame->pkt_dts += diff_ts;
  441. if (frame->pkt_duration >= diff_ts)
  442. frame->pkt_duration -= diff_ts;
  443. } else {
  444. av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
  445. }
  446. av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
  447. avctx->internal->skip_samples, frame->nb_samples);
  448. frame->nb_samples -= avctx->internal->skip_samples;
  449. avctx->internal->skip_samples = 0;
  450. }
  451. }
  452. if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
  453. !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
  454. if (discard_padding == frame->nb_samples) {
  455. got_frame = 0;
  456. } else {
  457. if(avctx->pkt_timebase.num && avctx->sample_rate) {
  458. int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
  459. (AVRational){1, avctx->sample_rate},
  460. avctx->pkt_timebase);
  461. frame->pkt_duration = diff_ts;
  462. } else {
  463. av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
  464. }
  465. av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
  466. (int)discard_padding, frame->nb_samples);
  467. frame->nb_samples -= discard_padding;
  468. }
  469. }
  470. if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
  471. AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
  472. if (fside) {
  473. AV_WL32(fside->data, avctx->internal->skip_samples);
  474. AV_WL32(fside->data + 4, discard_padding);
  475. AV_WL8(fside->data + 8, skip_reason);
  476. AV_WL8(fside->data + 9, discard_reason);
  477. avctx->internal->skip_samples = 0;
  478. }
  479. }
  480. }
  481. #if FF_API_MERGE_SD
  482. if (did_split) {
  483. av_packet_free_side_data(&tmp);
  484. if(ret == tmp.size)
  485. ret = pkt->size;
  486. }
  487. #endif
  488. if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
  489. !avci->showed_multi_packet_warning &&
  490. ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
  491. av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
  492. avci->showed_multi_packet_warning = 1;
  493. }
  494. if (!got_frame)
  495. av_frame_unref(frame);
  496. if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
  497. ret = pkt->size;
  498. #if FF_API_AVCTX_TIMEBASE
  499. if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
  500. avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
  501. #endif
  502. /* do not stop draining when actual_got_frame != 0 or ret < 0 */
  503. /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
  504. if (avctx->internal->draining && !actual_got_frame) {
  505. if (ret < 0) {
  506. /* prevent infinite loop if a decoder wrongly always return error on draining */
  507. /* reasonable nb_errors_max = maximum b frames + thread count */
  508. int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
  509. avctx->thread_count : 1);
  510. if (avci->nb_draining_errors++ >= nb_errors_max) {
  511. av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
  512. "Stop draining and force EOF.\n");
  513. avci->draining_done = 1;
  514. ret = AVERROR_BUG;
  515. }
  516. } else {
  517. avci->draining_done = 1;
  518. }
  519. }
  520. avci->compat_decode_consumed += ret;
  521. if (ret >= pkt->size || ret < 0) {
  522. av_packet_unref(pkt);
  523. } else {
  524. int consumed = ret;
  525. pkt->data += consumed;
  526. pkt->size -= consumed;
  527. avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
  528. pkt->pts = AV_NOPTS_VALUE;
  529. pkt->dts = AV_NOPTS_VALUE;
  530. avci->last_pkt_props->pts = AV_NOPTS_VALUE;
  531. avci->last_pkt_props->dts = AV_NOPTS_VALUE;
  532. }
  533. if (got_frame)
  534. av_assert0(frame->buf[0]);
  535. return ret < 0 ? ret : 0;
  536. }
  537. static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
  538. {
  539. int ret;
  540. while (!frame->buf[0]) {
  541. ret = decode_simple_internal(avctx, frame);
  542. if (ret < 0)
  543. return ret;
  544. }
  545. return 0;
  546. }
  547. static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
  548. {
  549. AVCodecInternal *avci = avctx->internal;
  550. int ret;
  551. av_assert0(!frame->buf[0]);
  552. if (avctx->codec->receive_frame)
  553. ret = avctx->codec->receive_frame(avctx, frame);
  554. else
  555. ret = decode_simple_receive_frame(avctx, frame);
  556. if (ret == AVERROR_EOF)
  557. avci->draining_done = 1;
  558. return ret;
  559. }
  560. int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
  561. {
  562. AVCodecInternal *avci = avctx->internal;
  563. int ret;
  564. if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
  565. return AVERROR(EINVAL);
  566. if (avctx->internal->draining)
  567. return AVERROR_EOF;
  568. if (avpkt && !avpkt->size && avpkt->data)
  569. return AVERROR(EINVAL);
  570. ret = bsfs_init(avctx);
  571. if (ret < 0)
  572. return ret;
  573. av_packet_unref(avci->buffer_pkt);
  574. if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
  575. ret = av_packet_ref(avci->buffer_pkt, avpkt);
  576. if (ret < 0)
  577. return ret;
  578. }
  579. ret = av_bsf_send_packet(avci->filter.bsfs[0], avci->buffer_pkt);
  580. if (ret < 0) {
  581. av_packet_unref(avci->buffer_pkt);
  582. return ret;
  583. }
  584. if (!avci->buffer_frame->buf[0]) {
  585. ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
  586. if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
  587. return ret;
  588. }
  589. return 0;
  590. }
  591. int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
  592. {
  593. AVCodecInternal *avci = avctx->internal;
  594. int ret;
  595. av_frame_unref(frame);
  596. if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
  597. return AVERROR(EINVAL);
  598. ret = bsfs_init(avctx);
  599. if (ret < 0)
  600. return ret;
  601. if (avci->buffer_frame->buf[0]) {
  602. av_frame_move_ref(frame, avci->buffer_frame);
  603. } else {
  604. ret = decode_receive_frame_internal(avctx, frame);
  605. if (ret < 0)
  606. return ret;
  607. }
  608. avctx->frame_number++;
  609. return 0;
  610. }
  611. static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
  612. int *got_frame, const AVPacket *pkt)
  613. {
  614. AVCodecInternal *avci = avctx->internal;
  615. int ret = 0;
  616. av_assert0(avci->compat_decode_consumed == 0);
  617. *got_frame = 0;
  618. avci->compat_decode = 1;
  619. if (avci->compat_decode_partial_size > 0 &&
  620. avci->compat_decode_partial_size != pkt->size) {
  621. av_log(avctx, AV_LOG_ERROR,
  622. "Got unexpected packet size after a partial decode\n");
  623. ret = AVERROR(EINVAL);
  624. goto finish;
  625. }
  626. if (!avci->compat_decode_partial_size) {
  627. ret = avcodec_send_packet(avctx, pkt);
  628. if (ret == AVERROR_EOF)
  629. ret = 0;
  630. else if (ret == AVERROR(EAGAIN)) {
  631. /* we fully drain all the output in each decode call, so this should not
  632. * ever happen */
  633. ret = AVERROR_BUG;
  634. goto finish;
  635. } else if (ret < 0)
  636. goto finish;
  637. }
  638. while (ret >= 0) {
  639. ret = avcodec_receive_frame(avctx, frame);
  640. if (ret < 0) {
  641. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  642. ret = 0;
  643. goto finish;
  644. }
  645. if (frame != avci->compat_decode_frame) {
  646. if (!avctx->refcounted_frames) {
  647. ret = unrefcount_frame(avci, frame);
  648. if (ret < 0)
  649. goto finish;
  650. }
  651. *got_frame = 1;
  652. frame = avci->compat_decode_frame;
  653. } else {
  654. if (!avci->compat_decode_warned) {
  655. av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
  656. "API cannot return all the frames for this decoder. "
  657. "Some frames will be dropped. Update your code to the "
  658. "new decoding API to fix this.\n");
  659. avci->compat_decode_warned = 1;
  660. }
  661. }
  662. if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
  663. break;
  664. }
  665. finish:
  666. if (ret == 0) {
  667. /* if there are any bsfs then assume full packet is always consumed */
  668. if (avctx->codec->bsfs)
  669. ret = pkt->size;
  670. else
  671. ret = FFMIN(avci->compat_decode_consumed, pkt->size);
  672. }
  673. avci->compat_decode_consumed = 0;
  674. avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
  675. return ret;
  676. }
  677. int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
  678. int *got_picture_ptr,
  679. const AVPacket *avpkt)
  680. {
  681. return compat_decode(avctx, picture, got_picture_ptr, avpkt);
  682. }
  683. int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
  684. AVFrame *frame,
  685. int *got_frame_ptr,
  686. const AVPacket *avpkt)
  687. {
  688. return compat_decode(avctx, frame, got_frame_ptr, avpkt);
  689. }
  690. static void get_subtitle_defaults(AVSubtitle *sub)
  691. {
  692. memset(sub, 0, sizeof(*sub));
  693. sub->pts = AV_NOPTS_VALUE;
  694. }
  695. #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
  696. static int recode_subtitle(AVCodecContext *avctx,
  697. AVPacket *outpkt, const AVPacket *inpkt)
  698. {
  699. #if CONFIG_ICONV
  700. iconv_t cd = (iconv_t)-1;
  701. int ret = 0;
  702. char *inb, *outb;
  703. size_t inl, outl;
  704. AVPacket tmp;
  705. #endif
  706. if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
  707. return 0;
  708. #if CONFIG_ICONV
  709. cd = iconv_open("UTF-8", avctx->sub_charenc);
  710. av_assert0(cd != (iconv_t)-1);
  711. inb = inpkt->data;
  712. inl = inpkt->size;
  713. if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
  714. av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
  715. ret = AVERROR(ENOMEM);
  716. goto end;
  717. }
  718. ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
  719. if (ret < 0)
  720. goto end;
  721. outpkt->buf = tmp.buf;
  722. outpkt->data = tmp.data;
  723. outpkt->size = tmp.size;
  724. outb = outpkt->data;
  725. outl = outpkt->size;
  726. if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
  727. iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
  728. outl >= outpkt->size || inl != 0) {
  729. ret = FFMIN(AVERROR(errno), -1);
  730. av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
  731. "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
  732. av_packet_unref(&tmp);
  733. goto end;
  734. }
  735. outpkt->size -= outl;
  736. memset(outpkt->data + outpkt->size, 0, outl);
  737. end:
  738. if (cd != (iconv_t)-1)
  739. iconv_close(cd);
  740. return ret;
  741. #else
  742. av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
  743. return AVERROR(EINVAL);
  744. #endif
  745. }
  746. static int utf8_check(const uint8_t *str)
  747. {
  748. const uint8_t *byte;
  749. uint32_t codepoint, min;
  750. while (*str) {
  751. byte = str;
  752. GET_UTF8(codepoint, *(byte++), return 0;);
  753. min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
  754. 1 << (5 * (byte - str) - 4);
  755. if (codepoint < min || codepoint >= 0x110000 ||
  756. codepoint == 0xFFFE /* BOM */ ||
  757. codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
  758. return 0;
  759. str = byte;
  760. }
  761. return 1;
  762. }
  763. #if FF_API_ASS_TIMING
  764. static void insert_ts(AVBPrint *buf, int ts)
  765. {
  766. if (ts == -1) {
  767. av_bprintf(buf, "9:59:59.99,");
  768. } else {
  769. int h, m, s;
  770. h = ts/360000; ts -= 360000*h;
  771. m = ts/ 6000; ts -= 6000*m;
  772. s = ts/ 100; ts -= 100*s;
  773. av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
  774. }
  775. }
  776. static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
  777. {
  778. int i;
  779. AVBPrint buf;
  780. av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
  781. for (i = 0; i < sub->num_rects; i++) {
  782. char *final_dialog;
  783. const char *dialog;
  784. AVSubtitleRect *rect = sub->rects[i];
  785. int ts_start, ts_duration = -1;
  786. long int layer;
  787. if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
  788. continue;
  789. av_bprint_clear(&buf);
  790. /* skip ReadOrder */
  791. dialog = strchr(rect->ass, ',');
  792. if (!dialog)
  793. continue;
  794. dialog++;
  795. /* extract Layer or Marked */
  796. layer = strtol(dialog, (char**)&dialog, 10);
  797. if (*dialog != ',')
  798. continue;
  799. dialog++;
  800. /* rescale timing to ASS time base (ms) */
  801. ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
  802. if (pkt->duration != -1)
  803. ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
  804. sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
  805. /* construct ASS (standalone file form with timestamps) string */
  806. av_bprintf(&buf, "Dialogue: %ld,", layer);
  807. insert_ts(&buf, ts_start);
  808. insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
  809. av_bprintf(&buf, "%s\r\n", dialog);
  810. final_dialog = av_strdup(buf.str);
  811. if (!av_bprint_is_complete(&buf) || !final_dialog) {
  812. av_freep(&final_dialog);
  813. av_bprint_finalize(&buf, NULL);
  814. return AVERROR(ENOMEM);
  815. }
  816. av_freep(&rect->ass);
  817. rect->ass = final_dialog;
  818. }
  819. av_bprint_finalize(&buf, NULL);
  820. return 0;
  821. }
  822. #endif
  823. int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
  824. int *got_sub_ptr,
  825. AVPacket *avpkt)
  826. {
  827. int i, ret = 0;
  828. if (!avpkt->data && avpkt->size) {
  829. av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
  830. return AVERROR(EINVAL);
  831. }
  832. if (!avctx->codec)
  833. return AVERROR(EINVAL);
  834. if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
  835. av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
  836. return AVERROR(EINVAL);
  837. }
  838. *got_sub_ptr = 0;
  839. get_subtitle_defaults(sub);
  840. if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
  841. AVPacket pkt_recoded;
  842. AVPacket tmp = *avpkt;
  843. #if FF_API_MERGE_SD
  844. FF_DISABLE_DEPRECATION_WARNINGS
  845. int did_split = av_packet_split_side_data(&tmp);
  846. //apply_param_change(avctx, &tmp);
  847. if (did_split) {
  848. /* FFMIN() prevents overflow in case the packet wasn't allocated with
  849. * proper padding.
  850. * If the side data is smaller than the buffer padding size, the
  851. * remaining bytes should have already been filled with zeros by the
  852. * original packet allocation anyway. */
  853. memset(tmp.data + tmp.size, 0,
  854. FFMIN(avpkt->size - tmp.size, AV_INPUT_BUFFER_PADDING_SIZE));
  855. }
  856. FF_ENABLE_DEPRECATION_WARNINGS
  857. #endif
  858. pkt_recoded = tmp;
  859. ret = recode_subtitle(avctx, &pkt_recoded, &tmp);
  860. if (ret < 0) {
  861. *got_sub_ptr = 0;
  862. } else {
  863. ret = extract_packet_props(avctx->internal, &pkt_recoded);
  864. if (ret < 0)
  865. return ret;
  866. if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
  867. sub->pts = av_rescale_q(avpkt->pts,
  868. avctx->pkt_timebase, AV_TIME_BASE_Q);
  869. ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
  870. av_assert1((ret >= 0) >= !!*got_sub_ptr &&
  871. !!*got_sub_ptr >= !!sub->num_rects);
  872. #if FF_API_ASS_TIMING
  873. if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
  874. && *got_sub_ptr && sub->num_rects) {
  875. const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
  876. : avctx->time_base;
  877. int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
  878. if (err < 0)
  879. ret = err;
  880. }
  881. #endif
  882. if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
  883. avctx->pkt_timebase.num) {
  884. AVRational ms = { 1, 1000 };
  885. sub->end_display_time = av_rescale_q(avpkt->duration,
  886. avctx->pkt_timebase, ms);
  887. }
  888. if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
  889. sub->format = 0;
  890. else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
  891. sub->format = 1;
  892. for (i = 0; i < sub->num_rects; i++) {
  893. if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
  894. av_log(avctx, AV_LOG_ERROR,
  895. "Invalid UTF-8 in decoded subtitles text; "
  896. "maybe missing -sub_charenc option\n");
  897. avsubtitle_free(sub);
  898. ret = AVERROR_INVALIDDATA;
  899. break;
  900. }
  901. }
  902. if (tmp.data != pkt_recoded.data) { // did we recode?
  903. /* prevent from destroying side data from original packet */
  904. pkt_recoded.side_data = NULL;
  905. pkt_recoded.side_data_elems = 0;
  906. av_packet_unref(&pkt_recoded);
  907. }
  908. }
  909. #if FF_API_MERGE_SD
  910. if (did_split) {
  911. av_packet_free_side_data(&tmp);
  912. if(ret == tmp.size)
  913. ret = avpkt->size;
  914. }
  915. #endif
  916. if (*got_sub_ptr)
  917. avctx->frame_number++;
  918. }
  919. return ret;
  920. }
  921. static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
  922. {
  923. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
  924. return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
  925. }
  926. enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
  927. {
  928. while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
  929. ++fmt;
  930. return fmt[0];
  931. }
  932. static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
  933. enum AVPixelFormat pix_fmt)
  934. {
  935. AVHWAccel *hwaccel = NULL;
  936. while ((hwaccel = av_hwaccel_next(hwaccel)))
  937. if (hwaccel->id == codec_id
  938. && hwaccel->pix_fmt == pix_fmt)
  939. return hwaccel;
  940. return NULL;
  941. }
  942. static int setup_hwaccel(AVCodecContext *avctx,
  943. const enum AVPixelFormat fmt,
  944. const char *name)
  945. {
  946. AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
  947. int ret = 0;
  948. if (!hwa) {
  949. av_log(avctx, AV_LOG_ERROR,
  950. "Could not find an AVHWAccel for the pixel format: %s",
  951. name);
  952. return AVERROR(ENOENT);
  953. }
  954. if (hwa->capabilities & HWACCEL_CODEC_CAP_EXPERIMENTAL &&
  955. avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  956. av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
  957. hwa->name);
  958. return AVERROR_PATCHWELCOME;
  959. }
  960. if (hwa->priv_data_size) {
  961. avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
  962. if (!avctx->internal->hwaccel_priv_data)
  963. return AVERROR(ENOMEM);
  964. }
  965. if (hwa->init) {
  966. ret = hwa->init(avctx);
  967. if (ret < 0) {
  968. av_freep(&avctx->internal->hwaccel_priv_data);
  969. return ret;
  970. }
  971. }
  972. avctx->hwaccel = hwa;
  973. return 0;
  974. }
  975. int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
  976. {
  977. const AVPixFmtDescriptor *desc;
  978. enum AVPixelFormat *choices;
  979. enum AVPixelFormat ret;
  980. unsigned n = 0;
  981. while (fmt[n] != AV_PIX_FMT_NONE)
  982. ++n;
  983. av_assert0(n >= 1);
  984. avctx->sw_pix_fmt = fmt[n - 1];
  985. av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
  986. choices = av_malloc_array(n + 1, sizeof(*choices));
  987. if (!choices)
  988. return AV_PIX_FMT_NONE;
  989. memcpy(choices, fmt, (n + 1) * sizeof(*choices));
  990. for (;;) {
  991. if (avctx->hwaccel && avctx->hwaccel->uninit)
  992. avctx->hwaccel->uninit(avctx);
  993. av_freep(&avctx->internal->hwaccel_priv_data);
  994. avctx->hwaccel = NULL;
  995. av_buffer_unref(&avctx->hw_frames_ctx);
  996. ret = avctx->get_format(avctx, choices);
  997. desc = av_pix_fmt_desc_get(ret);
  998. if (!desc) {
  999. ret = AV_PIX_FMT_NONE;
  1000. break;
  1001. }
  1002. if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
  1003. break;
  1004. #if FF_API_CAP_VDPAU
  1005. if (avctx->codec->capabilities&AV_CODEC_CAP_HWACCEL_VDPAU)
  1006. break;
  1007. #endif
  1008. if (avctx->hw_frames_ctx) {
  1009. AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  1010. if (hw_frames_ctx->format != ret) {
  1011. av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() "
  1012. "does not match the format of provided AVHWFramesContext\n");
  1013. ret = AV_PIX_FMT_NONE;
  1014. break;
  1015. }
  1016. }
  1017. if (!setup_hwaccel(avctx, ret, desc->name))
  1018. break;
  1019. /* Remove failed hwaccel from choices */
  1020. for (n = 0; choices[n] != ret; n++)
  1021. av_assert0(choices[n] != AV_PIX_FMT_NONE);
  1022. do
  1023. choices[n] = choices[n + 1];
  1024. while (choices[n++] != AV_PIX_FMT_NONE);
  1025. }
  1026. av_freep(&choices);
  1027. return ret;
  1028. }
  1029. static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
  1030. {
  1031. FramePool *pool = avctx->internal->pool;
  1032. int i, ret;
  1033. switch (avctx->codec_type) {
  1034. case AVMEDIA_TYPE_VIDEO: {
  1035. uint8_t *data[4];
  1036. int linesize[4];
  1037. int size[4] = { 0 };
  1038. int w = frame->width;
  1039. int h = frame->height;
  1040. int tmpsize, unaligned;
  1041. if (pool->format == frame->format &&
  1042. pool->width == frame->width && pool->height == frame->height)
  1043. return 0;
  1044. avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
  1045. do {
  1046. // NOTE: do not align linesizes individually, this breaks e.g. assumptions
  1047. // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
  1048. ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
  1049. if (ret < 0)
  1050. return ret;
  1051. // increase alignment of w for next try (rhs gives the lowest bit set in w)
  1052. w += w & ~(w - 1);
  1053. unaligned = 0;
  1054. for (i = 0; i < 4; i++)
  1055. unaligned |= linesize[i] % pool->stride_align[i];
  1056. } while (unaligned);
  1057. tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
  1058. NULL, linesize);
  1059. if (tmpsize < 0)
  1060. return -1;
  1061. for (i = 0; i < 3 && data[i + 1]; i++)
  1062. size[i] = data[i + 1] - data[i];
  1063. size[i] = tmpsize - (data[i] - data[0]);
  1064. for (i = 0; i < 4; i++) {
  1065. av_buffer_pool_uninit(&pool->pools[i]);
  1066. pool->linesize[i] = linesize[i];
  1067. if (size[i]) {
  1068. pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
  1069. CONFIG_MEMORY_POISONING ?
  1070. NULL :
  1071. av_buffer_allocz);
  1072. if (!pool->pools[i]) {
  1073. ret = AVERROR(ENOMEM);
  1074. goto fail;
  1075. }
  1076. }
  1077. }
  1078. pool->format = frame->format;
  1079. pool->width = frame->width;
  1080. pool->height = frame->height;
  1081. break;
  1082. }
  1083. case AVMEDIA_TYPE_AUDIO: {
  1084. int ch = frame->channels; //av_get_channel_layout_nb_channels(frame->channel_layout);
  1085. int planar = av_sample_fmt_is_planar(frame->format);
  1086. int planes = planar ? ch : 1;
  1087. if (pool->format == frame->format && pool->planes == planes &&
  1088. pool->channels == ch && frame->nb_samples == pool->samples)
  1089. return 0;
  1090. av_buffer_pool_uninit(&pool->pools[0]);
  1091. ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
  1092. frame->nb_samples, frame->format, 0);
  1093. if (ret < 0)
  1094. goto fail;
  1095. pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
  1096. if (!pool->pools[0]) {
  1097. ret = AVERROR(ENOMEM);
  1098. goto fail;
  1099. }
  1100. pool->format = frame->format;
  1101. pool->planes = planes;
  1102. pool->channels = ch;
  1103. pool->samples = frame->nb_samples;
  1104. break;
  1105. }
  1106. default: av_assert0(0);
  1107. }
  1108. return 0;
  1109. fail:
  1110. for (i = 0; i < 4; i++)
  1111. av_buffer_pool_uninit(&pool->pools[i]);
  1112. pool->format = -1;
  1113. pool->planes = pool->channels = pool->samples = 0;
  1114. pool->width = pool->height = 0;
  1115. return ret;
  1116. }
  1117. static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
  1118. {
  1119. FramePool *pool = avctx->internal->pool;
  1120. int planes = pool->planes;
  1121. int i;
  1122. frame->linesize[0] = pool->linesize[0];
  1123. if (planes > AV_NUM_DATA_POINTERS) {
  1124. frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
  1125. frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
  1126. frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
  1127. sizeof(*frame->extended_buf));
  1128. if (!frame->extended_data || !frame->extended_buf) {
  1129. av_freep(&frame->extended_data);
  1130. av_freep(&frame->extended_buf);
  1131. return AVERROR(ENOMEM);
  1132. }
  1133. } else {
  1134. frame->extended_data = frame->data;
  1135. av_assert0(frame->nb_extended_buf == 0);
  1136. }
  1137. for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
  1138. frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
  1139. if (!frame->buf[i])
  1140. goto fail;
  1141. frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
  1142. }
  1143. for (i = 0; i < frame->nb_extended_buf; i++) {
  1144. frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
  1145. if (!frame->extended_buf[i])
  1146. goto fail;
  1147. frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
  1148. }
  1149. if (avctx->debug & FF_DEBUG_BUFFERS)
  1150. av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
  1151. return 0;
  1152. fail:
  1153. av_frame_unref(frame);
  1154. return AVERROR(ENOMEM);
  1155. }
  1156. static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
  1157. {
  1158. FramePool *pool = s->internal->pool;
  1159. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
  1160. int i;
  1161. if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
  1162. av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
  1163. return -1;
  1164. }
  1165. if (!desc) {
  1166. av_log(s, AV_LOG_ERROR,
  1167. "Unable to get pixel format descriptor for format %s\n",
  1168. av_get_pix_fmt_name(pic->format));
  1169. return AVERROR(EINVAL);
  1170. }
  1171. memset(pic->data, 0, sizeof(pic->data));
  1172. pic->extended_data = pic->data;
  1173. for (i = 0; i < 4 && pool->pools[i]; i++) {
  1174. pic->linesize[i] = pool->linesize[i];
  1175. pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
  1176. if (!pic->buf[i])
  1177. goto fail;
  1178. pic->data[i] = pic->buf[i]->data;
  1179. }
  1180. for (; i < AV_NUM_DATA_POINTERS; i++) {
  1181. pic->data[i] = NULL;
  1182. pic->linesize[i] = 0;
  1183. }
  1184. if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
  1185. desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)
  1186. avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
  1187. if (s->debug & FF_DEBUG_BUFFERS)
  1188. av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
  1189. return 0;
  1190. fail:
  1191. av_frame_unref(pic);
  1192. return AVERROR(ENOMEM);
  1193. }
  1194. int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
  1195. {
  1196. int ret;
  1197. if (avctx->hw_frames_ctx)
  1198. return av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
  1199. if ((ret = update_frame_pool(avctx, frame)) < 0)
  1200. return ret;
  1201. switch (avctx->codec_type) {
  1202. case AVMEDIA_TYPE_VIDEO:
  1203. return video_get_buffer(avctx, frame);
  1204. case AVMEDIA_TYPE_AUDIO:
  1205. return audio_get_buffer(avctx, frame);
  1206. default:
  1207. return -1;
  1208. }
  1209. }
  1210. static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
  1211. {
  1212. int size;
  1213. const uint8_t *side_metadata;
  1214. AVDictionary **frame_md = &frame->metadata;
  1215. side_metadata = av_packet_get_side_data(avpkt,
  1216. AV_PKT_DATA_STRINGS_METADATA, &size);
  1217. return av_packet_unpack_dictionary(side_metadata, size, frame_md);
  1218. }
  1219. int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
  1220. {
  1221. const AVPacket *pkt = avctx->internal->last_pkt_props;
  1222. int i;
  1223. static const struct {
  1224. enum AVPacketSideDataType packet;
  1225. enum AVFrameSideDataType frame;
  1226. } sd[] = {
  1227. { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
  1228. { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
  1229. { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
  1230. { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
  1231. { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
  1232. { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
  1233. { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
  1234. };
  1235. if (pkt) {
  1236. frame->pts = pkt->pts;
  1237. #if FF_API_PKT_PTS
  1238. FF_DISABLE_DEPRECATION_WARNINGS
  1239. frame->pkt_pts = pkt->pts;
  1240. FF_ENABLE_DEPRECATION_WARNINGS
  1241. #endif
  1242. frame->pkt_pos = pkt->pos;
  1243. frame->pkt_duration = pkt->duration;
  1244. frame->pkt_size = pkt->size;
  1245. for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
  1246. int size;
  1247. uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
  1248. if (packet_sd) {
  1249. AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
  1250. sd[i].frame,
  1251. size);
  1252. if (!frame_sd)
  1253. return AVERROR(ENOMEM);
  1254. memcpy(frame_sd->data, packet_sd, size);
  1255. }
  1256. }
  1257. add_metadata_from_side_data(pkt, frame);
  1258. if (pkt->flags & AV_PKT_FLAG_DISCARD) {
  1259. frame->flags |= AV_FRAME_FLAG_DISCARD;
  1260. } else {
  1261. frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
  1262. }
  1263. }
  1264. frame->reordered_opaque = avctx->reordered_opaque;
  1265. if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
  1266. frame->color_primaries = avctx->color_primaries;
  1267. if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
  1268. frame->color_trc = avctx->color_trc;
  1269. if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
  1270. frame->colorspace = avctx->colorspace;
  1271. if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
  1272. frame->color_range = avctx->color_range;
  1273. if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
  1274. frame->chroma_location = avctx->chroma_sample_location;
  1275. switch (avctx->codec->type) {
  1276. case AVMEDIA_TYPE_VIDEO:
  1277. frame->format = avctx->pix_fmt;
  1278. if (!frame->sample_aspect_ratio.num)
  1279. frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
  1280. if (frame->width && frame->height &&
  1281. av_image_check_sar(frame->width, frame->height,
  1282. frame->sample_aspect_ratio) < 0) {
  1283. av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
  1284. frame->sample_aspect_ratio.num,
  1285. frame->sample_aspect_ratio.den);
  1286. frame->sample_aspect_ratio = (AVRational){ 0, 1 };
  1287. }
  1288. break;
  1289. case AVMEDIA_TYPE_AUDIO:
  1290. if (!frame->sample_rate)
  1291. frame->sample_rate = avctx->sample_rate;
  1292. if (frame->format < 0)
  1293. frame->format = avctx->sample_fmt;
  1294. if (!frame->channel_layout) {
  1295. if (avctx->channel_layout) {
  1296. if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
  1297. avctx->channels) {
  1298. av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
  1299. "configuration.\n");
  1300. return AVERROR(EINVAL);
  1301. }
  1302. frame->channel_layout = avctx->channel_layout;
  1303. } else {
  1304. if (avctx->channels > FF_SANE_NB_CHANNELS) {
  1305. av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
  1306. avctx->channels);
  1307. return AVERROR(ENOSYS);
  1308. }
  1309. }
  1310. }
  1311. frame->channels = avctx->channels;
  1312. break;
  1313. }
  1314. return 0;
  1315. }
  1316. int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
  1317. {
  1318. return ff_init_buffer_info(avctx, frame);
  1319. }
  1320. static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
  1321. {
  1322. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  1323. int i;
  1324. int num_planes = av_pix_fmt_count_planes(frame->format);
  1325. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
  1326. int flags = desc ? desc->flags : 0;
  1327. if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
  1328. num_planes = 2;
  1329. for (i = 0; i < num_planes; i++) {
  1330. av_assert0(frame->data[i]);
  1331. }
  1332. // For now do not enforce anything for palette of pseudopal formats
  1333. if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PSEUDOPAL))
  1334. num_planes = 2;
  1335. // For formats without data like hwaccel allow unused pointers to be non-NULL.
  1336. for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
  1337. if (frame->data[i])
  1338. av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
  1339. frame->data[i] = NULL;
  1340. }
  1341. }
  1342. }
  1343. static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
  1344. {
  1345. const AVHWAccel *hwaccel = avctx->hwaccel;
  1346. int override_dimensions = 1;
  1347. int ret;
  1348. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  1349. if ((ret = av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
  1350. av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
  1351. return AVERROR(EINVAL);
  1352. }
  1353. if (frame->width <= 0 || frame->height <= 0) {
  1354. frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
  1355. frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
  1356. override_dimensions = 0;
  1357. }
  1358. if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
  1359. av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
  1360. return AVERROR(EINVAL);
  1361. }
  1362. }
  1363. ret = ff_decode_frame_props(avctx, frame);
  1364. if (ret < 0)
  1365. return ret;
  1366. if (hwaccel) {
  1367. if (hwaccel->alloc_frame) {
  1368. ret = hwaccel->alloc_frame(avctx, frame);
  1369. goto end;
  1370. }
  1371. } else
  1372. avctx->sw_pix_fmt = avctx->pix_fmt;
  1373. ret = avctx->get_buffer2(avctx, frame, flags);
  1374. if (ret >= 0)
  1375. validate_avframe_allocation(avctx, frame);
  1376. end:
  1377. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions) {
  1378. frame->width = avctx->width;
  1379. frame->height = avctx->height;
  1380. }
  1381. return ret;
  1382. }
  1383. int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
  1384. {
  1385. int ret = get_buffer_internal(avctx, frame, flags);
  1386. if (ret < 0) {
  1387. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  1388. frame->width = frame->height = 0;
  1389. }
  1390. return ret;
  1391. }
  1392. static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
  1393. {
  1394. AVFrame *tmp;
  1395. int ret;
  1396. av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
  1397. if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
  1398. av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
  1399. frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
  1400. av_frame_unref(frame);
  1401. }
  1402. ff_init_buffer_info(avctx, frame);
  1403. if (!frame->data[0])
  1404. return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
  1405. if (av_frame_is_writable(frame))
  1406. return ff_decode_frame_props(avctx, frame);
  1407. tmp = av_frame_alloc();
  1408. if (!tmp)
  1409. return AVERROR(ENOMEM);
  1410. av_frame_move_ref(tmp, frame);
  1411. ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
  1412. if (ret < 0) {
  1413. av_frame_free(&tmp);
  1414. return ret;
  1415. }
  1416. av_frame_copy(frame, tmp);
  1417. av_frame_free(&tmp);
  1418. return 0;
  1419. }
  1420. int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
  1421. {
  1422. int ret = reget_buffer_internal(avctx, frame);
  1423. if (ret < 0)
  1424. av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
  1425. return ret;
  1426. }
  1427. void avcodec_flush_buffers(AVCodecContext *avctx)
  1428. {
  1429. avctx->internal->draining = 0;
  1430. avctx->internal->draining_done = 0;
  1431. avctx->internal->nb_draining_errors = 0;
  1432. av_frame_unref(avctx->internal->buffer_frame);
  1433. av_frame_unref(avctx->internal->compat_decode_frame);
  1434. av_packet_unref(avctx->internal->buffer_pkt);
  1435. avctx->internal->buffer_pkt_valid = 0;
  1436. av_packet_unref(avctx->internal->ds.in_pkt);
  1437. if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
  1438. ff_thread_flush(avctx);
  1439. else if (avctx->codec->flush)
  1440. avctx->codec->flush(avctx);
  1441. avctx->pts_correction_last_pts =
  1442. avctx->pts_correction_last_dts = INT64_MIN;
  1443. ff_decode_bsfs_uninit(avctx);
  1444. if (!avctx->refcounted_frames)
  1445. av_frame_unref(avctx->internal->to_free);
  1446. }
  1447. void ff_decode_bsfs_uninit(AVCodecContext *avctx)
  1448. {
  1449. DecodeFilterContext *s = &avctx->internal->filter;
  1450. int i;
  1451. for (i = 0; i < s->nb_bsfs; i++)
  1452. av_bsf_free(&s->bsfs[i]);
  1453. av_freep(&s->bsfs);
  1454. s->nb_bsfs = 0;
  1455. }