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.

1563 lines
52KB

  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/bprint.h"
  28. #include "libavutil/common.h"
  29. #include "libavutil/frame.h"
  30. #include "libavutil/hwcontext.h"
  31. #include "libavutil/imgutils.h"
  32. #include "libavutil/internal.h"
  33. #include "avcodec.h"
  34. #include "bytestream.h"
  35. #include "internal.h"
  36. #include "thread.h"
  37. static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
  38. {
  39. int size = 0, ret;
  40. const uint8_t *data;
  41. uint32_t flags;
  42. int64_t val;
  43. data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
  44. if (!data)
  45. return 0;
  46. if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
  47. av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
  48. "changes, but PARAM_CHANGE side data was sent to it.\n");
  49. ret = AVERROR(EINVAL);
  50. goto fail2;
  51. }
  52. if (size < 4)
  53. goto fail;
  54. flags = bytestream_get_le32(&data);
  55. size -= 4;
  56. if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
  57. if (size < 4)
  58. goto fail;
  59. val = bytestream_get_le32(&data);
  60. if (val <= 0 || val > INT_MAX) {
  61. av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
  62. ret = AVERROR_INVALIDDATA;
  63. goto fail2;
  64. }
  65. avctx->channels = val;
  66. size -= 4;
  67. }
  68. if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
  69. if (size < 8)
  70. goto fail;
  71. avctx->channel_layout = bytestream_get_le64(&data);
  72. size -= 8;
  73. }
  74. if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
  75. if (size < 4)
  76. goto fail;
  77. val = bytestream_get_le32(&data);
  78. if (val <= 0 || val > INT_MAX) {
  79. av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
  80. ret = AVERROR_INVALIDDATA;
  81. goto fail2;
  82. }
  83. avctx->sample_rate = val;
  84. size -= 4;
  85. }
  86. if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
  87. if (size < 8)
  88. goto fail;
  89. avctx->width = bytestream_get_le32(&data);
  90. avctx->height = bytestream_get_le32(&data);
  91. size -= 8;
  92. ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
  93. if (ret < 0)
  94. goto fail2;
  95. }
  96. return 0;
  97. fail:
  98. av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
  99. ret = AVERROR_INVALIDDATA;
  100. fail2:
  101. if (ret < 0) {
  102. av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
  103. if (avctx->err_recognition & AV_EF_EXPLODE)
  104. return ret;
  105. }
  106. return 0;
  107. }
  108. static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
  109. {
  110. int ret;
  111. /* move the original frame to our backup */
  112. av_frame_unref(avci->to_free);
  113. av_frame_move_ref(avci->to_free, frame);
  114. /* now copy everything except the AVBufferRefs back
  115. * note that we make a COPY of the side data, so calling av_frame_free() on
  116. * the caller's frame will work properly */
  117. ret = av_frame_copy_props(frame, avci->to_free);
  118. if (ret < 0)
  119. return ret;
  120. memcpy(frame->data, avci->to_free->data, sizeof(frame->data));
  121. memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
  122. if (avci->to_free->extended_data != avci->to_free->data) {
  123. int planes = av_frame_get_channels(avci->to_free);
  124. int size = planes * sizeof(*frame->extended_data);
  125. if (!size) {
  126. av_frame_unref(frame);
  127. return AVERROR_BUG;
  128. }
  129. frame->extended_data = av_malloc(size);
  130. if (!frame->extended_data) {
  131. av_frame_unref(frame);
  132. return AVERROR(ENOMEM);
  133. }
  134. memcpy(frame->extended_data, avci->to_free->extended_data,
  135. size);
  136. } else
  137. frame->extended_data = frame->data;
  138. frame->format = avci->to_free->format;
  139. frame->width = avci->to_free->width;
  140. frame->height = avci->to_free->height;
  141. frame->channel_layout = avci->to_free->channel_layout;
  142. frame->nb_samples = avci->to_free->nb_samples;
  143. av_frame_set_channels(frame, av_frame_get_channels(avci->to_free));
  144. return 0;
  145. }
  146. /**
  147. * Attempt to guess proper monotonic timestamps for decoded video frames
  148. * which might have incorrect times. Input timestamps may wrap around, in
  149. * which case the output will as well.
  150. *
  151. * @param pts the pts field of the decoded AVPacket, as passed through
  152. * AVFrame.pts
  153. * @param dts the dts field of the decoded AVPacket
  154. * @return one of the input values, may be AV_NOPTS_VALUE
  155. */
  156. static int64_t guess_correct_pts(AVCodecContext *ctx,
  157. int64_t reordered_pts, int64_t dts)
  158. {
  159. int64_t pts = AV_NOPTS_VALUE;
  160. if (dts != AV_NOPTS_VALUE) {
  161. ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
  162. ctx->pts_correction_last_dts = dts;
  163. } else if (reordered_pts != AV_NOPTS_VALUE)
  164. ctx->pts_correction_last_dts = reordered_pts;
  165. if (reordered_pts != AV_NOPTS_VALUE) {
  166. ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
  167. ctx->pts_correction_last_pts = reordered_pts;
  168. } else if(dts != AV_NOPTS_VALUE)
  169. ctx->pts_correction_last_pts = dts;
  170. if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
  171. && reordered_pts != AV_NOPTS_VALUE)
  172. pts = reordered_pts;
  173. else
  174. pts = dts;
  175. return pts;
  176. }
  177. static int do_decode(AVCodecContext *avctx, AVPacket *pkt)
  178. {
  179. int got_frame = 0;
  180. int ret;
  181. av_assert0(!avctx->internal->buffer_frame->buf[0]);
  182. if (!pkt)
  183. pkt = avctx->internal->buffer_pkt;
  184. // This is the lesser evil. The field is for compatibility with legacy users
  185. // of the legacy API, and users using the new API should not be forced to
  186. // even know about this field.
  187. avctx->refcounted_frames = 1;
  188. // Some codecs (at least wma lossless) will crash when feeding drain packets
  189. // after EOF was signaled.
  190. if (avctx->internal->draining_done)
  191. return AVERROR_EOF;
  192. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  193. ret = avcodec_decode_video2(avctx, avctx->internal->buffer_frame,
  194. &got_frame, pkt);
  195. if (ret >= 0 && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
  196. ret = pkt->size;
  197. } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  198. ret = avcodec_decode_audio4(avctx, avctx->internal->buffer_frame,
  199. &got_frame, pkt);
  200. } else {
  201. ret = AVERROR(EINVAL);
  202. }
  203. if (ret == AVERROR(EAGAIN))
  204. ret = pkt->size;
  205. if (avctx->internal->draining && !got_frame)
  206. avctx->internal->draining_done = 1;
  207. if (ret < 0)
  208. return ret;
  209. if (ret >= pkt->size) {
  210. av_packet_unref(avctx->internal->buffer_pkt);
  211. } else {
  212. int consumed = ret;
  213. if (pkt != avctx->internal->buffer_pkt) {
  214. av_packet_unref(avctx->internal->buffer_pkt);
  215. if ((ret = av_packet_ref(avctx->internal->buffer_pkt, pkt)) < 0)
  216. return ret;
  217. }
  218. avctx->internal->buffer_pkt->data += consumed;
  219. avctx->internal->buffer_pkt->size -= consumed;
  220. avctx->internal->buffer_pkt->pts = AV_NOPTS_VALUE;
  221. avctx->internal->buffer_pkt->dts = AV_NOPTS_VALUE;
  222. }
  223. if (got_frame)
  224. av_assert0(avctx->internal->buffer_frame->buf[0]);
  225. return 0;
  226. }
  227. int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
  228. {
  229. int ret;
  230. if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
  231. return AVERROR(EINVAL);
  232. if (avctx->internal->draining)
  233. return AVERROR_EOF;
  234. if (avpkt && !avpkt->size && avpkt->data)
  235. return AVERROR(EINVAL);
  236. if (!avpkt || !avpkt->size) {
  237. avctx->internal->draining = 1;
  238. avpkt = NULL;
  239. if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
  240. return 0;
  241. }
  242. if (avctx->codec->send_packet) {
  243. if (avpkt) {
  244. AVPacket tmp = *avpkt;
  245. #if FF_API_MERGE_SD
  246. FF_DISABLE_DEPRECATION_WARNINGS
  247. int did_split = av_packet_split_side_data(&tmp);
  248. FF_ENABLE_DEPRECATION_WARNINGS
  249. #endif
  250. ret = apply_param_change(avctx, &tmp);
  251. if (ret >= 0)
  252. ret = avctx->codec->send_packet(avctx, &tmp);
  253. #if FF_API_MERGE_SD
  254. if (did_split)
  255. av_packet_free_side_data(&tmp);
  256. #endif
  257. return ret;
  258. } else {
  259. return avctx->codec->send_packet(avctx, NULL);
  260. }
  261. }
  262. // Emulation via old API. Assume avpkt is likely not refcounted, while
  263. // decoder output is always refcounted, and avoid copying.
  264. if (avctx->internal->buffer_pkt->size || avctx->internal->buffer_frame->buf[0])
  265. return AVERROR(EAGAIN);
  266. // The goal is decoding the first frame of the packet without using memcpy,
  267. // because the common case is having only 1 frame per packet (especially
  268. // with video, but audio too). In other cases, it can't be avoided, unless
  269. // the user is feeding refcounted packets.
  270. return do_decode(avctx, (AVPacket *)avpkt);
  271. }
  272. int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
  273. {
  274. int ret;
  275. av_frame_unref(frame);
  276. if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
  277. return AVERROR(EINVAL);
  278. if (avctx->codec->receive_frame) {
  279. if (avctx->internal->draining && !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
  280. return AVERROR_EOF;
  281. ret = avctx->codec->receive_frame(avctx, frame);
  282. if (ret >= 0) {
  283. if (av_frame_get_best_effort_timestamp(frame) == AV_NOPTS_VALUE) {
  284. av_frame_set_best_effort_timestamp(frame,
  285. guess_correct_pts(avctx, frame->pts, frame->pkt_dts));
  286. }
  287. }
  288. return ret;
  289. }
  290. // Emulation via old API.
  291. if (!avctx->internal->buffer_frame->buf[0]) {
  292. if (!avctx->internal->buffer_pkt->size && !avctx->internal->draining)
  293. return AVERROR(EAGAIN);
  294. while (1) {
  295. if ((ret = do_decode(avctx, avctx->internal->buffer_pkt)) < 0) {
  296. av_packet_unref(avctx->internal->buffer_pkt);
  297. return ret;
  298. }
  299. // Some audio decoders may consume partial data without returning
  300. // a frame (fate-wmapro-2ch). There is no way to make the caller
  301. // call avcodec_receive_frame() again without returning a frame,
  302. // so try to decode more in these cases.
  303. if (avctx->internal->buffer_frame->buf[0] ||
  304. !avctx->internal->buffer_pkt->size)
  305. break;
  306. }
  307. }
  308. if (!avctx->internal->buffer_frame->buf[0])
  309. return avctx->internal->draining ? AVERROR_EOF : AVERROR(EAGAIN);
  310. av_frame_move_ref(frame, avctx->internal->buffer_frame);
  311. return 0;
  312. }
  313. int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
  314. int *got_picture_ptr,
  315. const AVPacket *avpkt)
  316. {
  317. AVCodecInternal *avci = avctx->internal;
  318. int ret;
  319. // copy to ensure we do not change avpkt
  320. AVPacket tmp = *avpkt;
  321. if (!avctx->codec)
  322. return AVERROR(EINVAL);
  323. if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) {
  324. av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n");
  325. return AVERROR(EINVAL);
  326. }
  327. if (!avctx->codec->decode) {
  328. av_log(avctx, AV_LOG_ERROR, "This decoder requires using the avcodec_send_packet() API.\n");
  329. return AVERROR(ENOSYS);
  330. }
  331. *got_picture_ptr = 0;
  332. if ((avctx->coded_width || avctx->coded_height) && av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx))
  333. return AVERROR(EINVAL);
  334. avctx->internal->pkt = avpkt;
  335. ret = apply_param_change(avctx, avpkt);
  336. if (ret < 0)
  337. return ret;
  338. av_frame_unref(picture);
  339. if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size ||
  340. (avctx->active_thread_type & FF_THREAD_FRAME)) {
  341. #if FF_API_MERGE_SD
  342. FF_DISABLE_DEPRECATION_WARNINGS
  343. int did_split = av_packet_split_side_data(&tmp);
  344. FF_ENABLE_DEPRECATION_WARNINGS
  345. #endif
  346. ret = apply_param_change(avctx, &tmp);
  347. if (ret < 0)
  348. goto fail;
  349. avctx->internal->pkt = &tmp;
  350. if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
  351. ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
  352. &tmp);
  353. else {
  354. ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
  355. &tmp);
  356. if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
  357. picture->pkt_dts = avpkt->dts;
  358. if(!avctx->has_b_frames){
  359. av_frame_set_pkt_pos(picture, avpkt->pos);
  360. }
  361. //FIXME these should be under if(!avctx->has_b_frames)
  362. /* get_buffer is supposed to set frame parameters */
  363. if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
  364. if (!picture->sample_aspect_ratio.num) picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
  365. if (!picture->width) picture->width = avctx->width;
  366. if (!picture->height) picture->height = avctx->height;
  367. if (picture->format == AV_PIX_FMT_NONE) picture->format = avctx->pix_fmt;
  368. }
  369. }
  370. fail:
  371. emms_c(); //needed to avoid an emms_c() call before every return;
  372. avctx->internal->pkt = NULL;
  373. #if FF_API_MERGE_SD
  374. if (did_split) {
  375. av_packet_free_side_data(&tmp);
  376. if(ret == tmp.size)
  377. ret = avpkt->size;
  378. }
  379. #endif
  380. if (picture->flags & AV_FRAME_FLAG_DISCARD) {
  381. *got_picture_ptr = 0;
  382. }
  383. if (*got_picture_ptr) {
  384. if (!avctx->refcounted_frames) {
  385. int err = unrefcount_frame(avci, picture);
  386. if (err < 0)
  387. return err;
  388. }
  389. avctx->frame_number++;
  390. av_frame_set_best_effort_timestamp(picture,
  391. guess_correct_pts(avctx,
  392. picture->pts,
  393. picture->pkt_dts));
  394. } else
  395. av_frame_unref(picture);
  396. } else
  397. ret = 0;
  398. /* many decoders assign whole AVFrames, thus overwriting extended_data;
  399. * make sure it's set correctly */
  400. av_assert0(!picture->extended_data || picture->extended_data == picture->data);
  401. #if FF_API_AVCTX_TIMEBASE
  402. if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
  403. avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
  404. #endif
  405. return ret;
  406. }
  407. int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
  408. AVFrame *frame,
  409. int *got_frame_ptr,
  410. const AVPacket *avpkt)
  411. {
  412. AVCodecInternal *avci = avctx->internal;
  413. int ret = 0;
  414. *got_frame_ptr = 0;
  415. if (!avctx->codec)
  416. return AVERROR(EINVAL);
  417. if (!avctx->codec->decode) {
  418. av_log(avctx, AV_LOG_ERROR, "This decoder requires using the avcodec_send_packet() API.\n");
  419. return AVERROR(ENOSYS);
  420. }
  421. if (!avpkt->data && avpkt->size) {
  422. av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
  423. return AVERROR(EINVAL);
  424. }
  425. if (avctx->codec->type != AVMEDIA_TYPE_AUDIO) {
  426. av_log(avctx, AV_LOG_ERROR, "Invalid media type for audio\n");
  427. return AVERROR(EINVAL);
  428. }
  429. av_frame_unref(frame);
  430. if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
  431. uint8_t *side;
  432. int side_size;
  433. uint32_t discard_padding = 0;
  434. uint8_t skip_reason = 0;
  435. uint8_t discard_reason = 0;
  436. // copy to ensure we do not change avpkt
  437. AVPacket tmp = *avpkt;
  438. #if FF_API_MERGE_SD
  439. FF_DISABLE_DEPRECATION_WARNINGS
  440. int did_split = av_packet_split_side_data(&tmp);
  441. FF_ENABLE_DEPRECATION_WARNINGS
  442. #endif
  443. ret = apply_param_change(avctx, &tmp);
  444. if (ret < 0)
  445. goto fail;
  446. avctx->internal->pkt = &tmp;
  447. if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
  448. ret = ff_thread_decode_frame(avctx, frame, got_frame_ptr, &tmp);
  449. else {
  450. ret = avctx->codec->decode(avctx, frame, got_frame_ptr, &tmp);
  451. av_assert0(ret <= tmp.size);
  452. frame->pkt_dts = avpkt->dts;
  453. }
  454. if (ret >= 0 && *got_frame_ptr) {
  455. avctx->frame_number++;
  456. av_frame_set_best_effort_timestamp(frame,
  457. guess_correct_pts(avctx,
  458. frame->pts,
  459. frame->pkt_dts));
  460. if (frame->format == AV_SAMPLE_FMT_NONE)
  461. frame->format = avctx->sample_fmt;
  462. if (!frame->channel_layout)
  463. frame->channel_layout = avctx->channel_layout;
  464. if (!av_frame_get_channels(frame))
  465. av_frame_set_channels(frame, avctx->channels);
  466. if (!frame->sample_rate)
  467. frame->sample_rate = avctx->sample_rate;
  468. }
  469. side= av_packet_get_side_data(avctx->internal->pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
  470. if(side && side_size>=10) {
  471. avctx->internal->skip_samples = AV_RL32(side) * avctx->internal->skip_samples_multiplier;
  472. discard_padding = AV_RL32(side + 4);
  473. av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
  474. avctx->internal->skip_samples, (int)discard_padding);
  475. skip_reason = AV_RL8(side + 8);
  476. discard_reason = AV_RL8(side + 9);
  477. }
  478. if ((frame->flags & AV_FRAME_FLAG_DISCARD) && *got_frame_ptr &&
  479. !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
  480. avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples);
  481. *got_frame_ptr = 0;
  482. }
  483. if (avctx->internal->skip_samples > 0 && *got_frame_ptr &&
  484. !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
  485. if(frame->nb_samples <= avctx->internal->skip_samples){
  486. *got_frame_ptr = 0;
  487. avctx->internal->skip_samples -= frame->nb_samples;
  488. av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
  489. avctx->internal->skip_samples);
  490. } else {
  491. av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
  492. frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
  493. if(avctx->pkt_timebase.num && avctx->sample_rate) {
  494. int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
  495. (AVRational){1, avctx->sample_rate},
  496. avctx->pkt_timebase);
  497. if(frame->pts!=AV_NOPTS_VALUE)
  498. frame->pts += diff_ts;
  499. #if FF_API_PKT_PTS
  500. FF_DISABLE_DEPRECATION_WARNINGS
  501. if(frame->pkt_pts!=AV_NOPTS_VALUE)
  502. frame->pkt_pts += diff_ts;
  503. FF_ENABLE_DEPRECATION_WARNINGS
  504. #endif
  505. if(frame->pkt_dts!=AV_NOPTS_VALUE)
  506. frame->pkt_dts += diff_ts;
  507. if (av_frame_get_pkt_duration(frame) >= diff_ts)
  508. av_frame_set_pkt_duration(frame, av_frame_get_pkt_duration(frame) - diff_ts);
  509. } else {
  510. av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
  511. }
  512. av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
  513. avctx->internal->skip_samples, frame->nb_samples);
  514. frame->nb_samples -= avctx->internal->skip_samples;
  515. avctx->internal->skip_samples = 0;
  516. }
  517. }
  518. if (discard_padding > 0 && discard_padding <= frame->nb_samples && *got_frame_ptr &&
  519. !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
  520. if (discard_padding == frame->nb_samples) {
  521. *got_frame_ptr = 0;
  522. } else {
  523. if(avctx->pkt_timebase.num && avctx->sample_rate) {
  524. int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
  525. (AVRational){1, avctx->sample_rate},
  526. avctx->pkt_timebase);
  527. av_frame_set_pkt_duration(frame, diff_ts);
  528. } else {
  529. av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
  530. }
  531. av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
  532. (int)discard_padding, frame->nb_samples);
  533. frame->nb_samples -= discard_padding;
  534. }
  535. }
  536. if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && *got_frame_ptr) {
  537. AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
  538. if (fside) {
  539. AV_WL32(fside->data, avctx->internal->skip_samples);
  540. AV_WL32(fside->data + 4, discard_padding);
  541. AV_WL8(fside->data + 8, skip_reason);
  542. AV_WL8(fside->data + 9, discard_reason);
  543. avctx->internal->skip_samples = 0;
  544. }
  545. }
  546. fail:
  547. avctx->internal->pkt = NULL;
  548. #if FF_API_MERGE_SD
  549. if (did_split) {
  550. av_packet_free_side_data(&tmp);
  551. if(ret == tmp.size)
  552. ret = avpkt->size;
  553. }
  554. #endif
  555. if (ret >= 0 && *got_frame_ptr) {
  556. if (!avctx->refcounted_frames) {
  557. int err = unrefcount_frame(avci, frame);
  558. if (err < 0)
  559. return err;
  560. }
  561. } else
  562. av_frame_unref(frame);
  563. }
  564. av_assert0(ret <= avpkt->size);
  565. if (!avci->showed_multi_packet_warning &&
  566. ret >= 0 && ret != avpkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
  567. av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
  568. avci->showed_multi_packet_warning = 1;
  569. }
  570. return ret;
  571. }
  572. static void get_subtitle_defaults(AVSubtitle *sub)
  573. {
  574. memset(sub, 0, sizeof(*sub));
  575. sub->pts = AV_NOPTS_VALUE;
  576. }
  577. #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
  578. static int recode_subtitle(AVCodecContext *avctx,
  579. AVPacket *outpkt, const AVPacket *inpkt)
  580. {
  581. #if CONFIG_ICONV
  582. iconv_t cd = (iconv_t)-1;
  583. int ret = 0;
  584. char *inb, *outb;
  585. size_t inl, outl;
  586. AVPacket tmp;
  587. #endif
  588. if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
  589. return 0;
  590. #if CONFIG_ICONV
  591. cd = iconv_open("UTF-8", avctx->sub_charenc);
  592. av_assert0(cd != (iconv_t)-1);
  593. inb = inpkt->data;
  594. inl = inpkt->size;
  595. if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
  596. av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
  597. ret = AVERROR(ENOMEM);
  598. goto end;
  599. }
  600. ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
  601. if (ret < 0)
  602. goto end;
  603. outpkt->buf = tmp.buf;
  604. outpkt->data = tmp.data;
  605. outpkt->size = tmp.size;
  606. outb = outpkt->data;
  607. outl = outpkt->size;
  608. if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
  609. iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
  610. outl >= outpkt->size || inl != 0) {
  611. ret = FFMIN(AVERROR(errno), -1);
  612. av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
  613. "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
  614. av_packet_unref(&tmp);
  615. goto end;
  616. }
  617. outpkt->size -= outl;
  618. memset(outpkt->data + outpkt->size, 0, outl);
  619. end:
  620. if (cd != (iconv_t)-1)
  621. iconv_close(cd);
  622. return ret;
  623. #else
  624. av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
  625. return AVERROR(EINVAL);
  626. #endif
  627. }
  628. static int utf8_check(const uint8_t *str)
  629. {
  630. const uint8_t *byte;
  631. uint32_t codepoint, min;
  632. while (*str) {
  633. byte = str;
  634. GET_UTF8(codepoint, *(byte++), return 0;);
  635. min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
  636. 1 << (5 * (byte - str) - 4);
  637. if (codepoint < min || codepoint >= 0x110000 ||
  638. codepoint == 0xFFFE /* BOM */ ||
  639. codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
  640. return 0;
  641. str = byte;
  642. }
  643. return 1;
  644. }
  645. #if FF_API_ASS_TIMING
  646. static void insert_ts(AVBPrint *buf, int ts)
  647. {
  648. if (ts == -1) {
  649. av_bprintf(buf, "9:59:59.99,");
  650. } else {
  651. int h, m, s;
  652. h = ts/360000; ts -= 360000*h;
  653. m = ts/ 6000; ts -= 6000*m;
  654. s = ts/ 100; ts -= 100*s;
  655. av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
  656. }
  657. }
  658. static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
  659. {
  660. int i;
  661. AVBPrint buf;
  662. av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
  663. for (i = 0; i < sub->num_rects; i++) {
  664. char *final_dialog;
  665. const char *dialog;
  666. AVSubtitleRect *rect = sub->rects[i];
  667. int ts_start, ts_duration = -1;
  668. long int layer;
  669. if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
  670. continue;
  671. av_bprint_clear(&buf);
  672. /* skip ReadOrder */
  673. dialog = strchr(rect->ass, ',');
  674. if (!dialog)
  675. continue;
  676. dialog++;
  677. /* extract Layer or Marked */
  678. layer = strtol(dialog, (char**)&dialog, 10);
  679. if (*dialog != ',')
  680. continue;
  681. dialog++;
  682. /* rescale timing to ASS time base (ms) */
  683. ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
  684. if (pkt->duration != -1)
  685. ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
  686. sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
  687. /* construct ASS (standalone file form with timestamps) string */
  688. av_bprintf(&buf, "Dialogue: %ld,", layer);
  689. insert_ts(&buf, ts_start);
  690. insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
  691. av_bprintf(&buf, "%s\r\n", dialog);
  692. final_dialog = av_strdup(buf.str);
  693. if (!av_bprint_is_complete(&buf) || !final_dialog) {
  694. av_freep(&final_dialog);
  695. av_bprint_finalize(&buf, NULL);
  696. return AVERROR(ENOMEM);
  697. }
  698. av_freep(&rect->ass);
  699. rect->ass = final_dialog;
  700. }
  701. av_bprint_finalize(&buf, NULL);
  702. return 0;
  703. }
  704. #endif
  705. int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
  706. int *got_sub_ptr,
  707. AVPacket *avpkt)
  708. {
  709. int i, ret = 0;
  710. if (!avpkt->data && avpkt->size) {
  711. av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
  712. return AVERROR(EINVAL);
  713. }
  714. if (!avctx->codec)
  715. return AVERROR(EINVAL);
  716. if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
  717. av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
  718. return AVERROR(EINVAL);
  719. }
  720. *got_sub_ptr = 0;
  721. get_subtitle_defaults(sub);
  722. if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
  723. AVPacket pkt_recoded;
  724. AVPacket tmp = *avpkt;
  725. #if FF_API_MERGE_SD
  726. FF_DISABLE_DEPRECATION_WARNINGS
  727. int did_split = av_packet_split_side_data(&tmp);
  728. //apply_param_change(avctx, &tmp);
  729. if (did_split) {
  730. /* FFMIN() prevents overflow in case the packet wasn't allocated with
  731. * proper padding.
  732. * If the side data is smaller than the buffer padding size, the
  733. * remaining bytes should have already been filled with zeros by the
  734. * original packet allocation anyway. */
  735. memset(tmp.data + tmp.size, 0,
  736. FFMIN(avpkt->size - tmp.size, AV_INPUT_BUFFER_PADDING_SIZE));
  737. }
  738. FF_ENABLE_DEPRECATION_WARNINGS
  739. #endif
  740. pkt_recoded = tmp;
  741. ret = recode_subtitle(avctx, &pkt_recoded, &tmp);
  742. if (ret < 0) {
  743. *got_sub_ptr = 0;
  744. } else {
  745. avctx->internal->pkt = &pkt_recoded;
  746. if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
  747. sub->pts = av_rescale_q(avpkt->pts,
  748. avctx->pkt_timebase, AV_TIME_BASE_Q);
  749. ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
  750. av_assert1((ret >= 0) >= !!*got_sub_ptr &&
  751. !!*got_sub_ptr >= !!sub->num_rects);
  752. #if FF_API_ASS_TIMING
  753. if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
  754. && *got_sub_ptr && sub->num_rects) {
  755. const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
  756. : avctx->time_base;
  757. int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
  758. if (err < 0)
  759. ret = err;
  760. }
  761. #endif
  762. if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
  763. avctx->pkt_timebase.num) {
  764. AVRational ms = { 1, 1000 };
  765. sub->end_display_time = av_rescale_q(avpkt->duration,
  766. avctx->pkt_timebase, ms);
  767. }
  768. if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
  769. sub->format = 0;
  770. else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
  771. sub->format = 1;
  772. for (i = 0; i < sub->num_rects; i++) {
  773. if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
  774. av_log(avctx, AV_LOG_ERROR,
  775. "Invalid UTF-8 in decoded subtitles text; "
  776. "maybe missing -sub_charenc option\n");
  777. avsubtitle_free(sub);
  778. ret = AVERROR_INVALIDDATA;
  779. break;
  780. }
  781. }
  782. if (tmp.data != pkt_recoded.data) { // did we recode?
  783. /* prevent from destroying side data from original packet */
  784. pkt_recoded.side_data = NULL;
  785. pkt_recoded.side_data_elems = 0;
  786. av_packet_unref(&pkt_recoded);
  787. }
  788. avctx->internal->pkt = NULL;
  789. }
  790. #if FF_API_MERGE_SD
  791. if (did_split) {
  792. av_packet_free_side_data(&tmp);
  793. if(ret == tmp.size)
  794. ret = avpkt->size;
  795. }
  796. #endif
  797. if (*got_sub_ptr)
  798. avctx->frame_number++;
  799. }
  800. return ret;
  801. }
  802. static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
  803. {
  804. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
  805. return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
  806. }
  807. enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
  808. {
  809. while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
  810. ++fmt;
  811. return fmt[0];
  812. }
  813. static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
  814. enum AVPixelFormat pix_fmt)
  815. {
  816. AVHWAccel *hwaccel = NULL;
  817. while ((hwaccel = av_hwaccel_next(hwaccel)))
  818. if (hwaccel->id == codec_id
  819. && hwaccel->pix_fmt == pix_fmt)
  820. return hwaccel;
  821. return NULL;
  822. }
  823. static int setup_hwaccel(AVCodecContext *avctx,
  824. const enum AVPixelFormat fmt,
  825. const char *name)
  826. {
  827. AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
  828. int ret = 0;
  829. if (!hwa) {
  830. av_log(avctx, AV_LOG_ERROR,
  831. "Could not find an AVHWAccel for the pixel format: %s",
  832. name);
  833. return AVERROR(ENOENT);
  834. }
  835. if (hwa->capabilities & HWACCEL_CODEC_CAP_EXPERIMENTAL &&
  836. avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  837. av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
  838. hwa->name);
  839. return AVERROR_PATCHWELCOME;
  840. }
  841. if (hwa->priv_data_size) {
  842. avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
  843. if (!avctx->internal->hwaccel_priv_data)
  844. return AVERROR(ENOMEM);
  845. }
  846. if (hwa->init) {
  847. ret = hwa->init(avctx);
  848. if (ret < 0) {
  849. av_freep(&avctx->internal->hwaccel_priv_data);
  850. return ret;
  851. }
  852. }
  853. avctx->hwaccel = hwa;
  854. return 0;
  855. }
  856. int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
  857. {
  858. const AVPixFmtDescriptor *desc;
  859. enum AVPixelFormat *choices;
  860. enum AVPixelFormat ret;
  861. unsigned n = 0;
  862. while (fmt[n] != AV_PIX_FMT_NONE)
  863. ++n;
  864. av_assert0(n >= 1);
  865. avctx->sw_pix_fmt = fmt[n - 1];
  866. av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
  867. choices = av_malloc_array(n + 1, sizeof(*choices));
  868. if (!choices)
  869. return AV_PIX_FMT_NONE;
  870. memcpy(choices, fmt, (n + 1) * sizeof(*choices));
  871. for (;;) {
  872. if (avctx->hwaccel && avctx->hwaccel->uninit)
  873. avctx->hwaccel->uninit(avctx);
  874. av_freep(&avctx->internal->hwaccel_priv_data);
  875. avctx->hwaccel = NULL;
  876. av_buffer_unref(&avctx->hw_frames_ctx);
  877. ret = avctx->get_format(avctx, choices);
  878. desc = av_pix_fmt_desc_get(ret);
  879. if (!desc) {
  880. ret = AV_PIX_FMT_NONE;
  881. break;
  882. }
  883. if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
  884. break;
  885. #if FF_API_CAP_VDPAU
  886. if (avctx->codec->capabilities&AV_CODEC_CAP_HWACCEL_VDPAU)
  887. break;
  888. #endif
  889. if (avctx->hw_frames_ctx) {
  890. AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  891. if (hw_frames_ctx->format != ret) {
  892. av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() "
  893. "does not match the format of provided AVHWFramesContext\n");
  894. ret = AV_PIX_FMT_NONE;
  895. break;
  896. }
  897. }
  898. if (!setup_hwaccel(avctx, ret, desc->name))
  899. break;
  900. /* Remove failed hwaccel from choices */
  901. for (n = 0; choices[n] != ret; n++)
  902. av_assert0(choices[n] != AV_PIX_FMT_NONE);
  903. do
  904. choices[n] = choices[n + 1];
  905. while (choices[n++] != AV_PIX_FMT_NONE);
  906. }
  907. av_freep(&choices);
  908. return ret;
  909. }
  910. static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
  911. {
  912. FramePool *pool = avctx->internal->pool;
  913. int i, ret;
  914. switch (avctx->codec_type) {
  915. case AVMEDIA_TYPE_VIDEO: {
  916. uint8_t *data[4];
  917. int linesize[4];
  918. int size[4] = { 0 };
  919. int w = frame->width;
  920. int h = frame->height;
  921. int tmpsize, unaligned;
  922. if (pool->format == frame->format &&
  923. pool->width == frame->width && pool->height == frame->height)
  924. return 0;
  925. avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
  926. do {
  927. // NOTE: do not align linesizes individually, this breaks e.g. assumptions
  928. // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
  929. ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
  930. if (ret < 0)
  931. return ret;
  932. // increase alignment of w for next try (rhs gives the lowest bit set in w)
  933. w += w & ~(w - 1);
  934. unaligned = 0;
  935. for (i = 0; i < 4; i++)
  936. unaligned |= linesize[i] % pool->stride_align[i];
  937. } while (unaligned);
  938. tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
  939. NULL, linesize);
  940. if (tmpsize < 0)
  941. return -1;
  942. for (i = 0; i < 3 && data[i + 1]; i++)
  943. size[i] = data[i + 1] - data[i];
  944. size[i] = tmpsize - (data[i] - data[0]);
  945. for (i = 0; i < 4; i++) {
  946. av_buffer_pool_uninit(&pool->pools[i]);
  947. pool->linesize[i] = linesize[i];
  948. if (size[i]) {
  949. pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
  950. CONFIG_MEMORY_POISONING ?
  951. NULL :
  952. av_buffer_allocz);
  953. if (!pool->pools[i]) {
  954. ret = AVERROR(ENOMEM);
  955. goto fail;
  956. }
  957. }
  958. }
  959. pool->format = frame->format;
  960. pool->width = frame->width;
  961. pool->height = frame->height;
  962. break;
  963. }
  964. case AVMEDIA_TYPE_AUDIO: {
  965. int ch = av_frame_get_channels(frame); //av_get_channel_layout_nb_channels(frame->channel_layout);
  966. int planar = av_sample_fmt_is_planar(frame->format);
  967. int planes = planar ? ch : 1;
  968. if (pool->format == frame->format && pool->planes == planes &&
  969. pool->channels == ch && frame->nb_samples == pool->samples)
  970. return 0;
  971. av_buffer_pool_uninit(&pool->pools[0]);
  972. ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
  973. frame->nb_samples, frame->format, 0);
  974. if (ret < 0)
  975. goto fail;
  976. pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
  977. if (!pool->pools[0]) {
  978. ret = AVERROR(ENOMEM);
  979. goto fail;
  980. }
  981. pool->format = frame->format;
  982. pool->planes = planes;
  983. pool->channels = ch;
  984. pool->samples = frame->nb_samples;
  985. break;
  986. }
  987. default: av_assert0(0);
  988. }
  989. return 0;
  990. fail:
  991. for (i = 0; i < 4; i++)
  992. av_buffer_pool_uninit(&pool->pools[i]);
  993. pool->format = -1;
  994. pool->planes = pool->channels = pool->samples = 0;
  995. pool->width = pool->height = 0;
  996. return ret;
  997. }
  998. static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
  999. {
  1000. FramePool *pool = avctx->internal->pool;
  1001. int planes = pool->planes;
  1002. int i;
  1003. frame->linesize[0] = pool->linesize[0];
  1004. if (planes > AV_NUM_DATA_POINTERS) {
  1005. frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
  1006. frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
  1007. frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
  1008. sizeof(*frame->extended_buf));
  1009. if (!frame->extended_data || !frame->extended_buf) {
  1010. av_freep(&frame->extended_data);
  1011. av_freep(&frame->extended_buf);
  1012. return AVERROR(ENOMEM);
  1013. }
  1014. } else {
  1015. frame->extended_data = frame->data;
  1016. av_assert0(frame->nb_extended_buf == 0);
  1017. }
  1018. for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
  1019. frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
  1020. if (!frame->buf[i])
  1021. goto fail;
  1022. frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
  1023. }
  1024. for (i = 0; i < frame->nb_extended_buf; i++) {
  1025. frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
  1026. if (!frame->extended_buf[i])
  1027. goto fail;
  1028. frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
  1029. }
  1030. if (avctx->debug & FF_DEBUG_BUFFERS)
  1031. av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
  1032. return 0;
  1033. fail:
  1034. av_frame_unref(frame);
  1035. return AVERROR(ENOMEM);
  1036. }
  1037. static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
  1038. {
  1039. FramePool *pool = s->internal->pool;
  1040. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
  1041. int i;
  1042. if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
  1043. av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
  1044. return -1;
  1045. }
  1046. if (!desc) {
  1047. av_log(s, AV_LOG_ERROR,
  1048. "Unable to get pixel format descriptor for format %s\n",
  1049. av_get_pix_fmt_name(pic->format));
  1050. return AVERROR(EINVAL);
  1051. }
  1052. memset(pic->data, 0, sizeof(pic->data));
  1053. pic->extended_data = pic->data;
  1054. for (i = 0; i < 4 && pool->pools[i]; i++) {
  1055. pic->linesize[i] = pool->linesize[i];
  1056. pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
  1057. if (!pic->buf[i])
  1058. goto fail;
  1059. pic->data[i] = pic->buf[i]->data;
  1060. }
  1061. for (; i < AV_NUM_DATA_POINTERS; i++) {
  1062. pic->data[i] = NULL;
  1063. pic->linesize[i] = 0;
  1064. }
  1065. if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
  1066. desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)
  1067. avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
  1068. if (s->debug & FF_DEBUG_BUFFERS)
  1069. av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
  1070. return 0;
  1071. fail:
  1072. av_frame_unref(pic);
  1073. return AVERROR(ENOMEM);
  1074. }
  1075. int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
  1076. {
  1077. int ret;
  1078. if (avctx->hw_frames_ctx)
  1079. return av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
  1080. if ((ret = update_frame_pool(avctx, frame)) < 0)
  1081. return ret;
  1082. switch (avctx->codec_type) {
  1083. case AVMEDIA_TYPE_VIDEO:
  1084. return video_get_buffer(avctx, frame);
  1085. case AVMEDIA_TYPE_AUDIO:
  1086. return audio_get_buffer(avctx, frame);
  1087. default:
  1088. return -1;
  1089. }
  1090. }
  1091. static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
  1092. {
  1093. int size;
  1094. const uint8_t *side_metadata;
  1095. AVDictionary **frame_md = avpriv_frame_get_metadatap(frame);
  1096. side_metadata = av_packet_get_side_data(avpkt,
  1097. AV_PKT_DATA_STRINGS_METADATA, &size);
  1098. return av_packet_unpack_dictionary(side_metadata, size, frame_md);
  1099. }
  1100. int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
  1101. {
  1102. const AVPacket *pkt = avctx->internal->pkt;
  1103. int i;
  1104. static const struct {
  1105. enum AVPacketSideDataType packet;
  1106. enum AVFrameSideDataType frame;
  1107. } sd[] = {
  1108. { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
  1109. { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
  1110. { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
  1111. { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
  1112. { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
  1113. { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
  1114. { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
  1115. };
  1116. if (pkt) {
  1117. frame->pts = pkt->pts;
  1118. #if FF_API_PKT_PTS
  1119. FF_DISABLE_DEPRECATION_WARNINGS
  1120. frame->pkt_pts = pkt->pts;
  1121. FF_ENABLE_DEPRECATION_WARNINGS
  1122. #endif
  1123. av_frame_set_pkt_pos (frame, pkt->pos);
  1124. av_frame_set_pkt_duration(frame, pkt->duration);
  1125. av_frame_set_pkt_size (frame, pkt->size);
  1126. for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
  1127. int size;
  1128. uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
  1129. if (packet_sd) {
  1130. AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
  1131. sd[i].frame,
  1132. size);
  1133. if (!frame_sd)
  1134. return AVERROR(ENOMEM);
  1135. memcpy(frame_sd->data, packet_sd, size);
  1136. }
  1137. }
  1138. add_metadata_from_side_data(pkt, frame);
  1139. if (pkt->flags & AV_PKT_FLAG_DISCARD) {
  1140. frame->flags |= AV_FRAME_FLAG_DISCARD;
  1141. } else {
  1142. frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
  1143. }
  1144. } else {
  1145. frame->pts = AV_NOPTS_VALUE;
  1146. #if FF_API_PKT_PTS
  1147. FF_DISABLE_DEPRECATION_WARNINGS
  1148. frame->pkt_pts = AV_NOPTS_VALUE;
  1149. FF_ENABLE_DEPRECATION_WARNINGS
  1150. #endif
  1151. av_frame_set_pkt_pos (frame, -1);
  1152. av_frame_set_pkt_duration(frame, 0);
  1153. av_frame_set_pkt_size (frame, -1);
  1154. }
  1155. frame->reordered_opaque = avctx->reordered_opaque;
  1156. if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
  1157. frame->color_primaries = avctx->color_primaries;
  1158. if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
  1159. frame->color_trc = avctx->color_trc;
  1160. if (av_frame_get_colorspace(frame) == AVCOL_SPC_UNSPECIFIED)
  1161. av_frame_set_colorspace(frame, avctx->colorspace);
  1162. if (av_frame_get_color_range(frame) == AVCOL_RANGE_UNSPECIFIED)
  1163. av_frame_set_color_range(frame, avctx->color_range);
  1164. if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
  1165. frame->chroma_location = avctx->chroma_sample_location;
  1166. switch (avctx->codec->type) {
  1167. case AVMEDIA_TYPE_VIDEO:
  1168. frame->format = avctx->pix_fmt;
  1169. if (!frame->sample_aspect_ratio.num)
  1170. frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
  1171. if (frame->width && frame->height &&
  1172. av_image_check_sar(frame->width, frame->height,
  1173. frame->sample_aspect_ratio) < 0) {
  1174. av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
  1175. frame->sample_aspect_ratio.num,
  1176. frame->sample_aspect_ratio.den);
  1177. frame->sample_aspect_ratio = (AVRational){ 0, 1 };
  1178. }
  1179. break;
  1180. case AVMEDIA_TYPE_AUDIO:
  1181. if (!frame->sample_rate)
  1182. frame->sample_rate = avctx->sample_rate;
  1183. if (frame->format < 0)
  1184. frame->format = avctx->sample_fmt;
  1185. if (!frame->channel_layout) {
  1186. if (avctx->channel_layout) {
  1187. if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
  1188. avctx->channels) {
  1189. av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
  1190. "configuration.\n");
  1191. return AVERROR(EINVAL);
  1192. }
  1193. frame->channel_layout = avctx->channel_layout;
  1194. } else {
  1195. if (avctx->channels > FF_SANE_NB_CHANNELS) {
  1196. av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
  1197. avctx->channels);
  1198. return AVERROR(ENOSYS);
  1199. }
  1200. }
  1201. }
  1202. av_frame_set_channels(frame, avctx->channels);
  1203. break;
  1204. }
  1205. return 0;
  1206. }
  1207. int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
  1208. {
  1209. return ff_init_buffer_info(avctx, frame);
  1210. }
  1211. static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
  1212. {
  1213. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  1214. int i;
  1215. int num_planes = av_pix_fmt_count_planes(frame->format);
  1216. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
  1217. int flags = desc ? desc->flags : 0;
  1218. if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
  1219. num_planes = 2;
  1220. for (i = 0; i < num_planes; i++) {
  1221. av_assert0(frame->data[i]);
  1222. }
  1223. // For now do not enforce anything for palette of pseudopal formats
  1224. if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PSEUDOPAL))
  1225. num_planes = 2;
  1226. // For formats without data like hwaccel allow unused pointers to be non-NULL.
  1227. for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
  1228. if (frame->data[i])
  1229. av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
  1230. frame->data[i] = NULL;
  1231. }
  1232. }
  1233. }
  1234. static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
  1235. {
  1236. const AVHWAccel *hwaccel = avctx->hwaccel;
  1237. int override_dimensions = 1;
  1238. int ret;
  1239. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  1240. if ((ret = av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
  1241. av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
  1242. return AVERROR(EINVAL);
  1243. }
  1244. if (frame->width <= 0 || frame->height <= 0) {
  1245. frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
  1246. frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
  1247. override_dimensions = 0;
  1248. }
  1249. if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
  1250. av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
  1251. return AVERROR(EINVAL);
  1252. }
  1253. }
  1254. ret = ff_decode_frame_props(avctx, frame);
  1255. if (ret < 0)
  1256. return ret;
  1257. if (hwaccel) {
  1258. if (hwaccel->alloc_frame) {
  1259. ret = hwaccel->alloc_frame(avctx, frame);
  1260. goto end;
  1261. }
  1262. } else
  1263. avctx->sw_pix_fmt = avctx->pix_fmt;
  1264. ret = avctx->get_buffer2(avctx, frame, flags);
  1265. if (ret >= 0)
  1266. validate_avframe_allocation(avctx, frame);
  1267. end:
  1268. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions) {
  1269. frame->width = avctx->width;
  1270. frame->height = avctx->height;
  1271. }
  1272. return ret;
  1273. }
  1274. int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
  1275. {
  1276. int ret = get_buffer_internal(avctx, frame, flags);
  1277. if (ret < 0) {
  1278. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  1279. frame->width = frame->height = 0;
  1280. }
  1281. return ret;
  1282. }
  1283. static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
  1284. {
  1285. AVFrame *tmp;
  1286. int ret;
  1287. av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
  1288. if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
  1289. av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
  1290. frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
  1291. av_frame_unref(frame);
  1292. }
  1293. ff_init_buffer_info(avctx, frame);
  1294. if (!frame->data[0])
  1295. return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
  1296. if (av_frame_is_writable(frame))
  1297. return ff_decode_frame_props(avctx, frame);
  1298. tmp = av_frame_alloc();
  1299. if (!tmp)
  1300. return AVERROR(ENOMEM);
  1301. av_frame_move_ref(tmp, frame);
  1302. ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
  1303. if (ret < 0) {
  1304. av_frame_free(&tmp);
  1305. return ret;
  1306. }
  1307. av_frame_copy(frame, tmp);
  1308. av_frame_free(&tmp);
  1309. return 0;
  1310. }
  1311. int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
  1312. {
  1313. int ret = reget_buffer_internal(avctx, frame);
  1314. if (ret < 0)
  1315. av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
  1316. return ret;
  1317. }
  1318. void avcodec_flush_buffers(AVCodecContext *avctx)
  1319. {
  1320. avctx->internal->draining = 0;
  1321. avctx->internal->draining_done = 0;
  1322. av_frame_unref(avctx->internal->buffer_frame);
  1323. av_packet_unref(avctx->internal->buffer_pkt);
  1324. avctx->internal->buffer_pkt_valid = 0;
  1325. if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
  1326. ff_thread_flush(avctx);
  1327. else if (avctx->codec->flush)
  1328. avctx->codec->flush(avctx);
  1329. avctx->pts_correction_last_pts =
  1330. avctx->pts_correction_last_dts = INT64_MIN;
  1331. if (!avctx->refcounted_frames)
  1332. av_frame_unref(avctx->internal->to_free);
  1333. }