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.

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