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.

1756 lines
57KB

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