1 #include "vaapi_jpeg_decoder.h"
3 #include "jpeg_destroyer.h"
4 #include "jpeg_frame.h"
5 #include "jpeglib_error_wrapper.h"
6 #include "shared/memcpy_interleaved.h"
22 #include <va/va_drm.h>
23 #include <va/va_x11.h>
27 static unique_ptr<VADisplayWithCleanup> va_dpy;
28 static VAConfigID config_id;
29 static VAImageFormat uyvy_format;
30 bool vaapi_jpeg_decoding_usable = false;
33 unsigned width, height;
38 static list<VAResources> va_resources_freelist;
39 static mutex va_resources_mutex;
41 #define CHECK_VASTATUS(va_status, func) \
42 if (va_status != VA_STATUS_SUCCESS) { \
43 fprintf(stderr, "%s:%d (%s) failed with %d\n", __func__, __LINE__, func, va_status); \
47 #define CHECK_VASTATUS_RET(va_status, func) \
48 if (va_status != VA_STATUS_SUCCESS) { \
49 fprintf(stderr, "%s:%d (%s) failed with %d\n", __func__, __LINE__, func, va_status); \
53 // From libjpeg (although it's of course identical between implementations).
54 static const int jpeg_natural_order[DCTSIZE2] = {
55 0, 1, 8, 16, 9, 2, 3, 10,
56 17, 24, 32, 25, 18, 11, 4, 5,
57 12, 19, 26, 33, 40, 48, 41, 34,
58 27, 20, 13, 6, 7, 14, 21, 28,
59 35, 42, 49, 56, 57, 50, 43, 36,
60 29, 22, 15, 23, 30, 37, 44, 51,
61 58, 59, 52, 45, 38, 31, 39, 46,
62 53, 60, 61, 54, 47, 55, 62, 63,
65 VAResources get_va_resources(unsigned width, unsigned height)
68 lock_guard<mutex> lock(va_resources_mutex);
69 for (auto it = va_resources_freelist.begin(); it != va_resources_freelist.end(); ++it) {
70 if (it->width == width && it->height == height) {
71 VAResources ret = *it;
72 va_resources_freelist.erase(it);
83 VAStatus va_status = vaCreateSurfaces(va_dpy->va_dpy, VA_RT_FORMAT_YUV422,
85 &ret.surface, 1, nullptr, 0);
86 CHECK_VASTATUS(va_status, "vaCreateSurfaces");
88 va_status = vaCreateContext(va_dpy->va_dpy, config_id, width, height, 0, &ret.surface, 1, &ret.context);
89 CHECK_VASTATUS(va_status, "vaCreateContext");
91 va_status = vaCreateImage(va_dpy->va_dpy, &uyvy_format, width, height, &ret.image);
92 CHECK_VASTATUS(va_status, "vaCreateImage");
97 void release_va_resources(VAResources resources)
99 lock_guard<mutex> lock(va_resources_mutex);
100 if (va_resources_freelist.size() > 10) {
101 auto it = va_resources_freelist.end();
104 VAStatus va_status = vaDestroyImage(va_dpy->va_dpy, it->image.image_id);
105 CHECK_VASTATUS(va_status, "vaDestroyImage");
107 va_status = vaDestroyContext(va_dpy->va_dpy, it->context);
108 CHECK_VASTATUS(va_status, "vaDestroyContext");
110 va_status = vaDestroySurfaces(va_dpy->va_dpy, &it->surface, 1);
111 CHECK_VASTATUS(va_status, "vaDestroySurfaces");
113 va_resources_freelist.erase(it);
116 va_resources_freelist.push_front(resources);
119 // RAII wrapper to release VAResources on return (even on error).
120 class ReleaseVAResources {
122 ReleaseVAResources(const VAResources &resources)
123 : resources(resources) {}
124 ~ReleaseVAResources()
127 release_va_resources(resources);
131 void commit() { committed = true; }
134 const VAResources &resources;
135 bool committed = false;
138 VADisplayWithCleanup::~VADisplayWithCleanup()
140 if (va_dpy != nullptr) {
143 if (x11_display != nullptr) {
144 XCloseDisplay(x11_display);
151 unique_ptr<VADisplayWithCleanup> va_open_display(const string &va_display)
153 if (va_display.empty() || va_display[0] != '/') { // An X display.
154 Display *x11_display = XOpenDisplay(va_display.empty() ? nullptr : va_display.c_str());
155 if (x11_display == nullptr) {
156 fprintf(stderr, "error: can't connect to X server!\n");
160 unique_ptr<VADisplayWithCleanup> ret(new VADisplayWithCleanup);
161 ret->x11_display = x11_display;
162 ret->va_dpy = vaGetDisplay(x11_display);
163 if (ret->va_dpy == nullptr) {
167 } else { // A DRM node on the filesystem (e.g. /dev/dri/renderD128).
168 int drm_fd = open(va_display.c_str(), O_RDWR);
170 perror(va_display.c_str());
173 unique_ptr<VADisplayWithCleanup> ret(new VADisplayWithCleanup);
174 ret->drm_fd = drm_fd;
175 ret->va_dpy = vaGetDisplayDRM(drm_fd);
176 if (ret->va_dpy == nullptr) {
183 unique_ptr<VADisplayWithCleanup> try_open_va(const string &va_display, string *error)
185 unique_ptr<VADisplayWithCleanup> va_dpy = va_open_display(va_display);
186 if (va_dpy == nullptr) {
188 *error = "Opening VA display failed";
191 int major_ver, minor_ver;
192 VAStatus va_status = vaInitialize(va_dpy->va_dpy, &major_ver, &minor_ver);
193 if (va_status != VA_STATUS_SUCCESS) {
195 snprintf(buf, sizeof(buf), "vaInitialize() failed with status %d\n", va_status);
196 if (error != nullptr)
201 int num_entrypoints = vaMaxNumEntrypoints(va_dpy->va_dpy);
202 unique_ptr<VAEntrypoint[]> entrypoints(new VAEntrypoint[num_entrypoints]);
203 if (entrypoints == nullptr) {
204 if (error != nullptr)
205 *error = "Failed to allocate memory for VA entry points";
209 vaQueryConfigEntrypoints(va_dpy->va_dpy, VAProfileJPEGBaseline, entrypoints.get(), &num_entrypoints);
210 for (int slice_entrypoint = 0; slice_entrypoint < num_entrypoints; slice_entrypoint++) {
211 if (entrypoints[slice_entrypoint] != VAEntrypointVLD) {
215 // We found a usable decode, so return it.
219 if (error != nullptr)
220 *error = "Can't find VAEntrypointVLD for the JPEG profile";
224 string get_usable_va_display()
226 // Reduce the amount of chatter while probing,
227 // unless the user has specified otherwise.
228 bool need_env_reset = false;
229 if (getenv("LIBVA_MESSAGING_LEVEL") == nullptr) {
230 setenv("LIBVA_MESSAGING_LEVEL", "0", true);
231 need_env_reset = true;
234 // First try the default (ie., whatever $DISPLAY is set to).
235 unique_ptr<VADisplayWithCleanup> va_dpy = try_open_va("", nullptr);
236 if (va_dpy != nullptr) {
237 if (need_env_reset) {
238 unsetenv("LIBVA_MESSAGING_LEVEL");
243 fprintf(stderr, "The X11 display did not expose a VA-API JPEG decoder.\n");
245 // Try all /dev/dri/render* in turn. TODO: Accept /dev/dri/card*, too?
247 int err = glob("/dev/dri/renderD*", 0, nullptr, &g);
249 fprintf(stderr, "Couldn't list render nodes (%s) when trying to autodetect a replacement.\n", strerror(errno));
251 for (size_t i = 0; i < g.gl_pathc; ++i) {
252 string path = g.gl_pathv[i];
253 va_dpy = try_open_va(path, nullptr);
254 if (va_dpy != nullptr) {
255 fprintf(stderr, "Autodetected %s as a suitable replacement; using it.\n",
258 if (need_env_reset) {
259 unsetenv("LIBVA_MESSAGING_LEVEL");
266 fprintf(stderr, "No suitable VA-API JPEG decoders were found in /dev/dri; giving up.\n");
267 fprintf(stderr, "Note that if you are using an Intel CPU with an external GPU,\n");
268 fprintf(stderr, "you may need to enable the integrated Intel GPU in your BIOS\n");
269 fprintf(stderr, "to expose Quick Sync.\n");
273 void init_jpeg_vaapi()
275 string dpy = get_usable_va_display();
280 va_dpy = try_open_va(dpy, nullptr);
281 if (va_dpy == nullptr) {
285 VAConfigAttrib attr = { VAConfigAttribRTFormat, VA_RT_FORMAT_YUV422 };
287 VAStatus va_status = vaCreateConfig(va_dpy->va_dpy, VAProfileJPEGBaseline, VAEntrypointVLD,
288 &attr, 1, &config_id);
289 CHECK_VASTATUS(va_status, "vaCreateConfig");
291 int num_formats = vaMaxNumImageFormats(va_dpy->va_dpy);
292 assert(num_formats > 0);
294 unique_ptr<VAImageFormat[]> formats(new VAImageFormat[num_formats]);
295 va_status = vaQueryImageFormats(va_dpy->va_dpy, formats.get(), &num_formats);
296 CHECK_VASTATUS(va_status, "vaQueryImageFormats");
299 for (int i = 0; i < num_formats; ++i) {
300 // Seemingly VA_FOURCC_422H is no good for vaGetImage(). :-/
301 if (formats[i].fourcc == VA_FOURCC_UYVY) {
302 memcpy(&uyvy_format, &formats[i], sizeof(VAImageFormat));
311 fprintf(stderr, "VA-API JPEG decoding initialized.\n");
312 vaapi_jpeg_decoding_usable = true;
315 class VABufferDestroyer {
317 VABufferDestroyer(VADisplay dpy, VABufferID buf)
318 : dpy(dpy), buf(buf) {}
322 VAStatus va_status = vaDestroyBuffer(dpy, buf);
323 CHECK_VASTATUS(va_status, "vaDestroyBuffer");
331 shared_ptr<Frame> decode_jpeg_vaapi(const string &jpeg)
333 jpeg_decompress_struct dinfo;
334 JPEGWrapErrorManager error_mgr(&dinfo);
335 if (!error_mgr.run([&dinfo] { jpeg_create_decompress(&dinfo); })) {
338 JPEGDestroyer destroy_dinfo(&dinfo);
340 jpeg_save_markers(&dinfo, JPEG_APP0 + 1, 0xFFFF);
342 jpeg_mem_src(&dinfo, reinterpret_cast<const unsigned char *>(jpeg.data()), jpeg.size());
343 if (!error_mgr.run([&dinfo] { jpeg_read_header(&dinfo, true); })) {
347 if (dinfo.num_components != 3) {
348 fprintf(stderr, "Not a color JPEG. (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
349 dinfo.num_components,
350 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
351 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
352 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
355 if (dinfo.comp_info[0].h_samp_factor != 2 ||
356 dinfo.comp_info[1].h_samp_factor != 1 ||
357 dinfo.comp_info[1].v_samp_factor != dinfo.comp_info[0].v_samp_factor ||
358 dinfo.comp_info[2].h_samp_factor != 1 ||
359 dinfo.comp_info[2].v_samp_factor != dinfo.comp_info[0].v_samp_factor) {
360 fprintf(stderr, "Not 4:2:2. (Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
361 dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
362 dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
363 dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
367 // Picture parameters.
368 VAPictureParameterBufferJPEGBaseline pic_param;
369 memset(&pic_param, 0, sizeof(pic_param));
370 pic_param.picture_width = dinfo.image_width;
371 pic_param.picture_height = dinfo.image_height;
372 for (int component_idx = 0; component_idx < dinfo.num_components; ++component_idx) {
373 const jpeg_component_info *comp = &dinfo.comp_info[component_idx];
374 pic_param.components[component_idx].component_id = comp->component_id;
375 pic_param.components[component_idx].h_sampling_factor = comp->h_samp_factor;
376 pic_param.components[component_idx].v_sampling_factor = comp->v_samp_factor;
377 pic_param.components[component_idx].quantiser_table_selector = comp->quant_tbl_no;
379 pic_param.num_components = dinfo.num_components;
380 pic_param.color_space = 0; // YUV.
381 pic_param.rotation = VA_ROTATION_NONE;
383 VABufferID pic_param_buffer;
384 VAStatus va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAPictureParameterBufferType, sizeof(pic_param), 1, &pic_param, &pic_param_buffer);
385 CHECK_VASTATUS_RET(va_status, "vaCreateBuffer");
386 VABufferDestroyer destroy_pic_param(va_dpy->va_dpy, pic_param_buffer);
388 // Quantization matrices.
389 VAIQMatrixBufferJPEGBaseline iq;
390 memset(&iq, 0, sizeof(iq));
392 for (int quant_tbl_idx = 0; quant_tbl_idx < min(4, NUM_QUANT_TBLS); ++quant_tbl_idx) {
393 const JQUANT_TBL *qtbl = dinfo.quant_tbl_ptrs[quant_tbl_idx];
394 if (qtbl == nullptr) {
395 iq.load_quantiser_table[quant_tbl_idx] = 0;
397 iq.load_quantiser_table[quant_tbl_idx] = 1;
398 for (int i = 0; i < 64; ++i) {
399 if (qtbl->quantval[i] > 255) {
400 fprintf(stderr, "Baseline JPEG only!\n");
403 iq.quantiser_table[quant_tbl_idx][i] = qtbl->quantval[jpeg_natural_order[i]];
408 VABufferID iq_buffer;
409 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAIQMatrixBufferType, sizeof(iq), 1, &iq, &iq_buffer);
410 CHECK_VASTATUS_RET(va_status, "vaCreateBuffer");
411 VABufferDestroyer destroy_iq(va_dpy->va_dpy, iq_buffer);
413 // Huffman tables (arithmetic is not supported).
414 VAHuffmanTableBufferJPEGBaseline huff;
415 memset(&huff, 0, sizeof(huff));
417 for (int huff_tbl_idx = 0; huff_tbl_idx < min(2, NUM_HUFF_TBLS); ++huff_tbl_idx) {
418 const JHUFF_TBL *ac_hufftbl = dinfo.ac_huff_tbl_ptrs[huff_tbl_idx];
419 const JHUFF_TBL *dc_hufftbl = dinfo.dc_huff_tbl_ptrs[huff_tbl_idx];
420 if (ac_hufftbl == nullptr) {
421 assert(dc_hufftbl == nullptr);
422 huff.load_huffman_table[huff_tbl_idx] = 0;
424 assert(dc_hufftbl != nullptr);
425 huff.load_huffman_table[huff_tbl_idx] = 1;
427 for (int i = 0; i < 16; ++i) {
428 huff.huffman_table[huff_tbl_idx].num_dc_codes[i] = dc_hufftbl->bits[i + 1];
430 for (int i = 0; i < 12; ++i) {
431 huff.huffman_table[huff_tbl_idx].dc_values[i] = dc_hufftbl->huffval[i];
433 for (int i = 0; i < 16; ++i) {
434 huff.huffman_table[huff_tbl_idx].num_ac_codes[i] = ac_hufftbl->bits[i + 1];
436 for (int i = 0; i < 162; ++i) {
437 huff.huffman_table[huff_tbl_idx].ac_values[i] = ac_hufftbl->huffval[i];
442 VABufferID huff_buffer;
443 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VAHuffmanTableBufferType, sizeof(huff), 1, &huff, &huff_buffer);
444 CHECK_VASTATUS_RET(va_status, "vaCreateBuffer");
445 VABufferDestroyer destroy_huff(va_dpy->va_dpy, huff_buffer);
447 // Slice parameters (metadata about the slice).
448 VASliceParameterBufferJPEGBaseline parms;
449 memset(&parms, 0, sizeof(parms));
450 parms.slice_data_size = dinfo.src->bytes_in_buffer;
451 parms.slice_data_offset = 0;
452 parms.slice_data_flag = VA_SLICE_DATA_FLAG_ALL;
453 parms.slice_horizontal_position = 0;
454 parms.slice_vertical_position = 0;
455 for (int component_idx = 0; component_idx < dinfo.num_components; ++component_idx) {
456 const jpeg_component_info *comp = &dinfo.comp_info[component_idx];
457 parms.components[component_idx].component_selector = comp->component_id;
458 parms.components[component_idx].dc_table_selector = comp->dc_tbl_no;
459 parms.components[component_idx].ac_table_selector = comp->ac_tbl_no;
460 if (parms.components[component_idx].dc_table_selector > 1 ||
461 parms.components[component_idx].ac_table_selector > 1) {
462 fprintf(stderr, "Uses too many Huffman tables\n");
466 parms.num_components = dinfo.num_components;
467 parms.restart_interval = dinfo.restart_interval;
468 int horiz_mcus = (dinfo.image_width + (DCTSIZE * 2) - 1) / (DCTSIZE * 2);
469 int vert_mcus = (dinfo.image_height + DCTSIZE - 1) / DCTSIZE;
470 parms.num_mcus = horiz_mcus * vert_mcus;
472 VABufferID slice_param_buffer;
473 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VASliceParameterBufferType, sizeof(parms), 1, &parms, &slice_param_buffer);
474 CHECK_VASTATUS_RET(va_status, "vaCreateBuffer");
475 VABufferDestroyer destroy_slice_param(va_dpy->va_dpy, slice_param_buffer);
477 // The actual data. VA-API will destuff and all for us.
478 VABufferID data_buffer;
479 va_status = vaCreateBuffer(va_dpy->va_dpy, config_id, VASliceDataBufferType, dinfo.src->bytes_in_buffer, 1, const_cast<unsigned char *>(dinfo.src->next_input_byte), &data_buffer);
480 CHECK_VASTATUS_RET(va_status, "vaCreateBuffer");
481 VABufferDestroyer destroy_data(va_dpy->va_dpy, data_buffer);
483 VAResources resources = get_va_resources(dinfo.image_width, dinfo.image_height);
484 ReleaseVAResources release(resources);
486 va_status = vaBeginPicture(va_dpy->va_dpy, resources.context, resources.surface);
487 CHECK_VASTATUS_RET(va_status, "vaBeginPicture");
488 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &pic_param_buffer, 1);
489 CHECK_VASTATUS_RET(va_status, "vaRenderPicture(pic_param)");
490 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &iq_buffer, 1);
491 CHECK_VASTATUS_RET(va_status, "vaRenderPicture(iq)");
492 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &huff_buffer, 1);
493 CHECK_VASTATUS_RET(va_status, "vaRenderPicture(huff)");
494 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &slice_param_buffer, 1);
495 CHECK_VASTATUS_RET(va_status, "vaRenderPicture(slice_param)");
496 va_status = vaRenderPicture(va_dpy->va_dpy, resources.context, &data_buffer, 1);
497 CHECK_VASTATUS_RET(va_status, "vaRenderPicture(data)");
498 va_status = vaEndPicture(va_dpy->va_dpy, resources.context);
499 CHECK_VASTATUS_RET(va_status, "vaEndPicture");
501 // vaDeriveImage() works, but the resulting image seems to live in
502 // uncached memory, which makes copying data out from it very, very slow.
503 // Thanks to FFmpeg for the observation that you can vaGetImage() the
504 // surface onto your own image (although then, it can't be planar, which
505 // is unfortunate for us).
508 va_status = vaDeriveImage(va_dpy->va_dpy, surf, &image);
509 CHECK_VASTATUS_RET(va_status, "vaDeriveImage");
511 va_status = vaSyncSurface(va_dpy->va_dpy, resources.surface);
512 CHECK_VASTATUS_RET(va_status, "vaSyncSurface");
514 va_status = vaGetImage(va_dpy->va_dpy, resources.surface, 0, 0, dinfo.image_width, dinfo.image_height, resources.image.image_id);
515 CHECK_VASTATUS_RET(va_status, "vaGetImage");
519 va_status = vaMapBuffer(va_dpy->va_dpy, resources.image.buf, &mapped);
520 CHECK_VASTATUS_RET(va_status, "vaMapBuffer");
522 shared_ptr<Frame> frame(new Frame);
524 // 4:2:2 planar (for vaDeriveImage).
525 frame->y.reset(new uint8_t[dinfo.image_width * dinfo.image_height]);
526 frame->cb.reset(new uint8_t[(dinfo.image_width / 2) * dinfo.image_height]);
527 frame->cr.reset(new uint8_t[(dinfo.image_width / 2) * dinfo.image_height]);
528 for (int component_idx = 0; component_idx < dinfo.num_components; ++component_idx) {
531 if (component_idx == 0) {
532 dptr = frame->y.get();
533 width = dinfo.image_width;
534 } else if (component_idx == 1) {
535 dptr = frame->cb.get();
536 width = dinfo.image_width / 2;
537 } else if (component_idx == 2) {
538 dptr = frame->cr.get();
539 width = dinfo.image_width / 2;
543 const uint8_t *sptr = (const uint8_t *)mapped + image.offsets[component_idx];
544 size_t spitch = image.pitches[component_idx];
545 for (size_t y = 0; y < dinfo.image_height; ++y) {
546 memcpy(dptr + y * width, sptr + y * spitch, width);
550 // Convert Y'CbCr to separate Y' and CbCr.
551 frame->is_semiplanar = true;
552 frame->y.reset(new uint8_t[dinfo.image_width * dinfo.image_height]);
553 frame->cbcr.reset(new uint8_t[dinfo.image_width * dinfo.image_height]);
554 const uint8_t *src = (const uint8_t *)mapped + resources.image.offsets[0];
555 if (resources.image.pitches[0] == dinfo.image_width * 2) {
556 memcpy_interleaved(frame->cbcr.get(), frame->y.get(), src, dinfo.image_width * dinfo.image_height * 2);
558 for (unsigned y = 0; y < dinfo.image_height; ++y) {
559 memcpy_interleaved(frame->cbcr.get() + y * dinfo.image_width, frame->y.get() + y * dinfo.image_width,
560 src + y * resources.image.pitches[0], dinfo.image_width * 2);
564 frame->width = dinfo.image_width;
565 frame->height = dinfo.image_height;
566 frame->chroma_subsampling_x = 2;
567 frame->chroma_subsampling_y = 1;
568 frame->pitch_y = dinfo.image_width;
569 frame->pitch_chroma = dinfo.image_width / 2;
571 if (dinfo.marker_list != nullptr &&
572 dinfo.marker_list->marker == JPEG_APP0 + 1 &&
573 dinfo.marker_list->data_length >= 4 &&
574 memcmp(dinfo.marker_list->data, "Exif", 4) == 0) {
575 frame->exif_data.assign(reinterpret_cast<char *>(dinfo.marker_list->data),
576 dinfo.marker_list->data_length);
579 va_status = vaUnmapBuffer(va_dpy->va_dpy, resources.image.buf);
580 CHECK_VASTATUS_RET(va_status, "vaUnmapBuffer");