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.

1692 lines
54KB

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