2
0

decode.c 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016
  1. /*
  2. * generic decoding-related code
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include <stdint.h>
  21. #include <string.h>
  22. #include "config.h"
  23. #if CONFIG_ICONV
  24. # include <iconv.h>
  25. #endif
  26. #include "libavutil/avassert.h"
  27. #include "libavutil/avstring.h"
  28. #include "libavutil/bprint.h"
  29. #include "libavutil/common.h"
  30. #include "libavutil/frame.h"
  31. #include "libavutil/hwcontext.h"
  32. #include "libavutil/imgutils.h"
  33. #include "libavutil/internal.h"
  34. #include "libavutil/intmath.h"
  35. #include "libavutil/opt.h"
  36. #include "avcodec.h"
  37. #include "bytestream.h"
  38. #include "decode.h"
  39. #include "hwaccel.h"
  40. #include "internal.h"
  41. #include "thread.h"
  42. static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
  43. {
  44. int size = 0, ret;
  45. const uint8_t *data;
  46. uint32_t flags;
  47. int64_t val;
  48. data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
  49. if (!data)
  50. return 0;
  51. if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
  52. av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
  53. "changes, but PARAM_CHANGE side data was sent to it.\n");
  54. ret = AVERROR(EINVAL);
  55. goto fail2;
  56. }
  57. if (size < 4)
  58. goto fail;
  59. flags = bytestream_get_le32(&data);
  60. size -= 4;
  61. if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
  62. if (size < 4)
  63. goto fail;
  64. val = bytestream_get_le32(&data);
  65. if (val <= 0 || val > INT_MAX) {
  66. av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
  67. ret = AVERROR_INVALIDDATA;
  68. goto fail2;
  69. }
  70. avctx->channels = val;
  71. size -= 4;
  72. }
  73. if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
  74. if (size < 8)
  75. goto fail;
  76. avctx->channel_layout = bytestream_get_le64(&data);
  77. size -= 8;
  78. }
  79. if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
  80. if (size < 4)
  81. goto fail;
  82. val = bytestream_get_le32(&data);
  83. if (val <= 0 || val > INT_MAX) {
  84. av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
  85. ret = AVERROR_INVALIDDATA;
  86. goto fail2;
  87. }
  88. avctx->sample_rate = val;
  89. size -= 4;
  90. }
  91. if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
  92. if (size < 8)
  93. goto fail;
  94. avctx->width = bytestream_get_le32(&data);
  95. avctx->height = bytestream_get_le32(&data);
  96. size -= 8;
  97. ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
  98. if (ret < 0)
  99. goto fail2;
  100. }
  101. return 0;
  102. fail:
  103. av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
  104. ret = AVERROR_INVALIDDATA;
  105. fail2:
  106. if (ret < 0) {
  107. av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
  108. if (avctx->err_recognition & AV_EF_EXPLODE)
  109. return ret;
  110. }
  111. return 0;
  112. }
  113. static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
  114. {
  115. int ret = 0;
  116. av_packet_unref(avci->last_pkt_props);
  117. if (pkt) {
  118. ret = av_packet_copy_props(avci->last_pkt_props, pkt);
  119. if (!ret)
  120. avci->last_pkt_props->size = pkt->size; // HACK: Needed for ff_decode_frame_props().
  121. }
  122. return ret;
  123. }
  124. static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
  125. {
  126. int ret;
  127. /* move the original frame to our backup */
  128. av_frame_unref(avci->to_free);
  129. av_frame_move_ref(avci->to_free, frame);
  130. /* now copy everything except the AVBufferRefs back
  131. * note that we make a COPY of the side data, so calling av_frame_free() on
  132. * the caller's frame will work properly */
  133. ret = av_frame_copy_props(frame, avci->to_free);
  134. if (ret < 0)
  135. return ret;
  136. memcpy(frame->data, avci->to_free->data, sizeof(frame->data));
  137. memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
  138. if (avci->to_free->extended_data != avci->to_free->data) {
  139. int planes = avci->to_free->channels;
  140. int size = planes * sizeof(*frame->extended_data);
  141. if (!size) {
  142. av_frame_unref(frame);
  143. return AVERROR_BUG;
  144. }
  145. frame->extended_data = av_malloc(size);
  146. if (!frame->extended_data) {
  147. av_frame_unref(frame);
  148. return AVERROR(ENOMEM);
  149. }
  150. memcpy(frame->extended_data, avci->to_free->extended_data,
  151. size);
  152. } else
  153. frame->extended_data = frame->data;
  154. frame->format = avci->to_free->format;
  155. frame->width = avci->to_free->width;
  156. frame->height = avci->to_free->height;
  157. frame->channel_layout = avci->to_free->channel_layout;
  158. frame->nb_samples = avci->to_free->nb_samples;
  159. frame->channels = avci->to_free->channels;
  160. return 0;
  161. }
  162. int ff_decode_bsfs_init(AVCodecContext *avctx)
  163. {
  164. AVCodecInternal *avci = avctx->internal;
  165. DecodeFilterContext *s = &avci->filter;
  166. const char *bsfs_str;
  167. int ret;
  168. if (s->nb_bsfs)
  169. return 0;
  170. bsfs_str = avctx->codec->bsfs ? avctx->codec->bsfs : "null";
  171. while (bsfs_str && *bsfs_str) {
  172. AVBSFContext **tmp;
  173. const AVBitStreamFilter *filter;
  174. char *bsf, *bsf_options_str, *bsf_name;
  175. bsf = av_get_token(&bsfs_str, ",");
  176. if (!bsf) {
  177. ret = AVERROR(ENOMEM);
  178. goto fail;
  179. }
  180. bsf_name = av_strtok(bsf, "=", &bsf_options_str);
  181. if (!bsf_name) {
  182. av_freep(&bsf);
  183. ret = AVERROR(ENOMEM);
  184. goto fail;
  185. }
  186. filter = av_bsf_get_by_name(bsf_name);
  187. if (!filter) {
  188. av_log(avctx, AV_LOG_ERROR, "A non-existing bitstream filter %s "
  189. "requested by a decoder. This is a bug, please report it.\n",
  190. bsf_name);
  191. av_freep(&bsf);
  192. ret = AVERROR_BUG;
  193. goto fail;
  194. }
  195. tmp = av_realloc_array(s->bsfs, s->nb_bsfs + 1, sizeof(*s->bsfs));
  196. if (!tmp) {
  197. av_freep(&bsf);
  198. ret = AVERROR(ENOMEM);
  199. goto fail;
  200. }
  201. s->bsfs = tmp;
  202. s->nb_bsfs++;
  203. ret = av_bsf_alloc(filter, &s->bsfs[s->nb_bsfs - 1]);
  204. if (ret < 0) {
  205. av_freep(&bsf);
  206. goto fail;
  207. }
  208. if (s->nb_bsfs == 1) {
  209. /* We do not currently have an API for passing the input timebase into decoders,
  210. * but no filters used here should actually need it.
  211. * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
  212. s->bsfs[s->nb_bsfs - 1]->time_base_in = (AVRational){ 1, 90000 };
  213. ret = avcodec_parameters_from_context(s->bsfs[s->nb_bsfs - 1]->par_in,
  214. avctx);
  215. } else {
  216. s->bsfs[s->nb_bsfs - 1]->time_base_in = s->bsfs[s->nb_bsfs - 2]->time_base_out;
  217. ret = avcodec_parameters_copy(s->bsfs[s->nb_bsfs - 1]->par_in,
  218. s->bsfs[s->nb_bsfs - 2]->par_out);
  219. }
  220. if (ret < 0) {
  221. av_freep(&bsf);
  222. goto fail;
  223. }
  224. if (bsf_options_str && filter->priv_class) {
  225. const AVOption *opt = av_opt_next(s->bsfs[s->nb_bsfs - 1]->priv_data, NULL);
  226. const char * shorthand[2] = {NULL};
  227. if (opt)
  228. shorthand[0] = opt->name;
  229. ret = av_opt_set_from_string(s->bsfs[s->nb_bsfs - 1]->priv_data, bsf_options_str, shorthand, "=", ":");
  230. if (ret < 0) {
  231. if (ret != AVERROR(ENOMEM)) {
  232. av_log(avctx, AV_LOG_ERROR, "Invalid options for bitstream filter %s "
  233. "requested by the decoder. This is a bug, please report it.\n",
  234. bsf_name);
  235. ret = AVERROR_BUG;
  236. }
  237. av_freep(&bsf);
  238. goto fail;
  239. }
  240. }
  241. av_freep(&bsf);
  242. ret = av_bsf_init(s->bsfs[s->nb_bsfs - 1]);
  243. if (ret < 0)
  244. goto fail;
  245. if (*bsfs_str)
  246. bsfs_str++;
  247. }
  248. return 0;
  249. fail:
  250. ff_decode_bsfs_uninit(avctx);
  251. return ret;
  252. }
  253. /* try to get one output packet from the filter chain */
  254. static int bsfs_poll(AVCodecContext *avctx, AVPacket *pkt)
  255. {
  256. DecodeFilterContext *s = &avctx->internal->filter;
  257. int idx, ret;
  258. /* start with the last filter in the chain */
  259. idx = s->nb_bsfs - 1;
  260. while (idx >= 0) {
  261. /* request a packet from the currently selected filter */
  262. ret = av_bsf_receive_packet(s->bsfs[idx], pkt);
  263. if (ret == AVERROR(EAGAIN)) {
  264. /* no packets available, try the next filter up the chain */
  265. ret = 0;
  266. idx--;
  267. continue;
  268. } else if (ret < 0 && ret != AVERROR_EOF) {
  269. return ret;
  270. }
  271. /* got a packet or EOF -- pass it to the caller or to the next filter
  272. * down the chain */
  273. if (idx == s->nb_bsfs - 1) {
  274. return ret;
  275. } else {
  276. idx++;
  277. ret = av_bsf_send_packet(s->bsfs[idx], ret < 0 ? NULL : pkt);
  278. if (ret < 0) {
  279. av_log(avctx, AV_LOG_ERROR,
  280. "Error pre-processing a packet before decoding\n");
  281. av_packet_unref(pkt);
  282. return ret;
  283. }
  284. }
  285. }
  286. return AVERROR(EAGAIN);
  287. }
  288. int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
  289. {
  290. AVCodecInternal *avci = avctx->internal;
  291. int ret;
  292. if (avci->draining)
  293. return AVERROR_EOF;
  294. ret = bsfs_poll(avctx, pkt);
  295. if (ret == AVERROR_EOF)
  296. avci->draining = 1;
  297. if (ret < 0)
  298. return ret;
  299. ret = extract_packet_props(avctx->internal, pkt);
  300. if (ret < 0)
  301. goto finish;
  302. ret = apply_param_change(avctx, pkt);
  303. if (ret < 0)
  304. goto finish;
  305. if (avctx->codec->receive_frame)
  306. avci->compat_decode_consumed += pkt->size;
  307. return 0;
  308. finish:
  309. av_packet_unref(pkt);
  310. return ret;
  311. }
  312. /**
  313. * Attempt to guess proper monotonic timestamps for decoded video frames
  314. * which might have incorrect times. Input timestamps may wrap around, in
  315. * which case the output will as well.
  316. *
  317. * @param pts the pts field of the decoded AVPacket, as passed through
  318. * AVFrame.pts
  319. * @param dts the dts field of the decoded AVPacket
  320. * @return one of the input values, may be AV_NOPTS_VALUE
  321. */
  322. static int64_t guess_correct_pts(AVCodecContext *ctx,
  323. int64_t reordered_pts, int64_t dts)
  324. {
  325. int64_t pts = AV_NOPTS_VALUE;
  326. if (dts != AV_NOPTS_VALUE) {
  327. ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
  328. ctx->pts_correction_last_dts = dts;
  329. } else if (reordered_pts != AV_NOPTS_VALUE)
  330. ctx->pts_correction_last_dts = reordered_pts;
  331. if (reordered_pts != AV_NOPTS_VALUE) {
  332. ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
  333. ctx->pts_correction_last_pts = reordered_pts;
  334. } else if(dts != AV_NOPTS_VALUE)
  335. ctx->pts_correction_last_pts = dts;
  336. if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
  337. && reordered_pts != AV_NOPTS_VALUE)
  338. pts = reordered_pts;
  339. else
  340. pts = dts;
  341. return pts;
  342. }
  343. /*
  344. * The core of the receive_frame_wrapper for the decoders implementing
  345. * the simple API. Certain decoders might consume partial packets without
  346. * returning any output, so this function needs to be called in a loop until it
  347. * returns EAGAIN.
  348. **/
  349. static int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame)
  350. {
  351. AVCodecInternal *avci = avctx->internal;
  352. DecodeSimpleContext *ds = &avci->ds;
  353. AVPacket *pkt = ds->in_pkt;
  354. // copy to ensure we do not change pkt
  355. int got_frame, actual_got_frame;
  356. int ret;
  357. if (!pkt->data && !avci->draining) {
  358. av_packet_unref(pkt);
  359. ret = ff_decode_get_packet(avctx, pkt);
  360. if (ret < 0 && ret != AVERROR_EOF)
  361. return ret;
  362. }
  363. // Some codecs (at least wma lossless) will crash when feeding drain packets
  364. // after EOF was signaled.
  365. if (avci->draining_done)
  366. return AVERROR_EOF;
  367. if (!pkt->data &&
  368. !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
  369. avctx->active_thread_type & FF_THREAD_FRAME))
  370. return AVERROR_EOF;
  371. got_frame = 0;
  372. if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
  373. ret = ff_thread_decode_frame(avctx, frame, &got_frame, pkt);
  374. } else {
  375. ret = avctx->codec->decode(avctx, frame, &got_frame, pkt);
  376. if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
  377. frame->pkt_dts = pkt->dts;
  378. if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
  379. if(!avctx->has_b_frames)
  380. frame->pkt_pos = pkt->pos;
  381. //FIXME these should be under if(!avctx->has_b_frames)
  382. /* get_buffer is supposed to set frame parameters */
  383. if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
  384. if (!frame->sample_aspect_ratio.num) frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
  385. if (!frame->width) frame->width = avctx->width;
  386. if (!frame->height) frame->height = avctx->height;
  387. if (frame->format == AV_PIX_FMT_NONE) frame->format = avctx->pix_fmt;
  388. }
  389. }
  390. }
  391. emms_c();
  392. actual_got_frame = got_frame;
  393. if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
  394. if (frame->flags & AV_FRAME_FLAG_DISCARD)
  395. got_frame = 0;
  396. if (got_frame)
  397. frame->best_effort_timestamp = guess_correct_pts(avctx,
  398. frame->pts,
  399. frame->pkt_dts);
  400. } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
  401. uint8_t *side;
  402. int side_size;
  403. uint32_t discard_padding = 0;
  404. uint8_t skip_reason = 0;
  405. uint8_t discard_reason = 0;
  406. if (ret >= 0 && got_frame) {
  407. frame->best_effort_timestamp = guess_correct_pts(avctx,
  408. frame->pts,
  409. frame->pkt_dts);
  410. if (frame->format == AV_SAMPLE_FMT_NONE)
  411. frame->format = avctx->sample_fmt;
  412. if (!frame->channel_layout)
  413. frame->channel_layout = avctx->channel_layout;
  414. if (!frame->channels)
  415. frame->channels = avctx->channels;
  416. if (!frame->sample_rate)
  417. frame->sample_rate = avctx->sample_rate;
  418. }
  419. side= av_packet_get_side_data(avci->last_pkt_props, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
  420. if(side && side_size>=10) {
  421. avctx->internal->skip_samples = AV_RL32(side) * avctx->internal->skip_samples_multiplier;
  422. discard_padding = AV_RL32(side + 4);
  423. av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
  424. avctx->internal->skip_samples, (int)discard_padding);
  425. skip_reason = AV_RL8(side + 8);
  426. discard_reason = AV_RL8(side + 9);
  427. }
  428. if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
  429. !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
  430. avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples);
  431. got_frame = 0;
  432. }
  433. if (avctx->internal->skip_samples > 0 && got_frame &&
  434. !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
  435. if(frame->nb_samples <= avctx->internal->skip_samples){
  436. got_frame = 0;
  437. avctx->internal->skip_samples -= frame->nb_samples;
  438. av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
  439. avctx->internal->skip_samples);
  440. } else {
  441. av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
  442. frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
  443. if(avctx->pkt_timebase.num && avctx->sample_rate) {
  444. int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
  445. (AVRational){1, avctx->sample_rate},
  446. avctx->pkt_timebase);
  447. if(frame->pts!=AV_NOPTS_VALUE)
  448. frame->pts += diff_ts;
  449. #if FF_API_PKT_PTS
  450. FF_DISABLE_DEPRECATION_WARNINGS
  451. if(frame->pkt_pts!=AV_NOPTS_VALUE)
  452. frame->pkt_pts += diff_ts;
  453. FF_ENABLE_DEPRECATION_WARNINGS
  454. #endif
  455. if(frame->pkt_dts!=AV_NOPTS_VALUE)
  456. frame->pkt_dts += diff_ts;
  457. if (frame->pkt_duration >= diff_ts)
  458. frame->pkt_duration -= diff_ts;
  459. } else {
  460. av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
  461. }
  462. av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
  463. avctx->internal->skip_samples, frame->nb_samples);
  464. frame->nb_samples -= avctx->internal->skip_samples;
  465. avctx->internal->skip_samples = 0;
  466. }
  467. }
  468. if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
  469. !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
  470. if (discard_padding == frame->nb_samples) {
  471. got_frame = 0;
  472. } else {
  473. if(avctx->pkt_timebase.num && avctx->sample_rate) {
  474. int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
  475. (AVRational){1, avctx->sample_rate},
  476. avctx->pkt_timebase);
  477. frame->pkt_duration = diff_ts;
  478. } else {
  479. av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
  480. }
  481. av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
  482. (int)discard_padding, frame->nb_samples);
  483. frame->nb_samples -= discard_padding;
  484. }
  485. }
  486. if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
  487. AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
  488. if (fside) {
  489. AV_WL32(fside->data, avctx->internal->skip_samples);
  490. AV_WL32(fside->data + 4, discard_padding);
  491. AV_WL8(fside->data + 8, skip_reason);
  492. AV_WL8(fside->data + 9, discard_reason);
  493. avctx->internal->skip_samples = 0;
  494. }
  495. }
  496. }
  497. if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
  498. !avci->showed_multi_packet_warning &&
  499. ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
  500. av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
  501. avci->showed_multi_packet_warning = 1;
  502. }
  503. if (!got_frame)
  504. av_frame_unref(frame);
  505. if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
  506. ret = pkt->size;
  507. #if FF_API_AVCTX_TIMEBASE
  508. if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
  509. avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
  510. #endif
  511. /* do not stop draining when actual_got_frame != 0 or ret < 0 */
  512. /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
  513. if (avctx->internal->draining && !actual_got_frame) {
  514. if (ret < 0) {
  515. /* prevent infinite loop if a decoder wrongly always return error on draining */
  516. /* reasonable nb_errors_max = maximum b frames + thread count */
  517. int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
  518. avctx->thread_count : 1);
  519. if (avci->nb_draining_errors++ >= nb_errors_max) {
  520. av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
  521. "Stop draining and force EOF.\n");
  522. avci->draining_done = 1;
  523. ret = AVERROR_BUG;
  524. }
  525. } else {
  526. avci->draining_done = 1;
  527. }
  528. }
  529. avci->compat_decode_consumed += ret;
  530. if (ret >= pkt->size || ret < 0) {
  531. av_packet_unref(pkt);
  532. } else {
  533. int consumed = ret;
  534. pkt->data += consumed;
  535. pkt->size -= consumed;
  536. avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
  537. pkt->pts = AV_NOPTS_VALUE;
  538. pkt->dts = AV_NOPTS_VALUE;
  539. avci->last_pkt_props->pts = AV_NOPTS_VALUE;
  540. avci->last_pkt_props->dts = AV_NOPTS_VALUE;
  541. }
  542. if (got_frame)
  543. av_assert0(frame->buf[0]);
  544. return ret < 0 ? ret : 0;
  545. }
  546. static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
  547. {
  548. int ret;
  549. while (!frame->buf[0]) {
  550. ret = decode_simple_internal(avctx, frame);
  551. if (ret < 0)
  552. return ret;
  553. }
  554. return 0;
  555. }
  556. static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
  557. {
  558. AVCodecInternal *avci = avctx->internal;
  559. int ret;
  560. av_assert0(!frame->buf[0]);
  561. if (avctx->codec->receive_frame)
  562. ret = avctx->codec->receive_frame(avctx, frame);
  563. else
  564. ret = decode_simple_receive_frame(avctx, frame);
  565. if (ret == AVERROR_EOF)
  566. avci->draining_done = 1;
  567. if (!ret) {
  568. /* the only case where decode data is not set should be decoders
  569. * that do not call ff_get_buffer() */
  570. av_assert0((frame->private_ref && frame->private_ref->size == sizeof(FrameDecodeData)) ||
  571. !(avctx->codec->capabilities & AV_CODEC_CAP_DR1));
  572. if (frame->private_ref) {
  573. FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
  574. if (fdd->post_process) {
  575. ret = fdd->post_process(avctx, frame);
  576. if (ret < 0) {
  577. av_frame_unref(frame);
  578. return ret;
  579. }
  580. }
  581. }
  582. }
  583. /* free the per-frame decode data */
  584. av_buffer_unref(&frame->private_ref);
  585. return ret;
  586. }
  587. int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
  588. {
  589. AVCodecInternal *avci = avctx->internal;
  590. int ret;
  591. if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
  592. return AVERROR(EINVAL);
  593. if (avctx->internal->draining)
  594. return AVERROR_EOF;
  595. if (avpkt && !avpkt->size && avpkt->data)
  596. return AVERROR(EINVAL);
  597. av_packet_unref(avci->buffer_pkt);
  598. if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
  599. ret = av_packet_ref(avci->buffer_pkt, avpkt);
  600. if (ret < 0)
  601. return ret;
  602. }
  603. ret = av_bsf_send_packet(avci->filter.bsfs[0], avci->buffer_pkt);
  604. if (ret < 0) {
  605. av_packet_unref(avci->buffer_pkt);
  606. return ret;
  607. }
  608. if (!avci->buffer_frame->buf[0]) {
  609. ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
  610. if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
  611. return ret;
  612. }
  613. return 0;
  614. }
  615. static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
  616. {
  617. /* make sure we are noisy about decoders returning invalid cropping data */
  618. if (frame->crop_left >= INT_MAX - frame->crop_right ||
  619. frame->crop_top >= INT_MAX - frame->crop_bottom ||
  620. (frame->crop_left + frame->crop_right) >= frame->width ||
  621. (frame->crop_top + frame->crop_bottom) >= frame->height) {
  622. av_log(avctx, AV_LOG_WARNING,
  623. "Invalid cropping information set by a decoder: "
  624. "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
  625. "(frame size %dx%d). This is a bug, please report it\n",
  626. frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
  627. frame->width, frame->height);
  628. frame->crop_left = 0;
  629. frame->crop_right = 0;
  630. frame->crop_top = 0;
  631. frame->crop_bottom = 0;
  632. return 0;
  633. }
  634. if (!avctx->apply_cropping)
  635. return 0;
  636. return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
  637. AV_FRAME_CROP_UNALIGNED : 0);
  638. }
  639. int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
  640. {
  641. AVCodecInternal *avci = avctx->internal;
  642. int ret;
  643. av_frame_unref(frame);
  644. if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
  645. return AVERROR(EINVAL);
  646. if (avci->buffer_frame->buf[0]) {
  647. av_frame_move_ref(frame, avci->buffer_frame);
  648. } else {
  649. ret = decode_receive_frame_internal(avctx, frame);
  650. if (ret < 0)
  651. return ret;
  652. }
  653. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  654. ret = apply_cropping(avctx, frame);
  655. if (ret < 0) {
  656. av_frame_unref(frame);
  657. return ret;
  658. }
  659. }
  660. avctx->frame_number++;
  661. return 0;
  662. }
  663. static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
  664. int *got_frame, const AVPacket *pkt)
  665. {
  666. AVCodecInternal *avci = avctx->internal;
  667. int ret = 0;
  668. av_assert0(avci->compat_decode_consumed == 0);
  669. if (avci->draining_done && pkt && pkt->size != 0) {
  670. av_log(avctx, AV_LOG_WARNING, "Got unexpected packet after EOF\n");
  671. avcodec_flush_buffers(avctx);
  672. }
  673. *got_frame = 0;
  674. avci->compat_decode = 1;
  675. if (avci->compat_decode_partial_size > 0 &&
  676. avci->compat_decode_partial_size != pkt->size) {
  677. av_log(avctx, AV_LOG_ERROR,
  678. "Got unexpected packet size after a partial decode\n");
  679. ret = AVERROR(EINVAL);
  680. goto finish;
  681. }
  682. if (!avci->compat_decode_partial_size) {
  683. ret = avcodec_send_packet(avctx, pkt);
  684. if (ret == AVERROR_EOF)
  685. ret = 0;
  686. else if (ret == AVERROR(EAGAIN)) {
  687. /* we fully drain all the output in each decode call, so this should not
  688. * ever happen */
  689. ret = AVERROR_BUG;
  690. goto finish;
  691. } else if (ret < 0)
  692. goto finish;
  693. }
  694. while (ret >= 0) {
  695. ret = avcodec_receive_frame(avctx, frame);
  696. if (ret < 0) {
  697. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  698. ret = 0;
  699. goto finish;
  700. }
  701. if (frame != avci->compat_decode_frame) {
  702. if (!avctx->refcounted_frames) {
  703. ret = unrefcount_frame(avci, frame);
  704. if (ret < 0)
  705. goto finish;
  706. }
  707. *got_frame = 1;
  708. frame = avci->compat_decode_frame;
  709. } else {
  710. if (!avci->compat_decode_warned) {
  711. av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
  712. "API cannot return all the frames for this decoder. "
  713. "Some frames will be dropped. Update your code to the "
  714. "new decoding API to fix this.\n");
  715. avci->compat_decode_warned = 1;
  716. }
  717. }
  718. if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
  719. break;
  720. }
  721. finish:
  722. if (ret == 0) {
  723. /* if there are any bsfs then assume full packet is always consumed */
  724. if (avctx->codec->bsfs)
  725. ret = pkt->size;
  726. else
  727. ret = FFMIN(avci->compat_decode_consumed, pkt->size);
  728. }
  729. avci->compat_decode_consumed = 0;
  730. avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
  731. return ret;
  732. }
  733. int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
  734. int *got_picture_ptr,
  735. const AVPacket *avpkt)
  736. {
  737. return compat_decode(avctx, picture, got_picture_ptr, avpkt);
  738. }
  739. int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
  740. AVFrame *frame,
  741. int *got_frame_ptr,
  742. const AVPacket *avpkt)
  743. {
  744. return compat_decode(avctx, frame, got_frame_ptr, avpkt);
  745. }
  746. static void get_subtitle_defaults(AVSubtitle *sub)
  747. {
  748. memset(sub, 0, sizeof(*sub));
  749. sub->pts = AV_NOPTS_VALUE;
  750. }
  751. #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
  752. static int recode_subtitle(AVCodecContext *avctx,
  753. AVPacket *outpkt, const AVPacket *inpkt)
  754. {
  755. #if CONFIG_ICONV
  756. iconv_t cd = (iconv_t)-1;
  757. int ret = 0;
  758. char *inb, *outb;
  759. size_t inl, outl;
  760. AVPacket tmp;
  761. #endif
  762. if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
  763. return 0;
  764. #if CONFIG_ICONV
  765. cd = iconv_open("UTF-8", avctx->sub_charenc);
  766. av_assert0(cd != (iconv_t)-1);
  767. inb = inpkt->data;
  768. inl = inpkt->size;
  769. if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
  770. av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
  771. ret = AVERROR(ENOMEM);
  772. goto end;
  773. }
  774. ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
  775. if (ret < 0)
  776. goto end;
  777. outpkt->buf = tmp.buf;
  778. outpkt->data = tmp.data;
  779. outpkt->size = tmp.size;
  780. outb = outpkt->data;
  781. outl = outpkt->size;
  782. if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
  783. iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
  784. outl >= outpkt->size || inl != 0) {
  785. ret = FFMIN(AVERROR(errno), -1);
  786. av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
  787. "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
  788. av_packet_unref(&tmp);
  789. goto end;
  790. }
  791. outpkt->size -= outl;
  792. memset(outpkt->data + outpkt->size, 0, outl);
  793. end:
  794. if (cd != (iconv_t)-1)
  795. iconv_close(cd);
  796. return ret;
  797. #else
  798. av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
  799. return AVERROR(EINVAL);
  800. #endif
  801. }
  802. static int utf8_check(const uint8_t *str)
  803. {
  804. const uint8_t *byte;
  805. uint32_t codepoint, min;
  806. while (*str) {
  807. byte = str;
  808. GET_UTF8(codepoint, *(byte++), return 0;);
  809. min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
  810. 1 << (5 * (byte - str) - 4);
  811. if (codepoint < min || codepoint >= 0x110000 ||
  812. codepoint == 0xFFFE /* BOM */ ||
  813. codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
  814. return 0;
  815. str = byte;
  816. }
  817. return 1;
  818. }
  819. #if FF_API_ASS_TIMING
  820. static void insert_ts(AVBPrint *buf, int ts)
  821. {
  822. if (ts == -1) {
  823. av_bprintf(buf, "9:59:59.99,");
  824. } else {
  825. int h, m, s;
  826. h = ts/360000; ts -= 360000*h;
  827. m = ts/ 6000; ts -= 6000*m;
  828. s = ts/ 100; ts -= 100*s;
  829. av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
  830. }
  831. }
  832. static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
  833. {
  834. int i;
  835. AVBPrint buf;
  836. av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
  837. for (i = 0; i < sub->num_rects; i++) {
  838. char *final_dialog;
  839. const char *dialog;
  840. AVSubtitleRect *rect = sub->rects[i];
  841. int ts_start, ts_duration = -1;
  842. long int layer;
  843. if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
  844. continue;
  845. av_bprint_clear(&buf);
  846. /* skip ReadOrder */
  847. dialog = strchr(rect->ass, ',');
  848. if (!dialog)
  849. continue;
  850. dialog++;
  851. /* extract Layer or Marked */
  852. layer = strtol(dialog, (char**)&dialog, 10);
  853. if (*dialog != ',')
  854. continue;
  855. dialog++;
  856. /* rescale timing to ASS time base (ms) */
  857. ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
  858. if (pkt->duration != -1)
  859. ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
  860. sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
  861. /* construct ASS (standalone file form with timestamps) string */
  862. av_bprintf(&buf, "Dialogue: %ld,", layer);
  863. insert_ts(&buf, ts_start);
  864. insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
  865. av_bprintf(&buf, "%s\r\n", dialog);
  866. final_dialog = av_strdup(buf.str);
  867. if (!av_bprint_is_complete(&buf) || !final_dialog) {
  868. av_freep(&final_dialog);
  869. av_bprint_finalize(&buf, NULL);
  870. return AVERROR(ENOMEM);
  871. }
  872. av_freep(&rect->ass);
  873. rect->ass = final_dialog;
  874. }
  875. av_bprint_finalize(&buf, NULL);
  876. return 0;
  877. }
  878. #endif
  879. int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
  880. int *got_sub_ptr,
  881. AVPacket *avpkt)
  882. {
  883. int i, ret = 0;
  884. if (!avpkt->data && avpkt->size) {
  885. av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
  886. return AVERROR(EINVAL);
  887. }
  888. if (!avctx->codec)
  889. return AVERROR(EINVAL);
  890. if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
  891. av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
  892. return AVERROR(EINVAL);
  893. }
  894. *got_sub_ptr = 0;
  895. get_subtitle_defaults(sub);
  896. if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
  897. AVPacket pkt_recoded = *avpkt;
  898. ret = recode_subtitle(avctx, &pkt_recoded, avpkt);
  899. if (ret < 0) {
  900. *got_sub_ptr = 0;
  901. } else {
  902. ret = extract_packet_props(avctx->internal, &pkt_recoded);
  903. if (ret < 0)
  904. return ret;
  905. if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
  906. sub->pts = av_rescale_q(avpkt->pts,
  907. avctx->pkt_timebase, AV_TIME_BASE_Q);
  908. ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
  909. av_assert1((ret >= 0) >= !!*got_sub_ptr &&
  910. !!*got_sub_ptr >= !!sub->num_rects);
  911. #if FF_API_ASS_TIMING
  912. if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
  913. && *got_sub_ptr && sub->num_rects) {
  914. const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
  915. : avctx->time_base;
  916. int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
  917. if (err < 0)
  918. ret = err;
  919. }
  920. #endif
  921. if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
  922. avctx->pkt_timebase.num) {
  923. AVRational ms = { 1, 1000 };
  924. sub->end_display_time = av_rescale_q(avpkt->duration,
  925. avctx->pkt_timebase, ms);
  926. }
  927. if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
  928. sub->format = 0;
  929. else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
  930. sub->format = 1;
  931. for (i = 0; i < sub->num_rects; i++) {
  932. if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_IGNORE &&
  933. sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
  934. av_log(avctx, AV_LOG_ERROR,
  935. "Invalid UTF-8 in decoded subtitles text; "
  936. "maybe missing -sub_charenc option\n");
  937. avsubtitle_free(sub);
  938. ret = AVERROR_INVALIDDATA;
  939. break;
  940. }
  941. }
  942. if (avpkt->data != pkt_recoded.data) { // did we recode?
  943. /* prevent from destroying side data from original packet */
  944. pkt_recoded.side_data = NULL;
  945. pkt_recoded.side_data_elems = 0;
  946. av_packet_unref(&pkt_recoded);
  947. }
  948. }
  949. if (*got_sub_ptr)
  950. avctx->frame_number++;
  951. }
  952. return ret;
  953. }
  954. enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
  955. const enum AVPixelFormat *fmt)
  956. {
  957. const AVPixFmtDescriptor *desc;
  958. const AVCodecHWConfig *config;
  959. int i, n;
  960. // If a device was supplied when the codec was opened, assume that the
  961. // user wants to use it.
  962. if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
  963. AVHWDeviceContext *device_ctx =
  964. (AVHWDeviceContext*)avctx->hw_device_ctx->data;
  965. for (i = 0;; i++) {
  966. config = &avctx->codec->hw_configs[i]->public;
  967. if (!config)
  968. break;
  969. if (!(config->methods &
  970. AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
  971. continue;
  972. if (device_ctx->type != config->device_type)
  973. continue;
  974. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
  975. if (config->pix_fmt == fmt[n])
  976. return fmt[n];
  977. }
  978. }
  979. }
  980. // No device or other setup, so we have to choose from things which
  981. // don't any other external information.
  982. // If the last element of the list is a software format, choose it
  983. // (this should be best software format if any exist).
  984. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
  985. desc = av_pix_fmt_desc_get(fmt[n - 1]);
  986. if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
  987. return fmt[n - 1];
  988. // Finally, traverse the list in order and choose the first entry
  989. // with no external dependencies (if there is no hardware configuration
  990. // information available then this just picks the first entry).
  991. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
  992. for (i = 0;; i++) {
  993. config = avcodec_get_hw_config(avctx->codec, i);
  994. if (!config)
  995. break;
  996. if (config->pix_fmt == fmt[n])
  997. break;
  998. }
  999. if (!config) {
  1000. // No specific config available, so the decoder must be able
  1001. // to handle this format without any additional setup.
  1002. return fmt[n];
  1003. }
  1004. if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
  1005. // Usable with only internal setup.
  1006. return fmt[n];
  1007. }
  1008. }
  1009. // Nothing is usable, give up.
  1010. return AV_PIX_FMT_NONE;
  1011. }
  1012. int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
  1013. enum AVHWDeviceType dev_type)
  1014. {
  1015. AVHWDeviceContext *device_ctx;
  1016. AVHWFramesContext *frames_ctx;
  1017. int ret;
  1018. if (!avctx->hwaccel)
  1019. return AVERROR(ENOSYS);
  1020. if (avctx->hw_frames_ctx)
  1021. return 0;
  1022. if (!avctx->hw_device_ctx) {
  1023. av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
  1024. "required for hardware accelerated decoding.\n");
  1025. return AVERROR(EINVAL);
  1026. }
  1027. device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
  1028. if (device_ctx->type != dev_type) {
  1029. av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
  1030. "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
  1031. av_hwdevice_get_type_name(device_ctx->type));
  1032. return AVERROR(EINVAL);
  1033. }
  1034. ret = avcodec_get_hw_frames_parameters(avctx,
  1035. avctx->hw_device_ctx,
  1036. avctx->hwaccel->pix_fmt,
  1037. &avctx->hw_frames_ctx);
  1038. if (ret < 0)
  1039. return ret;
  1040. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  1041. if (frames_ctx->initial_pool_size) {
  1042. // We guarantee 4 base work surfaces. The function above guarantees 1
  1043. // (the absolute minimum), so add the missing count.
  1044. frames_ctx->initial_pool_size += 3;
  1045. }
  1046. ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
  1047. if (ret < 0) {
  1048. av_buffer_unref(&avctx->hw_frames_ctx);
  1049. return ret;
  1050. }
  1051. return 0;
  1052. }
  1053. int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
  1054. AVBufferRef *device_ref,
  1055. enum AVPixelFormat hw_pix_fmt,
  1056. AVBufferRef **out_frames_ref)
  1057. {
  1058. AVBufferRef *frames_ref = NULL;
  1059. const AVCodecHWConfigInternal *hw_config;
  1060. const AVHWAccel *hwa;
  1061. int i, ret;
  1062. for (i = 0;; i++) {
  1063. hw_config = avctx->codec->hw_configs[i];
  1064. if (!hw_config)
  1065. return AVERROR(ENOENT);
  1066. if (hw_config->public.pix_fmt == hw_pix_fmt)
  1067. break;
  1068. }
  1069. hwa = hw_config->hwaccel;
  1070. if (!hwa || !hwa->frame_params)
  1071. return AVERROR(ENOENT);
  1072. frames_ref = av_hwframe_ctx_alloc(device_ref);
  1073. if (!frames_ref)
  1074. return AVERROR(ENOMEM);
  1075. ret = hwa->frame_params(avctx, frames_ref);
  1076. if (ret >= 0) {
  1077. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
  1078. if (frames_ctx->initial_pool_size) {
  1079. // If the user has requested that extra output surfaces be
  1080. // available then add them here.
  1081. if (avctx->extra_hw_frames > 0)
  1082. frames_ctx->initial_pool_size += avctx->extra_hw_frames;
  1083. // If frame threading is enabled then an extra surface per thread
  1084. // is also required.
  1085. if (avctx->active_thread_type & FF_THREAD_FRAME)
  1086. frames_ctx->initial_pool_size += avctx->thread_count;
  1087. }
  1088. *out_frames_ref = frames_ref;
  1089. } else {
  1090. av_buffer_unref(&frames_ref);
  1091. }
  1092. return ret;
  1093. }
  1094. static int hwaccel_init(AVCodecContext *avctx,
  1095. const AVCodecHWConfigInternal *hw_config)
  1096. {
  1097. const AVHWAccel *hwaccel;
  1098. int err;
  1099. hwaccel = hw_config->hwaccel;
  1100. if (hwaccel->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
  1101. avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  1102. av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
  1103. hwaccel->name);
  1104. return AVERROR_PATCHWELCOME;
  1105. }
  1106. if (hwaccel->priv_data_size) {
  1107. avctx->internal->hwaccel_priv_data =
  1108. av_mallocz(hwaccel->priv_data_size);
  1109. if (!avctx->internal->hwaccel_priv_data)
  1110. return AVERROR(ENOMEM);
  1111. }
  1112. avctx->hwaccel = hwaccel;
  1113. if (hwaccel->init) {
  1114. err = hwaccel->init(avctx);
  1115. if (err < 0) {
  1116. av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
  1117. "hwaccel initialisation returned error.\n",
  1118. av_get_pix_fmt_name(hw_config->public.pix_fmt));
  1119. av_freep(&avctx->internal->hwaccel_priv_data);
  1120. avctx->hwaccel = NULL;
  1121. return err;
  1122. }
  1123. }
  1124. return 0;
  1125. }
  1126. static void hwaccel_uninit(AVCodecContext *avctx)
  1127. {
  1128. if (avctx->hwaccel && avctx->hwaccel->uninit)
  1129. avctx->hwaccel->uninit(avctx);
  1130. av_freep(&avctx->internal->hwaccel_priv_data);
  1131. avctx->hwaccel = NULL;
  1132. av_buffer_unref(&avctx->hw_frames_ctx);
  1133. }
  1134. int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
  1135. {
  1136. const AVPixFmtDescriptor *desc;
  1137. enum AVPixelFormat *choices;
  1138. enum AVPixelFormat ret, user_choice;
  1139. const AVCodecHWConfigInternal *hw_config;
  1140. const AVCodecHWConfig *config;
  1141. int i, n, err;
  1142. // Find end of list.
  1143. for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
  1144. // Must contain at least one entry.
  1145. av_assert0(n >= 1);
  1146. // If a software format is available, it must be the last entry.
  1147. desc = av_pix_fmt_desc_get(fmt[n - 1]);
  1148. if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
  1149. // No software format is available.
  1150. } else {
  1151. avctx->sw_pix_fmt = fmt[n - 1];
  1152. }
  1153. choices = av_malloc_array(n + 1, sizeof(*choices));
  1154. if (!choices)
  1155. return AV_PIX_FMT_NONE;
  1156. memcpy(choices, fmt, (n + 1) * sizeof(*choices));
  1157. for (;;) {
  1158. // Remove the previous hwaccel, if there was one.
  1159. hwaccel_uninit(avctx);
  1160. user_choice = avctx->get_format(avctx, choices);
  1161. if (user_choice == AV_PIX_FMT_NONE) {
  1162. // Explicitly chose nothing, give up.
  1163. ret = AV_PIX_FMT_NONE;
  1164. break;
  1165. }
  1166. desc = av_pix_fmt_desc_get(user_choice);
  1167. if (!desc) {
  1168. av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
  1169. "get_format() callback.\n");
  1170. ret = AV_PIX_FMT_NONE;
  1171. break;
  1172. }
  1173. av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
  1174. desc->name);
  1175. for (i = 0; i < n; i++) {
  1176. if (choices[i] == user_choice)
  1177. break;
  1178. }
  1179. if (i == n) {
  1180. av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
  1181. "%s not in possible list.\n", desc->name);
  1182. break;
  1183. }
  1184. if (avctx->codec->hw_configs) {
  1185. for (i = 0;; i++) {
  1186. hw_config = avctx->codec->hw_configs[i];
  1187. if (!hw_config)
  1188. break;
  1189. if (hw_config->public.pix_fmt == user_choice)
  1190. break;
  1191. }
  1192. } else {
  1193. hw_config = NULL;
  1194. }
  1195. if (!hw_config) {
  1196. // No config available, so no extra setup required.
  1197. ret = user_choice;
  1198. break;
  1199. }
  1200. config = &hw_config->public;
  1201. if (config->methods &
  1202. AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
  1203. avctx->hw_frames_ctx) {
  1204. const AVHWFramesContext *frames_ctx =
  1205. (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  1206. if (frames_ctx->format != user_choice) {
  1207. av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
  1208. "does not match the format of the provided frames "
  1209. "context.\n", desc->name);
  1210. goto try_again;
  1211. }
  1212. } else if (config->methods &
  1213. AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
  1214. avctx->hw_device_ctx) {
  1215. const AVHWDeviceContext *device_ctx =
  1216. (AVHWDeviceContext*)avctx->hw_device_ctx->data;
  1217. if (device_ctx->type != config->device_type) {
  1218. av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
  1219. "does not match the type of the provided device "
  1220. "context.\n", desc->name);
  1221. goto try_again;
  1222. }
  1223. } else if (config->methods &
  1224. AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
  1225. // Internal-only setup, no additional configuration.
  1226. } else if (config->methods &
  1227. AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
  1228. // Some ad-hoc configuration we can't see and can't check.
  1229. } else {
  1230. av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
  1231. "missing configuration.\n", desc->name);
  1232. goto try_again;
  1233. }
  1234. if (hw_config->hwaccel) {
  1235. av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
  1236. "initialisation.\n", desc->name);
  1237. err = hwaccel_init(avctx, hw_config);
  1238. if (err < 0)
  1239. goto try_again;
  1240. }
  1241. ret = user_choice;
  1242. break;
  1243. try_again:
  1244. av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
  1245. "get_format() without it.\n", desc->name);
  1246. for (i = 0; i < n; i++) {
  1247. if (choices[i] == user_choice)
  1248. break;
  1249. }
  1250. for (; i + 1 < n; i++)
  1251. choices[i] = choices[i + 1];
  1252. --n;
  1253. }
  1254. av_freep(&choices);
  1255. return ret;
  1256. }
  1257. static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
  1258. {
  1259. FramePool *pool = avctx->internal->pool;
  1260. int i, ret;
  1261. switch (avctx->codec_type) {
  1262. case AVMEDIA_TYPE_VIDEO: {
  1263. uint8_t *data[4];
  1264. int linesize[4];
  1265. int size[4] = { 0 };
  1266. int w = frame->width;
  1267. int h = frame->height;
  1268. int tmpsize, unaligned;
  1269. if (pool->format == frame->format &&
  1270. pool->width == frame->width && pool->height == frame->height)
  1271. return 0;
  1272. avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
  1273. do {
  1274. // NOTE: do not align linesizes individually, this breaks e.g. assumptions
  1275. // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
  1276. ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
  1277. if (ret < 0)
  1278. return ret;
  1279. // increase alignment of w for next try (rhs gives the lowest bit set in w)
  1280. w += w & ~(w - 1);
  1281. unaligned = 0;
  1282. for (i = 0; i < 4; i++)
  1283. unaligned |= linesize[i] % pool->stride_align[i];
  1284. } while (unaligned);
  1285. tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
  1286. NULL, linesize);
  1287. if (tmpsize < 0)
  1288. return tmpsize;
  1289. for (i = 0; i < 3 && data[i + 1]; i++)
  1290. size[i] = data[i + 1] - data[i];
  1291. size[i] = tmpsize - (data[i] - data[0]);
  1292. for (i = 0; i < 4; i++) {
  1293. av_buffer_pool_uninit(&pool->pools[i]);
  1294. pool->linesize[i] = linesize[i];
  1295. if (size[i]) {
  1296. pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
  1297. CONFIG_MEMORY_POISONING ?
  1298. NULL :
  1299. av_buffer_allocz);
  1300. if (!pool->pools[i]) {
  1301. ret = AVERROR(ENOMEM);
  1302. goto fail;
  1303. }
  1304. }
  1305. }
  1306. pool->format = frame->format;
  1307. pool->width = frame->width;
  1308. pool->height = frame->height;
  1309. break;
  1310. }
  1311. case AVMEDIA_TYPE_AUDIO: {
  1312. int ch = frame->channels; //av_get_channel_layout_nb_channels(frame->channel_layout);
  1313. int planar = av_sample_fmt_is_planar(frame->format);
  1314. int planes = planar ? ch : 1;
  1315. if (pool->format == frame->format && pool->planes == planes &&
  1316. pool->channels == ch && frame->nb_samples == pool->samples)
  1317. return 0;
  1318. av_buffer_pool_uninit(&pool->pools[0]);
  1319. ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
  1320. frame->nb_samples, frame->format, 0);
  1321. if (ret < 0)
  1322. goto fail;
  1323. pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
  1324. if (!pool->pools[0]) {
  1325. ret = AVERROR(ENOMEM);
  1326. goto fail;
  1327. }
  1328. pool->format = frame->format;
  1329. pool->planes = planes;
  1330. pool->channels = ch;
  1331. pool->samples = frame->nb_samples;
  1332. break;
  1333. }
  1334. default: av_assert0(0);
  1335. }
  1336. return 0;
  1337. fail:
  1338. for (i = 0; i < 4; i++)
  1339. av_buffer_pool_uninit(&pool->pools[i]);
  1340. pool->format = -1;
  1341. pool->planes = pool->channels = pool->samples = 0;
  1342. pool->width = pool->height = 0;
  1343. return ret;
  1344. }
  1345. static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
  1346. {
  1347. FramePool *pool = avctx->internal->pool;
  1348. int planes = pool->planes;
  1349. int i;
  1350. frame->linesize[0] = pool->linesize[0];
  1351. if (planes > AV_NUM_DATA_POINTERS) {
  1352. frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
  1353. frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
  1354. frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
  1355. sizeof(*frame->extended_buf));
  1356. if (!frame->extended_data || !frame->extended_buf) {
  1357. av_freep(&frame->extended_data);
  1358. av_freep(&frame->extended_buf);
  1359. return AVERROR(ENOMEM);
  1360. }
  1361. } else {
  1362. frame->extended_data = frame->data;
  1363. av_assert0(frame->nb_extended_buf == 0);
  1364. }
  1365. for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
  1366. frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
  1367. if (!frame->buf[i])
  1368. goto fail;
  1369. frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
  1370. }
  1371. for (i = 0; i < frame->nb_extended_buf; i++) {
  1372. frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
  1373. if (!frame->extended_buf[i])
  1374. goto fail;
  1375. frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
  1376. }
  1377. if (avctx->debug & FF_DEBUG_BUFFERS)
  1378. av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
  1379. return 0;
  1380. fail:
  1381. av_frame_unref(frame);
  1382. return AVERROR(ENOMEM);
  1383. }
  1384. static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
  1385. {
  1386. FramePool *pool = s->internal->pool;
  1387. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
  1388. int i;
  1389. if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
  1390. av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
  1391. return -1;
  1392. }
  1393. if (!desc) {
  1394. av_log(s, AV_LOG_ERROR,
  1395. "Unable to get pixel format descriptor for format %s\n",
  1396. av_get_pix_fmt_name(pic->format));
  1397. return AVERROR(EINVAL);
  1398. }
  1399. memset(pic->data, 0, sizeof(pic->data));
  1400. pic->extended_data = pic->data;
  1401. for (i = 0; i < 4 && pool->pools[i]; i++) {
  1402. pic->linesize[i] = pool->linesize[i];
  1403. pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
  1404. if (!pic->buf[i])
  1405. goto fail;
  1406. pic->data[i] = pic->buf[i]->data;
  1407. }
  1408. for (; i < AV_NUM_DATA_POINTERS; i++) {
  1409. pic->data[i] = NULL;
  1410. pic->linesize[i] = 0;
  1411. }
  1412. if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
  1413. ((desc->flags & FF_PSEUDOPAL) && pic->data[1]))
  1414. avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
  1415. if (s->debug & FF_DEBUG_BUFFERS)
  1416. av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
  1417. return 0;
  1418. fail:
  1419. av_frame_unref(pic);
  1420. return AVERROR(ENOMEM);
  1421. }
  1422. int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
  1423. {
  1424. int ret;
  1425. if (avctx->hw_frames_ctx) {
  1426. ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
  1427. frame->width = avctx->coded_width;
  1428. frame->height = avctx->coded_height;
  1429. return ret;
  1430. }
  1431. if ((ret = update_frame_pool(avctx, frame)) < 0)
  1432. return ret;
  1433. switch (avctx->codec_type) {
  1434. case AVMEDIA_TYPE_VIDEO:
  1435. return video_get_buffer(avctx, frame);
  1436. case AVMEDIA_TYPE_AUDIO:
  1437. return audio_get_buffer(avctx, frame);
  1438. default:
  1439. return -1;
  1440. }
  1441. }
  1442. static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
  1443. {
  1444. int size;
  1445. const uint8_t *side_metadata;
  1446. AVDictionary **frame_md = &frame->metadata;
  1447. side_metadata = av_packet_get_side_data(avpkt,
  1448. AV_PKT_DATA_STRINGS_METADATA, &size);
  1449. return av_packet_unpack_dictionary(side_metadata, size, frame_md);
  1450. }
  1451. int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
  1452. {
  1453. const AVPacket *pkt = avctx->internal->last_pkt_props;
  1454. int i;
  1455. static const struct {
  1456. enum AVPacketSideDataType packet;
  1457. enum AVFrameSideDataType frame;
  1458. } sd[] = {
  1459. { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
  1460. { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
  1461. { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
  1462. { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
  1463. { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
  1464. { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
  1465. { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
  1466. { AV_PKT_DATA_A53_CC, AV_FRAME_DATA_A53_CC },
  1467. };
  1468. if (pkt) {
  1469. frame->pts = pkt->pts;
  1470. #if FF_API_PKT_PTS
  1471. FF_DISABLE_DEPRECATION_WARNINGS
  1472. frame->pkt_pts = pkt->pts;
  1473. FF_ENABLE_DEPRECATION_WARNINGS
  1474. #endif
  1475. frame->pkt_pos = pkt->pos;
  1476. frame->pkt_duration = pkt->duration;
  1477. frame->pkt_size = pkt->size;
  1478. for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
  1479. int size;
  1480. uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
  1481. if (packet_sd) {
  1482. AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
  1483. sd[i].frame,
  1484. size);
  1485. if (!frame_sd)
  1486. return AVERROR(ENOMEM);
  1487. memcpy(frame_sd->data, packet_sd, size);
  1488. }
  1489. }
  1490. add_metadata_from_side_data(pkt, frame);
  1491. if (pkt->flags & AV_PKT_FLAG_DISCARD) {
  1492. frame->flags |= AV_FRAME_FLAG_DISCARD;
  1493. } else {
  1494. frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
  1495. }
  1496. }
  1497. frame->reordered_opaque = avctx->reordered_opaque;
  1498. if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
  1499. frame->color_primaries = avctx->color_primaries;
  1500. if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
  1501. frame->color_trc = avctx->color_trc;
  1502. if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
  1503. frame->colorspace = avctx->colorspace;
  1504. if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
  1505. frame->color_range = avctx->color_range;
  1506. if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
  1507. frame->chroma_location = avctx->chroma_sample_location;
  1508. switch (avctx->codec->type) {
  1509. case AVMEDIA_TYPE_VIDEO:
  1510. frame->format = avctx->pix_fmt;
  1511. if (!frame->sample_aspect_ratio.num)
  1512. frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
  1513. if (frame->width && frame->height &&
  1514. av_image_check_sar(frame->width, frame->height,
  1515. frame->sample_aspect_ratio) < 0) {
  1516. av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
  1517. frame->sample_aspect_ratio.num,
  1518. frame->sample_aspect_ratio.den);
  1519. frame->sample_aspect_ratio = (AVRational){ 0, 1 };
  1520. }
  1521. break;
  1522. case AVMEDIA_TYPE_AUDIO:
  1523. if (!frame->sample_rate)
  1524. frame->sample_rate = avctx->sample_rate;
  1525. if (frame->format < 0)
  1526. frame->format = avctx->sample_fmt;
  1527. if (!frame->channel_layout) {
  1528. if (avctx->channel_layout) {
  1529. if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
  1530. avctx->channels) {
  1531. av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
  1532. "configuration.\n");
  1533. return AVERROR(EINVAL);
  1534. }
  1535. frame->channel_layout = avctx->channel_layout;
  1536. } else {
  1537. if (avctx->channels > FF_SANE_NB_CHANNELS) {
  1538. av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
  1539. avctx->channels);
  1540. return AVERROR(ENOSYS);
  1541. }
  1542. }
  1543. }
  1544. frame->channels = avctx->channels;
  1545. break;
  1546. }
  1547. return 0;
  1548. }
  1549. static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
  1550. {
  1551. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  1552. int i;
  1553. int num_planes = av_pix_fmt_count_planes(frame->format);
  1554. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
  1555. int flags = desc ? desc->flags : 0;
  1556. if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
  1557. num_planes = 2;
  1558. if ((flags & FF_PSEUDOPAL) && frame->data[1])
  1559. num_planes = 2;
  1560. for (i = 0; i < num_planes; i++) {
  1561. av_assert0(frame->data[i]);
  1562. }
  1563. // For formats without data like hwaccel allow unused pointers to be non-NULL.
  1564. for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
  1565. if (frame->data[i])
  1566. av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
  1567. frame->data[i] = NULL;
  1568. }
  1569. }
  1570. }
  1571. static void decode_data_free(void *opaque, uint8_t *data)
  1572. {
  1573. FrameDecodeData *fdd = (FrameDecodeData*)data;
  1574. if (fdd->post_process_opaque_free)
  1575. fdd->post_process_opaque_free(fdd->post_process_opaque);
  1576. if (fdd->hwaccel_priv_free)
  1577. fdd->hwaccel_priv_free(fdd->hwaccel_priv);
  1578. av_freep(&fdd);
  1579. }
  1580. int ff_attach_decode_data(AVFrame *frame)
  1581. {
  1582. AVBufferRef *fdd_buf;
  1583. FrameDecodeData *fdd;
  1584. av_assert1(!frame->private_ref);
  1585. av_buffer_unref(&frame->private_ref);
  1586. fdd = av_mallocz(sizeof(*fdd));
  1587. if (!fdd)
  1588. return AVERROR(ENOMEM);
  1589. fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
  1590. NULL, AV_BUFFER_FLAG_READONLY);
  1591. if (!fdd_buf) {
  1592. av_freep(&fdd);
  1593. return AVERROR(ENOMEM);
  1594. }
  1595. frame->private_ref = fdd_buf;
  1596. return 0;
  1597. }
  1598. static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
  1599. {
  1600. const AVHWAccel *hwaccel = avctx->hwaccel;
  1601. int override_dimensions = 1;
  1602. int ret;
  1603. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  1604. if ((ret = av_image_check_size2(FFALIGN(avctx->width, STRIDE_ALIGN), avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
  1605. av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
  1606. return AVERROR(EINVAL);
  1607. }
  1608. if (frame->width <= 0 || frame->height <= 0) {
  1609. frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
  1610. frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
  1611. override_dimensions = 0;
  1612. }
  1613. if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
  1614. av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
  1615. return AVERROR(EINVAL);
  1616. }
  1617. }
  1618. ret = ff_decode_frame_props(avctx, frame);
  1619. if (ret < 0)
  1620. return ret;
  1621. if (hwaccel) {
  1622. if (hwaccel->alloc_frame) {
  1623. ret = hwaccel->alloc_frame(avctx, frame);
  1624. goto end;
  1625. }
  1626. } else
  1627. avctx->sw_pix_fmt = avctx->pix_fmt;
  1628. ret = avctx->get_buffer2(avctx, frame, flags);
  1629. if (ret < 0)
  1630. goto end;
  1631. validate_avframe_allocation(avctx, frame);
  1632. ret = ff_attach_decode_data(frame);
  1633. if (ret < 0)
  1634. goto end;
  1635. end:
  1636. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
  1637. !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
  1638. frame->width = avctx->width;
  1639. frame->height = avctx->height;
  1640. }
  1641. if (ret < 0)
  1642. av_frame_unref(frame);
  1643. return ret;
  1644. }
  1645. int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
  1646. {
  1647. int ret = get_buffer_internal(avctx, frame, flags);
  1648. if (ret < 0) {
  1649. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  1650. frame->width = frame->height = 0;
  1651. }
  1652. return ret;
  1653. }
  1654. static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
  1655. {
  1656. AVFrame *tmp;
  1657. int ret;
  1658. av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
  1659. if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
  1660. av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
  1661. frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
  1662. av_frame_unref(frame);
  1663. }
  1664. if (!frame->data[0])
  1665. return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
  1666. if (av_frame_is_writable(frame))
  1667. return ff_decode_frame_props(avctx, frame);
  1668. tmp = av_frame_alloc();
  1669. if (!tmp)
  1670. return AVERROR(ENOMEM);
  1671. av_frame_move_ref(tmp, frame);
  1672. ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
  1673. if (ret < 0) {
  1674. av_frame_free(&tmp);
  1675. return ret;
  1676. }
  1677. av_frame_copy(frame, tmp);
  1678. av_frame_free(&tmp);
  1679. return 0;
  1680. }
  1681. int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
  1682. {
  1683. int ret = reget_buffer_internal(avctx, frame);
  1684. if (ret < 0)
  1685. av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
  1686. return ret;
  1687. }
  1688. static void bsfs_flush(AVCodecContext *avctx)
  1689. {
  1690. DecodeFilterContext *s = &avctx->internal->filter;
  1691. for (int i = 0; i < s->nb_bsfs; i++)
  1692. av_bsf_flush(s->bsfs[i]);
  1693. }
  1694. void avcodec_flush_buffers(AVCodecContext *avctx)
  1695. {
  1696. avctx->internal->draining = 0;
  1697. avctx->internal->draining_done = 0;
  1698. avctx->internal->nb_draining_errors = 0;
  1699. av_frame_unref(avctx->internal->buffer_frame);
  1700. av_frame_unref(avctx->internal->compat_decode_frame);
  1701. av_packet_unref(avctx->internal->buffer_pkt);
  1702. avctx->internal->buffer_pkt_valid = 0;
  1703. av_packet_unref(avctx->internal->ds.in_pkt);
  1704. if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
  1705. ff_thread_flush(avctx);
  1706. else if (avctx->codec->flush)
  1707. avctx->codec->flush(avctx);
  1708. avctx->pts_correction_last_pts =
  1709. avctx->pts_correction_last_dts = INT64_MIN;
  1710. bsfs_flush(avctx);
  1711. if (!avctx->refcounted_frames)
  1712. av_frame_unref(avctx->internal->to_free);
  1713. }
  1714. void ff_decode_bsfs_uninit(AVCodecContext *avctx)
  1715. {
  1716. DecodeFilterContext *s = &avctx->internal->filter;
  1717. int i;
  1718. for (i = 0; i < s->nb_bsfs; i++)
  1719. av_bsf_free(&s->bsfs[i]);
  1720. av_freep(&s->bsfs);
  1721. s->nb_bsfs = 0;
  1722. }