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.

1710 lines
55KB

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