FFmpeg
Loading...
Searching...
No Matches
libjxldec.c
Go to the documentation of this file.
1/*
2 * JPEG XL decoding support via libjxl
3 * Copyright (c) 2021 Leo Izen <leo.izen@gmail.com>
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22/**
23 * @file
24 * JPEG XL decoder using libjxl
25 */
26
27#include "libavutil/avassert.h"
28#include "libavutil/buffer.h"
29#include "libavutil/common.h"
30#include "libavutil/csp.h"
31#include "libavutil/error.h"
33#include "libavutil/mem.h"
34#include "libavutil/pixdesc.h"
35#include "libavutil/pixfmt.h"
36#include "libavutil/frame.h"
37
38#include "avcodec.h"
39#include "codec_internal.h"
40#include "decode.h"
41#include "exif_internal.h"
42#include "internal.h"
43
44#include <jxl/decode.h>
45#include <jxl/thread_parallel_runner.h>
46#include "libjxl.h"
47
48#define EXIF_MAX_SIZE (16 << 20)
49
50typedef struct LibJxlDecodeContext {
51 void *runner;
52 JxlDecoder *decoder;
53 JxlBasicInfo basic_info;
54 JxlPixelFormat jxl_pixfmt;
55#if JPEGXL_NUMERIC_VERSION >= JPEGXL_COMPUTE_NUMERIC_VERSION(0, 8, 0)
56 JxlBitDepth jxl_bit_depth;
57#endif
58 JxlDecoderStatus events;
67 JxlDecoderStatus jret;
69 size_t exif_pos;
72
74{
76
77 ctx->events = JXL_DEC_BASIC_INFO | JXL_DEC_FULL_IMAGE
78 | JXL_DEC_COLOR_ENCODING | JXL_DEC_FRAME
79 | JXL_DEC_BOX;
80 if (JxlDecoderSubscribeEvents(ctx->decoder, ctx->events) != JXL_DEC_SUCCESS) {
81 av_log(avctx, AV_LOG_ERROR, "Error subscribing to JXL events\n");
82 return AVERROR_EXTERNAL;
83 }
84
85 if (JxlDecoderSetDecompressBoxes(ctx->decoder, JXL_TRUE) != JXL_DEC_SUCCESS) {
86 av_log(avctx, AV_LOG_ERROR, "Error setting compress box mode\n");
87 return AVERROR_EXTERNAL;
88 }
89
90 if (JxlDecoderSetParallelRunner(ctx->decoder, JxlThreadParallelRunner, ctx->runner) != JXL_DEC_SUCCESS) {
91 av_log(avctx, AV_LOG_ERROR, "Failed to set JxlThreadParallelRunner\n");
92 return AVERROR_EXTERNAL;
93 }
94
95 av_buffer_unref(&ctx->exif);
96 memset(&ctx->basic_info, 0, sizeof(JxlBasicInfo));
97 memset(&ctx->jxl_pixfmt, 0, sizeof(JxlPixelFormat));
98 ctx->prev_is_last = 1;
99
100 return 0;
101}
102
104{
106 JxlMemoryManager manager;
107
109 ctx->decoder = JxlDecoderCreate(&manager);
110 if (!ctx->decoder) {
111 av_log(avctx, AV_LOG_ERROR, "Failed to create JxlDecoder\n");
112 return AVERROR_EXTERNAL;
113 }
114
115 ctx->runner = JxlThreadParallelRunnerCreate(&manager, ff_libjxl_get_threadcount(avctx->thread_count));
116 if (!ctx->runner) {
117 av_log(avctx, AV_LOG_ERROR, "Failed to create JxlThreadParallelRunner\n");
118 return AVERROR_EXTERNAL;
119 }
120
121 ctx->avpkt = avctx->internal->in_pkt;
122 ctx->frame = av_frame_alloc();
123 if (!ctx->frame)
124 return AVERROR(ENOMEM);
125
126 return libjxl_init_jxl_decoder(avctx);
127}
128
130{
131 const JxlBasicInfo *basic_info = &ctx->basic_info;
132 JxlPixelFormat *format = &ctx->jxl_pixfmt;
133 format->endianness = JXL_NATIVE_ENDIAN;
134 format->num_channels = basic_info->num_color_channels + (basic_info->alpha_bits > 0);
135#if JPEGXL_NUMERIC_VERSION >= JPEGXL_COMPUTE_NUMERIC_VERSION(0, 8, 0)
136 ctx->jxl_bit_depth.bits_per_sample = avctx->bits_per_raw_sample = basic_info->bits_per_sample;
137 ctx->jxl_bit_depth.type = JXL_BIT_DEPTH_FROM_PIXEL_FORMAT;
138 ctx->jxl_bit_depth.exponent_bits_per_sample = basic_info->exponent_bits_per_sample;
139#endif
140 /* Gray */
141 if (basic_info->num_color_channels == 1) {
142 if (basic_info->bits_per_sample <= 8) {
143 format->data_type = JXL_TYPE_UINT8;
144 return basic_info->alpha_bits ? AV_PIX_FMT_YA8 : AV_PIX_FMT_GRAY8;
145 }
146 if (basic_info->exponent_bits_per_sample || basic_info->bits_per_sample > 16) {
147 if (!basic_info->alpha_bits) {
148 format->data_type = JXL_TYPE_FLOAT;
149 return AV_PIX_FMT_GRAYF32;
150 }
151 av_log(avctx, AV_LOG_WARNING, "Downsampling gray+alpha float to 16-bit integer via libjxl\n");
152 }
153 format->data_type = JXL_TYPE_UINT16;
154 return basic_info->alpha_bits ? AV_PIX_FMT_YA16 : AV_PIX_FMT_GRAY16;
155 }
156 /* rgb only */
157 /* libjxl only supports packed RGB and gray output at the moment */
158 if (basic_info->num_color_channels == 3) {
159 if (basic_info->bits_per_sample <= 8) {
160 format->data_type = JXL_TYPE_UINT8;
161 return basic_info->alpha_bits ? AV_PIX_FMT_RGBA : AV_PIX_FMT_RGB24;
162 }
163 if (basic_info->exponent_bits_per_sample || basic_info->bits_per_sample > 16) {
164 format->data_type = JXL_TYPE_FLOAT;
165 return basic_info->alpha_bits ? AV_PIX_FMT_RGBAF32 : AV_PIX_FMT_RGBF32;
166 }
167 format->data_type = JXL_TYPE_UINT16;
168 return basic_info->alpha_bits ? AV_PIX_FMT_RGBA64 : AV_PIX_FMT_RGB48;
169 }
170
171 return AV_PIX_FMT_NONE;
172}
173
174static enum AVColorPrimaries libjxl_get_primaries(void *avctx, const JxlColorEncoding *jxl_color)
175{
177 enum AVColorPrimaries prim;
178
179 /* libjxl populates these double values even if it uses an enum space */
180 desc.prim.r.x = av_d2q(jxl_color->primaries_red_xy[0], 300000);
181 desc.prim.r.y = av_d2q(jxl_color->primaries_red_xy[1], 300000);
182 desc.prim.g.x = av_d2q(jxl_color->primaries_green_xy[0], 300000);
183 desc.prim.g.y = av_d2q(jxl_color->primaries_green_xy[1], 300000);
184 desc.prim.b.x = av_d2q(jxl_color->primaries_blue_xy[0], 300000);
185 desc.prim.b.y = av_d2q(jxl_color->primaries_blue_xy[1], 300000);
186 desc.wp.x = av_d2q(jxl_color->white_point_xy[0], 300000);
187 desc.wp.y = av_d2q(jxl_color->white_point_xy[1], 300000);
188
190 if (prim == AVCOL_PRI_UNSPECIFIED) {
191 /* try D65 with the same primaries */
192 /* BT.709 uses D65 white point */
194 av_log(avctx, AV_LOG_WARNING, "Changing unknown white point to D65\n");
196 }
197
198 return prim;
199}
200
201static enum AVColorTransferCharacteristic libjxl_get_trc(void *avctx, const JxlColorEncoding *jxl_color)
202{
203 switch (jxl_color->transfer_function) {
204 case JXL_TRANSFER_FUNCTION_709: return AVCOL_TRC_BT709;
205 case JXL_TRANSFER_FUNCTION_LINEAR: return AVCOL_TRC_LINEAR;
206 case JXL_TRANSFER_FUNCTION_SRGB: return AVCOL_TRC_IEC61966_2_1;
207 case JXL_TRANSFER_FUNCTION_PQ: return AVCOL_TRC_SMPTE2084;
208 case JXL_TRANSFER_FUNCTION_DCI: return AVCOL_TRC_SMPTE428;
209 case JXL_TRANSFER_FUNCTION_HLG: return AVCOL_TRC_ARIB_STD_B67;
210 case JXL_TRANSFER_FUNCTION_GAMMA:
211 if (jxl_color->gamma > 0.45355 && jxl_color->gamma < 0.45555)
212 return AVCOL_TRC_GAMMA22;
213 else if (jxl_color->gamma > 0.35614 && jxl_color->gamma < 0.35814)
214 return AVCOL_TRC_GAMMA28;
215 else
216 av_log(avctx, AV_LOG_WARNING, "Unsupported gamma transfer: %f\n", jxl_color->gamma);
217 break;
218 default:
219 av_log(avctx, AV_LOG_WARNING, "Unknown transfer function: %d\n", jxl_color->transfer_function);
220 }
221
223}
224
226{
228 size_t icc_len;
229 JxlDecoderStatus jret;
230 /* an ICC profile is present, and we can meaningfully get it,
231 * because the pixel data is not XYB-encoded */
232#if JPEGXL_NUMERIC_VERSION < JPEGXL_COMPUTE_NUMERIC_VERSION(0, 9, 0)
233 jret = JxlDecoderGetICCProfileSize(ctx->decoder, &ctx->jxl_pixfmt, JXL_COLOR_PROFILE_TARGET_DATA, &icc_len);
234#else
235 jret = JxlDecoderGetICCProfileSize(ctx->decoder, JXL_COLOR_PROFILE_TARGET_DATA, &icc_len);
236#endif
237 if (jret == JXL_DEC_SUCCESS && icc_len > 0) {
238 av_buffer_unref(&ctx->iccp);
239 ctx->iccp = av_buffer_alloc(icc_len);
240 if (!ctx->iccp)
241 return AVERROR(ENOMEM);
242#if JPEGXL_NUMERIC_VERSION < JPEGXL_COMPUTE_NUMERIC_VERSION(0, 9, 0)
243 jret = JxlDecoderGetColorAsICCProfile(ctx->decoder, &ctx->jxl_pixfmt, JXL_COLOR_PROFILE_TARGET_DATA,
244 ctx->iccp->data, icc_len);
245#else
246 jret = JxlDecoderGetColorAsICCProfile(ctx->decoder, JXL_COLOR_PROFILE_TARGET_DATA, ctx->iccp->data, icc_len);
247#endif
248 if (jret != JXL_DEC_SUCCESS) {
249 av_log(avctx, AV_LOG_WARNING, "Unable to obtain ICC Profile\n");
250 av_buffer_unref(&ctx->iccp);
251 }
252 }
253
254 return 0;
255}
256
257/*
258 * There's generally four cases when it comes to decoding a libjxl image
259 * with regard to color encoding:
260 * (a) There is an embedded ICC profile in the image, and the image is XYB-encoded.
261 * (b) There is an embedded ICC profile in the image, and the image is not XYB-encoded.
262 * (c) There is no embedded ICC profile, and FFmpeg supports the tagged colorspace.
263 * (d) There is no embedded ICC profile, and FFmpeg does not support the tagged colorspace.
264 *
265 * In case (b), we forward the pixel data as is and forward the ICC Profile as-is.
266 * In case (c), we request the pixel data in the space it's tagged as,
267 * and tag the space accordingly.
268 * In case (a), libjxl does not support getting the pixel data in the space described by the ICC
269 * profile, so instead we request the pixel data in BT.2020/PQ as it is the widest
270 * space that FFmpeg supports.
271 * In case (d), we also request wide-gamut pixel data as a fallback since FFmpeg doesn't support
272 * the custom primaries tagged in the space.
273 */
275{
277 JxlDecoderStatus jret;
278 int ret;
279 JxlColorEncoding jxl_color;
280 /* set this flag if we need to fall back on wide gamut */
281 int fallback = 0;
282
283#if JPEGXL_NUMERIC_VERSION < JPEGXL_COMPUTE_NUMERIC_VERSION(0, 9, 0)
284 jret = JxlDecoderGetColorAsEncodedProfile(ctx->decoder, NULL, JXL_COLOR_PROFILE_TARGET_ORIGINAL, &jxl_color);
285#else
286 jret = JxlDecoderGetColorAsEncodedProfile(ctx->decoder, JXL_COLOR_PROFILE_TARGET_ORIGINAL, &jxl_color);
287#endif
288 if (jret == JXL_DEC_SUCCESS) {
289 /* enum values describe the colors of this image */
290 jret = JxlDecoderSetPreferredColorProfile(ctx->decoder, &jxl_color);
291 if (jret == JXL_DEC_SUCCESS)
292#if JPEGXL_NUMERIC_VERSION < JPEGXL_COMPUTE_NUMERIC_VERSION(0, 9, 0)
293 jret = JxlDecoderGetColorAsEncodedProfile(ctx->decoder, &ctx->jxl_pixfmt,
294 JXL_COLOR_PROFILE_TARGET_DATA, &jxl_color);
295#else
296 jret = JxlDecoderGetColorAsEncodedProfile(ctx->decoder, JXL_COLOR_PROFILE_TARGET_DATA, &jxl_color);
297#endif
298 /* if we couldn't successfully request the pixel data space, we fall back on wide gamut */
299 /* this code path is very unlikely to happen in practice */
300 if (jret != JXL_DEC_SUCCESS)
301 fallback = 1;
302 } else {
303 /* an ICC Profile is present in the stream */
304 if (ctx->basic_info.uses_original_profile) {
305 /* uses_original_profile is the same as !xyb_encoded */
306 av_log(avctx, AV_LOG_VERBOSE, "Using embedded ICC Profile\n");
307 if ((ret = libjxl_get_icc(avctx)) < 0)
308 return ret;
309 } else {
310 /*
311 * an XYB-encoded image with an embedded ICC profile can't always have the
312 * pixel data requested in the original space, so libjxl has no feature
313 * to allow this to happen, so we fall back on wide gamut
314 */
315 fallback = 1;
316 }
317 }
318
319 avctx->color_range = frame->color_range = AVCOL_RANGE_JPEG;
320 if (ctx->basic_info.num_color_channels > 1)
321 avctx->colorspace = AVCOL_SPC_RGB;
324
325 if (!ctx->iccp) {
326 /* checking enum values */
327 if (!fallback) {
328 if (avctx->colorspace == AVCOL_SPC_RGB)
329 avctx->color_primaries = libjxl_get_primaries(avctx, &jxl_color);
330 avctx->color_trc = libjxl_get_trc(avctx, &jxl_color);
331 }
332 /* fall back on wide gamut if enum values fail */
334 if (avctx->colorspace == AVCOL_SPC_RGB) {
335 av_log(avctx, AV_LOG_WARNING, "Falling back on wide gamut output\n");
336 jxl_color.primaries = JXL_PRIMARIES_2100;
338 }
339 /* libjxl requires this set even for grayscale */
340 jxl_color.white_point = JXL_WHITE_POINT_D65;
341 }
342 if (avctx->color_trc == AVCOL_TRC_UNSPECIFIED) {
343 if (ctx->jxl_pixfmt.data_type == JXL_TYPE_FLOAT
344 || ctx->jxl_pixfmt.data_type == JXL_TYPE_FLOAT16) {
345 av_log(avctx, AV_LOG_WARNING, "Falling back on Linear Light transfer\n");
346 jxl_color.transfer_function = JXL_TRANSFER_FUNCTION_LINEAR;
348 } else {
349 av_log(avctx, AV_LOG_WARNING, "Falling back on iec61966-2-1/sRGB transfer\n");
350 jxl_color.transfer_function = JXL_TRANSFER_FUNCTION_SRGB;
352 }
353 }
354 /* all colors will be in-gamut so we want accurate colors */
355 jxl_color.rendering_intent = JXL_RENDERING_INTENT_RELATIVE;
356 jxl_color.color_space = ctx->basic_info.num_color_channels > 1 ? JXL_COLOR_SPACE_RGB : JXL_COLOR_SPACE_GRAY;
357 jret = JxlDecoderSetPreferredColorProfile(ctx->decoder, &jxl_color);
358 if (jret != JXL_DEC_SUCCESS) {
359 av_log(avctx, AV_LOG_WARNING, "Unable to set fallback color encoding\n");
360 /*
361 * This should only happen if there's a non-XYB encoded image with custom primaries
362 * embedded as enums and no embedded ICC Profile.
363 * In this case, libjxl will synthesize an ICC Profile for us.
364 */
367 if ((ret = libjxl_get_icc(avctx)) < 0)
368 return ret;
369 }
370 }
371
372 frame->color_trc = avctx->color_trc;
373 frame->color_primaries = avctx->color_primaries;
374 frame->colorspace = avctx->colorspace;
375
376 return 0;
377}
378
380{
382 int ret = 0;
383
384 if (ctx->iccp) {
386 if (ret < 0)
387 return ret;
388 }
389
390 if (ctx->exif) {
391 AVExifMetadata ifd = { 0 };
392 /* size may be larger than exif_pos due to the realloc loop */
393 ret = av_exif_parse_buffer(avctx, ctx->exif->data, ctx->exif_pos, &ifd, AV_EXIF_T_OFF);
394 av_buffer_unref(&ctx->exif);
395 if (ret < 0) {
396 av_log(avctx, AV_LOG_ERROR, "Unable to parse EXIF buffer: %s\n", av_err2str(ret));
397 return ret;
398 }
399 /*
400 * JPEG XL Codestream orientation overrides EXIF orientation in all cases.
401 * As a result, we remove the EXIF Orientation tag rather than just zeroing it
402 * in order to prevent any ambiguity. libjxl autorotates the image for us so we
403 * do not need to worry about that.
404 */
405 ret = av_exif_remove_entry(avctx, &ifd, av_exif_get_tag_id("Orientation"), 0);
406 if (ret < 0)
407 av_log(avctx, AV_LOG_WARNING, "Unable to remove orientation from EXIF buffer: %s\n", av_err2str(ret));
408 ret = ff_decode_exif_attach_ifd(avctx, ctx->frame, &ifd);
409 if (ret < 0)
410 av_log(avctx, AV_LOG_ERROR, "Unable to attach EXIF ifd: %s\n", av_err2str(ret));
411 av_exif_free(&ifd);
412 }
413
414 return ret;
415}
416
418{
420 if (ctx->exif_box) {
421 /* last box was Exif */
422 size_t remainder = JxlDecoderReleaseBoxBuffer(ctx->decoder);
423 ctx->exif_pos = ctx->exif->size - remainder;
424 ctx->exif_box = 0;
425 }
426 int ret = libjxl_attach_sidedata(avctx);
428 ctx->frame_complete = 0;
429 return ret;
430}
431
433{
435 int ret;
436 AVPacket *pkt = ctx->avpkt;
437
438 while (1) {
439 size_t remaining;
440 JxlFrameHeader header;
441
442 if (!pkt->size) {
444 ret = ff_decode_get_packet(avctx, pkt);
445 if (ret < 0 && ret != AVERROR_EOF)
446 return ret;
447 ctx->accumulated_pts = 0;
448 ctx->frame_duration = 0;
449 if (!pkt->size) {
450 /* jret set by the last iteration of the loop */
451 if (ctx->jret == JXL_DEC_NEED_MORE_INPUT && !ctx->frame_complete) {
452 av_log(avctx, AV_LOG_ERROR, "Unexpected end of JXL codestream\n");
453 ctx->jret = JXL_DEC_ERROR;
454 return AVERROR_INVALIDDATA;
455 } else if (ctx->frame_complete) {
456 ctx->jret = JXL_DEC_SUCCESS;
457 goto success;
458 }
459 return AVERROR_EOF;
460 }
461 }
462
463 ctx->jret = JxlDecoderSetInput(ctx->decoder, pkt->data, pkt->size);
464 if (ctx->jret == JXL_DEC_ERROR) {
465 /* this should never happen here unless there's a bug in libjxl */
466 av_log(avctx, AV_LOG_ERROR, "Unknown libjxl decode error\n");
467 return AVERROR_EXTERNAL;
468 }
469
470 ctx->jret = JxlDecoderProcessInput(ctx->decoder);
471 /*
472 * JxlDecoderReleaseInput returns the number
473 * of bytes remaining to be read, rather than
474 * the number of bytes that it did read
475 */
476 remaining = JxlDecoderReleaseInput(ctx->decoder);
477 size_t consumed = pkt->size - remaining;
478 pkt->data += consumed;
479 pkt->size = remaining;
480
481 switch(ctx->jret) {
482 case JXL_DEC_ERROR:
483 av_log(avctx, AV_LOG_ERROR, "Unknown libjxl decode error\n");
484 /*
485 * we consume all remaining input on error, if nothing was consumed
486 * this prevents libjxl from consuming nothing forever
487 * and just dumping the last error over and over
488 */
489 if (!consumed)
491 return AVERROR_INVALIDDATA;
492 case JXL_DEC_NEED_MORE_INPUT:
493 av_log(avctx, AV_LOG_DEBUG, "NEED_MORE_INPUT event emitted\n");
494 continue;
495 case JXL_DEC_BASIC_INFO:
496 av_log(avctx, AV_LOG_DEBUG, "BASIC_INFO event emitted\n");
497 if (JxlDecoderGetBasicInfo(ctx->decoder, &ctx->basic_info) != JXL_DEC_SUCCESS) {
498 /*
499 * this should never happen
500 * if it does it is likely a libjxl decoder bug
501 */
502 av_log(avctx, AV_LOG_ERROR, "Bad libjxl basic info event\n");
503 return AVERROR_EXTERNAL;
504 }
505 avctx->pix_fmt = libjxl_get_pix_fmt(avctx, ctx);
506 if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
507 av_log(avctx, AV_LOG_ERROR, "Bad libjxl pixel format\n");
508 return AVERROR_EXTERNAL;
509 }
510 if ((ret = ff_set_dimensions(avctx, ctx->basic_info.xsize, ctx->basic_info.ysize)) < 0)
511 return ret;
512 if (ctx->basic_info.have_animation)
513 ctx->anim_timebase = av_make_q(ctx->basic_info.animation.tps_denominator,
514 ctx->basic_info.animation.tps_numerator);
515 if (ctx->basic_info.alpha_bits) {
516 if (ctx->basic_info.alpha_premultiplied)
518 else
520 }
521 continue;
522 case JXL_DEC_COLOR_ENCODING:
523 av_log(avctx, AV_LOG_DEBUG, "COLOR_ENCODING event emitted\n");
524 ret = libjxl_color_encoding_event(avctx, ctx->frame);
525 if (ret < 0)
526 return ret;
527 continue;
528 case JXL_DEC_NEED_IMAGE_OUT_BUFFER:
529 av_log(avctx, AV_LOG_DEBUG, "NEED_IMAGE_OUT_BUFFER event emitted\n");
530 ret = ff_get_buffer(avctx, ctx->frame, 0);
531 if (ret < 0)
532 return ret;
533 ctx->jxl_pixfmt.align = ctx->frame->linesize[0];
534 if (JxlDecoderSetImageOutBuffer(ctx->decoder, &ctx->jxl_pixfmt,
535 ctx->frame->data[0], ctx->frame->buf[0]->size)
536 != JXL_DEC_SUCCESS) {
537 av_log(avctx, AV_LOG_ERROR, "Bad libjxl dec need image out buffer event\n");
538 return AVERROR_EXTERNAL;
539 }
540#if JPEGXL_NUMERIC_VERSION >= JPEGXL_COMPUTE_NUMERIC_VERSION(0, 8, 0)
541 if (JxlDecoderSetImageOutBitDepth(ctx->decoder, &ctx->jxl_bit_depth) != JXL_DEC_SUCCESS) {
542 av_log(avctx, AV_LOG_ERROR, "Error setting output bit depth\n");
543 return AVERROR_EXTERNAL;
544 }
545#endif
546 continue;
547 case JXL_DEC_FRAME:
548 /* Frame here refers to the Frame bundle, not a decoded picture */
549 av_log(avctx, AV_LOG_DEBUG, "FRAME event emitted\n");
550 if (ctx->prev_is_last) {
551 /*
552 * The last frame sent was tagged as "is_last" which
553 * means this is a new image file altogether.
554 */
555 ctx->frame->pict_type = AV_PICTURE_TYPE_I;
556 ctx->frame->flags |= AV_FRAME_FLAG_KEY;
557 }
558 if (JxlDecoderGetFrameHeader(ctx->decoder, &header) != JXL_DEC_SUCCESS) {
559 av_log(avctx, AV_LOG_ERROR, "Bad libjxl dec frame event\n");
560 return AVERROR_EXTERNAL;
561 }
562 ctx->prev_is_last = header.is_last;
563 /* zero duration for animation means the frame is not presented */
564 if (ctx->basic_info.have_animation && header.duration)
565 ctx->frame_duration = header.duration;
566 continue;
567 case JXL_DEC_FULL_IMAGE:
568 /* full image is one frame, even if animated */
569 av_log(avctx, AV_LOG_DEBUG, "FULL_IMAGE event emitted\n");
570 if (ctx->basic_info.have_animation) {
571 ctx->frame->pts = av_rescale_q(ctx->accumulated_pts, ctx->anim_timebase, avctx->pkt_timebase);
572 ctx->frame->duration = av_rescale_q(ctx->frame_duration, ctx->anim_timebase, avctx->pkt_timebase);
573 } else {
574 ctx->frame->pts = 0;
575 ctx->frame->duration = pkt->duration;
576 }
577 if (pkt->pts != AV_NOPTS_VALUE)
578 ctx->frame->pts += pkt->pts;
579 ctx->accumulated_pts += ctx->frame_duration;
580 ctx->frame->pkt_dts = pkt->dts;
581 if (ctx->basic_info.have_animation && !ctx->prev_is_last) {
582 libjxl_finalize_frame(avctx, frame, ctx->frame);
583 return 0;
584 } else {
585 ctx->frame_complete = 1;
586 continue;
587 }
588 case JXL_DEC_SUCCESS:
589 av_log(avctx, AV_LOG_DEBUG, "SUCCESS event emitted\n");
590 /*
591 * this event will be fired when the zero-length EOF
592 * packet is sent to the decoder by the client,
593 * but it will also be fired when the next image of
594 * an image2pipe sequence is loaded up
595 */
596success:
597 libjxl_finalize_frame(avctx, frame, ctx->frame);
598 JxlDecoderReset(ctx->decoder);
600 return 0;
601 case JXL_DEC_BOX: {
602 char type[4];
603 av_log(avctx, AV_LOG_DEBUG, "BOX event emitted\n");
604 if (ctx->exif_box) {
605 /* last box was Exif */
606 size_t remainder = JxlDecoderReleaseBoxBuffer(ctx->decoder);
607 ctx->exif_pos = ctx->exif->size - remainder;
608 }
609 if (JxlDecoderGetBoxType(ctx->decoder, type, JXL_TRUE) != JXL_DEC_SUCCESS) {
610 av_log(avctx, AV_LOG_ERROR, "Error getting box type\n");
611 return AVERROR_EXTERNAL;
612 }
613 if (AV_RL32(type) != MKTAG('E','x','i','f')) {
614 ctx->exif_box = 0;
615 continue;
616 }
617 ctx->exif_box = 1;
618 av_buffer_unref(&ctx->exif);
619 ctx->exif_pos = 0;
620 // 4k buffer should usually be enough
621 ret = av_buffer_realloc(&ctx->exif, 4096);
622 if (ret < 0)
623 return AVERROR(ENOMEM);
624 if (JxlDecoderSetBoxBuffer(ctx->decoder, ctx->exif->data, ctx->exif->size) != JXL_DEC_SUCCESS) {
625 av_log(avctx, AV_LOG_ERROR, "Error setting box buffer\n");
626 return AVERROR_EXTERNAL;
627 }
628 continue;
629 }
630 case JXL_DEC_BOX_NEED_MORE_OUTPUT: {
631 av_log(avctx, AV_LOG_DEBUG, "BOX_NEED_MORE_OUTPUT event emitted\n");
632 size_t remainder = JxlDecoderReleaseBoxBuffer(ctx->decoder);
633 ctx->exif_pos = ctx->exif->size - remainder;
634 size_t new_size = ctx->exif->size << 1;
635 JxlBoxType type;
636 if (new_size > EXIF_MAX_SIZE &&
637 (JxlDecoderGetBoxType(ctx->decoder, type, JXL_FALSE) != JXL_DEC_SUCCESS ||
638 AV_RL32(type) == MKTAG('b','r','o','b'))) {
639 av_log(avctx, AV_LOG_ERROR, "Compressed Exif box larger than %d bytes\n", EXIF_MAX_SIZE);
640 av_buffer_unref(&ctx->exif);
641 ctx->exif_box = 0;
642 return AVERROR_INVALIDDATA;
643 }
644 ret = av_buffer_realloc(&ctx->exif, new_size);
645 if (ret < 0)
646 return AVERROR(ENOMEM);
647 if (JxlDecoderSetBoxBuffer(ctx->decoder, ctx->exif->data + ctx->exif_pos,
648 ctx->exif->size - ctx->exif_pos) != JXL_DEC_SUCCESS) {
649 av_log(avctx, AV_LOG_ERROR, "Error setting box buffer\n");
650 return AVERROR_EXTERNAL;
651 }
652 continue;
653 }
654 default:
655 av_log(avctx, AV_LOG_ERROR, "Bad libjxl event: %d\n", ctx->jret);
656 return AVERROR_EXTERNAL;
657 }
658 }
659}
660
662{
664
665 if (ctx->runner)
666 JxlThreadParallelRunnerDestroy(ctx->runner);
667 ctx->runner = NULL;
668 if (ctx->decoder)
669 JxlDecoderDestroy(ctx->decoder);
670 ctx->decoder = NULL;
671 av_buffer_unref(&ctx->exif);
672 av_buffer_unref(&ctx->iccp);
673 av_frame_free(&ctx->frame);
674
675 return 0;
676}
677
679 .p.name = "libjxl",
680 CODEC_LONG_NAME("libjxl JPEG XL"),
681 .p.type = AVMEDIA_TYPE_VIDEO,
682 .p.id = AV_CODEC_ID_JPEGXL,
683 .priv_data_size = sizeof(LibJxlDecodeContext),
686 .close = libjxl_decode_close,
688 .caps_internal = FF_CODEC_CAP_NOT_INIT_THREADSAFE |
691 .p.wrapper_name = "libjxl",
692};
693
695 .p.name = "libjxl_anim",
696 CODEC_LONG_NAME("libjxl JPEG XL animated"),
697 .p.type = AVMEDIA_TYPE_VIDEO,
699 .priv_data_size = sizeof(LibJxlDecodeContext),
702 .close = libjxl_decode_close,
704 .caps_internal = FF_CODEC_CAP_NOT_INIT_THREADSAFE |
707 .p.wrapper_name = "libjxl",
708};
uint8_t ptrdiff_t const uint8_t ptrdiff_t int intptr_t intptr_t int int16_t * dst
Definition dsp.h:97
static const char *const format[]
Definition af_aiir.c:445
const FFCodec ff_libjxl_decoder
Definition libjxldec.c:678
const FFCodec ff_libjxl_anim_decoder
Definition libjxldec.c:694
static AVFormatContext * ctx
simple assert() macros that are a bit more flexible than ISO C assert().
Libavcodec external API header.
refcounted data buffer API
#define FF_CODEC_RECEIVE_FRAME_CB(func)
#define FF_CODEC_CAP_NOT_INIT_THREADSAFE
The codec is not known to be init-threadsafe (i.e.
#define FF_CODEC_CAP_ICC_PROFILES
Codec supports embedded ICC profiles (AV_FRAME_DATA_ICC_PROFILE).
#define CODEC_LONG_NAME(str)
#define FF_CODEC_CAP_INIT_CLEANUP
The codec allows calling the close function for deallocation even if the init function returned a fai...
#define FF_CODEC_CAP_AUTO_THREADS
Codec handles avctx->thread_count == 0 (auto) internally.
common internal and external API header
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
Colorspace value utility functions for libavutil.
int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
Get a buffer for a frame.
Definition decode.c:1814
int ff_frame_new_side_data_from_buf(const AVCodecContext *avctx, AVFrame *frame, enum AVFrameSideDataType type, AVBufferRef **buf)
Similar to ff_frame_new_side_data, but using an existing buffer ref.
Definition decode.c:2269
int ff_decode_exif_attach_ifd(AVCodecContext *avctx, AVFrame *frame, const AVExifMetadata *ifd)
Definition decode.c:2544
int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
Called by decoders to get the next packet for decoding.
Definition decode.c:255
int ff_set_dimensions(AVCodecContext *s, int width, int height)
Definition utils.c:91
static AVPacket * pkt
static AVFrame * frame
int(* init)(AVBSFContext *ctx)
Definition dts2pts.c:613
error code definitions
int av_exif_parse_buffer(void *logctx, const uint8_t *buf, size_t size, AVExifMetadata *ifd, enum AVExifHeaderMode header_mode)
Decodes the EXIF data provided in the buffer and writes it into the struct *ifd.
Definition exif.c:902
void av_exif_free(AVExifMetadata *ifd)
Frees all resources associated with the given EXIF metadata struct.
Definition exif.c:679
int32_t av_exif_get_tag_id(const char *name)
Retrieves the tag ID associated with the provided tag string name.
Definition exif.c:245
int av_exif_remove_entry(void *logctx, AVExifMetadata *ifd, uint16_t id, int flags)
Remove an entry from the provided EXIF metadata struct.
Definition exif.c:1303
@ AV_EXIF_T_OFF
The first four bytes point to the actual start, then it's AV_EXIF_TIFF_HEADER.
Definition exif.h:68
EXIF metadata parser - internal functions.
int ret
Definition ffplay.c:391
reference-counted frame API
#define AV_CODEC_CAP_OTHER_THREADS
Codec supports multithreading through a method other than slice- or frame-level multithreading.
Definition codec.h:112
#define AV_CODEC_CAP_DR1
Codec uses get_buffer() or get_encode_buffer() for allocating buffers and supports custom allocators.
Definition codec.h:49
@ AV_CODEC_ID_JPEGXL_ANIM
Definition codec_id.h:322
@ AV_CODEC_ID_JPEGXL
Definition codec_id.h:308
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition packet.c:435
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it.
Definition buffer.c:140
int av_buffer_realloc(AVBufferRef **pbuf, size_t size)
Reallocate a given buffer.
Definition buffer.c:184
AVBufferRef * av_buffer_alloc(size_t size)
Allocate an AVBuffer of the given size using av_malloc().
Definition buffer.c:78
#define AVERROR_EXTERNAL
Generic error in an external library.
Definition error.h:59
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR_EOF
End of file.
Definition error.h:57
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition error.h:122
#define AVERROR(e)
Definition error.h:45
#define AV_FRAME_FLAG_KEY
A flag to mark frames that are keyframes.
Definition frame.h:694
void av_frame_move_ref(AVFrame *dst, AVFrame *src)
Move everything contained in src to dst and reset src.
Definition frame.c:526
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition frame.c:65
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition frame.c:53
@ AV_FRAME_DATA_ICC_PROFILE
The data contains an ICC profile as an opaque octet buffer following the format described by ISO 1507...
Definition frame.h:144
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_VERBOSE
Detailed information.
Definition log.h:226
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
enum AVColorPrimaries av_csp_primaries_id_from_desc(const AVColorPrimariesDesc *prm)
Detects which enum AVColorPrimaries constant corresponds to the given complete gamut description.
Definition csp.c:115
const AVColorPrimariesDesc * av_csp_primaries_desc_from_id(enum AVColorPrimaries prm)
Retrieves a complete gamut description from an enum constant describing the color primaries.
Definition csp.c:95
static AVRational av_make_q(int num, int den)
Create an AVRational.
Definition rational.h:71
AVRational av_d2q(double d, int max)
Convert a double precision floating point number to a rational.
Definition rational.c:110
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
@ AV_PICTURE_TYPE_I
Intra.
Definition avutil.h:278
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition avutil.h:247
#define AV_RL32(p)
enum MPFType type
Definition jpegmpfenc.c:55
common internal api header.
#define av_cold
Definition attributes.h:117
size_t ff_libjxl_get_threadcount(int threads)
Transform threadcount in ffmpeg to one used by libjxl.
Definition libjxl.c:33
void ff_libjxl_init_memory_manager(JxlMemoryManager *manager)
Initialize and populate a JxlMemoryManager with av_malloc() and av_free() so libjxl will use these fu...
Definition libjxl.c:65
JPEG XL via libjxl common support header.
static int libjxl_finalize_frame(AVCodecContext *avctx, AVFrame *dst, AVFrame *src)
Definition libjxldec.c:417
static int libjxl_attach_sidedata(AVCodecContext *avctx)
Definition libjxldec.c:379
static av_cold int libjxl_decode_init(AVCodecContext *avctx)
Definition libjxldec.c:103
static enum AVPixelFormat libjxl_get_pix_fmt(AVCodecContext *avctx, LibJxlDecodeContext *ctx)
Definition libjxldec.c:129
static int libjxl_get_icc(AVCodecContext *avctx)
Definition libjxldec.c:225
static av_cold int libjxl_decode_close(AVCodecContext *avctx)
Definition libjxldec.c:661
static int libjxl_color_encoding_event(AVCodecContext *avctx, AVFrame *frame)
Definition libjxldec.c:274
#define EXIF_MAX_SIZE
Definition libjxldec.c:48
static int libjxl_receive_frame(AVCodecContext *avctx, AVFrame *frame)
Definition libjxldec.c:432
static int libjxl_init_jxl_decoder(AVCodecContext *avctx)
Definition libjxldec.c:73
static enum AVColorPrimaries libjxl_get_primaries(void *avctx, const JxlColorEncoding *jxl_color)
Definition libjxldec.c:174
static enum AVColorTransferCharacteristic libjxl_get_trc(void *avctx, const JxlColorEncoding *jxl_color)
Definition libjxldec.c:201
const char * desc
Definition libsvtav1.c:110
#define MKTAG(a, b, c, d)
Definition macros.h:55
Memory handling functions.
pixel format definitions
#define AV_PIX_FMT_RGBF32
Definition pixfmt.h:637
#define AV_PIX_FMT_RGBAF32
Definition pixfmt.h:638
@ AVCOL_RANGE_JPEG
Full range content.
Definition pixfmt.h:792
#define AV_PIX_FMT_YA16
Definition pixfmt.h:533
@ AVALPHA_MODE_STRAIGHT
Alpha channel is independent of color values.
Definition pixfmt.h:828
@ AVALPHA_MODE_PREMULTIPLIED
Alpha channel is multiplied into color values.
Definition pixfmt.h:827
#define AV_PIX_FMT_RGBA64
Definition pixfmt.h:538
#define AV_PIX_FMT_RGB48
Definition pixfmt.h:534
#define AV_PIX_FMT_GRAYF32
Definition pixfmt.h:591
AVPixelFormat
Pixel format.
Definition pixfmt.h:71
@ AV_PIX_FMT_NONE
Definition pixfmt.h:72
@ AV_PIX_FMT_RGB24
packed RGB 8:8:8, 24bpp, RGBRGB...
Definition pixfmt.h:75
@ AV_PIX_FMT_GRAY8
Y , 8bpp.
Definition pixfmt.h:81
@ AV_PIX_FMT_RGBA
packed RGBA 8:8:8:8, 32bpp, RGBARGBA...
Definition pixfmt.h:100
@ AV_PIX_FMT_YA8
8 bits gray, 8 bits alpha
Definition pixfmt.h:140
#define AV_PIX_FMT_GRAY16
Definition pixfmt.h:531
AVColorPrimaries
Chromaticity coordinates of the source primaries.
Definition pixfmt.h:647
@ AVCOL_PRI_BT709
also ITU-R BT1361 / IEC 61966-2-4 / SMPTE RP 177 Annex B
Definition pixfmt.h:649
@ AVCOL_PRI_UNSPECIFIED
Definition pixfmt.h:650
@ AVCOL_PRI_BT2020
ITU-R BT2020.
Definition pixfmt.h:658
AVColorTransferCharacteristic
Color Transfer Characteristic.
Definition pixfmt.h:677
@ AVCOL_TRC_SMPTE2084
SMPTE ST 2084 for 10-, 12-, 14- and 16-bit systems.
Definition pixfmt.h:694
@ AVCOL_TRC_GAMMA22
also ITU-R BT470M / ITU-R BT1700 625 PAL & SECAM
Definition pixfmt.h:682
@ AVCOL_TRC_LINEAR
"Linear transfer characteristics"
Definition pixfmt.h:686
@ AVCOL_TRC_GAMMA28
also ITU-R BT470BG
Definition pixfmt.h:683
@ AVCOL_TRC_ARIB_STD_B67
ARIB STD-B67, known as "Hybrid log-gamma".
Definition pixfmt.h:698
@ AVCOL_TRC_SMPTE428
SMPTE ST 428-1.
Definition pixfmt.h:696
@ AVCOL_TRC_IEC61966_2_1
IEC 61966-2-1 (sRGB or sYCC)
Definition pixfmt.h:691
@ AVCOL_TRC_UNSPECIFIED
Definition pixfmt.h:680
@ AVCOL_TRC_BT709
also ITU-R BT1361
Definition pixfmt.h:679
@ AVCOL_SPC_RGB
order of coefficients is actually GBR, also IEC 61966-2-1 (sRGB), YZX and ST 428-1
Definition pixfmt.h:712
static const uint8_t header[24]
Definition sdr2.c:68
A reference to a data buffer.
Definition buffer.h:82
main external API structure.
Definition avcodec.h:443
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition avcodec.h:644
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition avcodec.h:685
AVRational pkt_timebase
Timebase in which pkt_dts/pts and AVPacket.dts/pts are expressed.
Definition avcodec.h:554
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
Definition avcodec.h:658
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition avcodec.h:1581
enum AVColorSpace colorspace
YUV colorspace type.
Definition avcodec.h:672
int thread_count
thread count is used to decide how many independent tasks should be passed to execute()
Definition avcodec.h:1589
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
Definition avcodec.h:665
enum AVAlphaMode alpha_mode
Indicates how the alpha channel of the video is represented.
Definition avcodec.h:1947
struct AVCodecInternal * internal
Private context used for internal data.
Definition avcodec.h:478
void * priv_data
Definition avcodec.h:470
AVPacket * in_pkt
This packet is used to hold the packet given to decoders implementing the .decode API; it is unused b...
Definition internal.h:83
Struct that contains both white point location and primaries location, providing the complete descrip...
Definition csp.h:78
AVWhitepointCoefficients wp
Definition csp.h:79
This structure describes decoded (raw) audio or video data.
Definition frame.h:479
This structure stores compressed data.
Definition packet.h:587
Rational number (pair of numerator and denominator).
Definition rational.h:58
int64_t frame_duration
Definition libjxldec.c:62
AVPacket * avpkt
Definition libjxldec.c:60
JxlBitDepth jxl_bit_depth
Definition libjxldec.c:56
JxlDecoderStatus events
Definition libjxldec.c:58
AVRational anim_timebase
Definition libjxldec.c:64
JxlBasicInfo basic_info
Definition libjxldec.c:53
JxlDecoder * decoder
Definition libjxldec.c:52
AVBufferRef * exif
Definition libjxldec.c:68
JxlDecoderStatus jret
Definition libjxldec.c:67
JxlPixelFormat jxl_pixfmt
Definition libjxldec.c:54
int64_t accumulated_pts
Definition libjxldec.c:61
AVBufferRef * iccp
Definition libjxldec.c:59
#define av_log(a,...)
#define src
Definition vp8dsp.c:248