]> git.sesse.net Git - nageru/blob - futatabi/vaapi_jpeg_decoder.cpp
f34654d508504434e81fbcc816e12b3a8aba95a5
[nageru] / futatabi / vaapi_jpeg_decoder.cpp
1 #include "vaapi_jpeg_decoder.h"
2
3 #include "jpeg_destroyer.h"
4 #include "jpeg_frame.h"
5 #include "jpeglib_error_wrapper.h"
6 #include "shared/memcpy_interleaved.h"
7
8 #include <X11/Xlib.h>
9 #include <assert.h>
10 #include <errno.h>
11 #include <fcntl.h>
12 #include <glob.h>
13 #include <jpeglib.h>
14 #include <list>
15 #include <mutex>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <string>
20 #include <unistd.h>
21 #include <va/va.h>
22 #include <va/va_drm.h>
23 #include <va/va_x11.h>
24
25 using namespace std;
26
27 static unique_ptr<VADisplayWithCleanup> va_dpy;
28 static VAConfigID config_id;
29 static VAImageFormat uyvy_format;
30 bool vaapi_jpeg_decoding_usable = false;
31
32 struct VAResources {
33         unsigned width, height;
34         VASurfaceID surface;
35         VAContextID context;
36         VAImage image;
37 };
38 static list<VAResources> va_resources_freelist;
39 static mutex va_resources_mutex;
40
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); \
44                 abort(); \
45         }
46
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); \
50                 return nullptr; \
51         }
52
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,
63 };
64
65 VAResources get_va_resources(unsigned width, unsigned height)
66 {
67         {
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);
73                                 return ret;
74                         }
75                 }
76         }
77
78         VAResources ret;
79
80         ret.width = width;
81         ret.height = height;
82
83         VAStatus va_status = vaCreateSurfaces(va_dpy->va_dpy, VA_RT_FORMAT_YUV422,
84                                               width, height,
85                                               &ret.surface, 1, nullptr, 0);
86         CHECK_VASTATUS(va_status, "vaCreateSurfaces");
87
88         va_status = vaCreateContext(va_dpy->va_dpy, config_id, width, height, 0, &ret.surface, 1, &ret.context);
89         CHECK_VASTATUS(va_status, "vaCreateContext");
90
91         va_status = vaCreateImage(va_dpy->va_dpy, &uyvy_format, width, height, &ret.image);
92         CHECK_VASTATUS(va_status, "vaCreateImage");
93
94         return ret;
95 }
96
97 void release_va_resources(VAResources resources)
98 {
99         lock_guard<mutex> lock(va_resources_mutex);
100         if (va_resources_freelist.size() > 10) {
101                 auto it = va_resources_freelist.end();
102                 --it;
103
104                 VAStatus va_status = vaDestroyImage(va_dpy->va_dpy, it->image.image_id);
105                 CHECK_VASTATUS(va_status, "vaDestroyImage");
106
107                 va_status = vaDestroyContext(va_dpy->va_dpy, it->context);
108                 CHECK_VASTATUS(va_status, "vaDestroyContext");
109
110                 va_status = vaDestroySurfaces(va_dpy->va_dpy, &it->surface, 1);
111                 CHECK_VASTATUS(va_status, "vaDestroySurfaces");
112
113                 va_resources_freelist.erase(it);
114         }
115
116         va_resources_freelist.push_front(resources);
117 }
118
119 // RAII wrapper to release VAResources on return (even on error).
120 class ReleaseVAResources {
121 public:
122         ReleaseVAResources(const VAResources &resources)
123                 : resources(resources) {}
124         ~ReleaseVAResources()
125         {
126                 if (!committed) {
127                         release_va_resources(resources);
128                 }
129         }
130
131         void commit() { committed = true; }
132
133 private:
134         const VAResources &resources;
135         bool committed = false;
136 };
137
138 VADisplayWithCleanup::~VADisplayWithCleanup()
139 {
140         if (va_dpy != nullptr) {
141                 vaTerminate(va_dpy);
142         }
143         if (x11_display != nullptr) {
144                 XCloseDisplay(x11_display);
145         }
146         if (drm_fd != -1) {
147                 close(drm_fd);
148         }
149 }
150
151 unique_ptr<VADisplayWithCleanup> va_open_display(const string &va_display)
152 {
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");
157                         return nullptr;
158                 }
159
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) {
164                         return nullptr;
165                 }
166                 return ret;
167         } else {  // A DRM node on the filesystem (e.g. /dev/dri/renderD128).
168                 int drm_fd = open(va_display.c_str(), O_RDWR);
169                 if (drm_fd == -1) {
170                         perror(va_display.c_str());
171                         return nullptr;
172                 }
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) {
177                         return nullptr;
178                 }
179                 return ret;
180         }
181 }
182
183 unique_ptr<VADisplayWithCleanup> try_open_va(const string &va_display, string *error)
184 {
185         unique_ptr<VADisplayWithCleanup> va_dpy = va_open_display(va_display);
186         if (va_dpy == nullptr) {
187                 if (error)
188                         *error = "Opening VA display failed";
189                 return nullptr;
190         }
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) {
194                 char buf[256];
195                 snprintf(buf, sizeof(buf), "vaInitialize() failed with status %d\n", va_status);
196                 if (error != nullptr)
197                         *error = buf;
198                 return nullptr;
199         }
200
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";
206                 return nullptr;
207         }
208
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) {
212                         continue;
213                 }
214
215                 // We found a usable decode, so return it.
216                 return va_dpy;
217         }
218
219         if (error != nullptr)
220                 *error = "Can't find VAEntrypointVLD for the JPEG profile";
221         return nullptr;
222 }
223
224 string get_usable_va_display()
225 {
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;
232         }
233
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");
239                 }
240                 return "";
241         }
242
243         fprintf(stderr, "The X11 display did not expose a VA-API JPEG decoder.\n");
244
245         // Try all /dev/dri/render* in turn. TODO: Accept /dev/dri/card*, too?
246         glob_t g;
247         int err = glob("/dev/dri/renderD*", 0, nullptr, &g);
248         if (err != 0) {
249                 fprintf(stderr, "Couldn't list render nodes (%s) when trying to autodetect a replacement.\n", strerror(errno));
250         } else {
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",
256                                         path.c_str());
257                                 globfree(&g);
258                                 if (need_env_reset) {
259                                         unsetenv("LIBVA_MESSAGING_LEVEL");
260                                 }
261                                 return path;
262                         }
263                 }
264         }
265
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");
270         return "none";
271 }
272
273 void init_jpeg_vaapi()
274 {
275         string dpy = get_usable_va_display();
276         if (dpy == "none") {
277                 return;
278         }
279
280         va_dpy = try_open_va(dpy, nullptr);
281         if (va_dpy == nullptr) {
282                 return;
283         }
284
285         VAConfigAttrib attr = { VAConfigAttribRTFormat, VA_RT_FORMAT_YUV422 };
286
287         VAStatus va_status = vaCreateConfig(va_dpy->va_dpy, VAProfileJPEGBaseline, VAEntrypointVLD,
288                                             &attr, 1, &config_id);
289         CHECK_VASTATUS(va_status, "vaCreateConfig");
290
291         int num_formats = vaMaxNumImageFormats(va_dpy->va_dpy);
292         assert(num_formats > 0);
293
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");
297
298         bool found = false;
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));
303                         found = true;
304                         break;
305                 }
306         }
307         if (!found) {
308                 return;
309         }
310
311         fprintf(stderr, "VA-API JPEG decoding initialized.\n");
312         vaapi_jpeg_decoding_usable = true;
313 }
314
315 class VABufferDestroyer {
316 public:
317         VABufferDestroyer(VADisplay dpy, VABufferID buf)
318                 : dpy(dpy), buf(buf) {}
319
320         ~VABufferDestroyer()
321         {
322                 VAStatus va_status = vaDestroyBuffer(dpy, buf);
323                 CHECK_VASTATUS(va_status, "vaDestroyBuffer");
324         }
325
326 private:
327         VADisplay dpy;
328         VABufferID buf;
329 };
330
331 shared_ptr<Frame> decode_jpeg_vaapi(const string &jpeg)
332 {
333         jpeg_decompress_struct dinfo;
334         JPEGWrapErrorManager error_mgr(&dinfo);
335         if (!error_mgr.run([&dinfo] { jpeg_create_decompress(&dinfo); })) {
336                 return nullptr;
337         }
338         JPEGDestroyer destroy_dinfo(&dinfo);
339
340         jpeg_save_markers(&dinfo, JPEG_APP0 + 1, 0xFFFF);
341
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); })) {
344                 return nullptr;
345         }
346
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);
353                 return nullptr;
354         }
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);
364                 return nullptr;
365         }
366
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;
378         }
379         pic_param.num_components = dinfo.num_components;
380         pic_param.color_space = 0;  // YUV.
381         pic_param.rotation = VA_ROTATION_NONE;
382
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);
387
388         // Quantization matrices.
389         VAIQMatrixBufferJPEGBaseline iq;
390         memset(&iq, 0, sizeof(iq));
391
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;
396                 } else {
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");
401                                         return nullptr;
402                                 }
403                                 iq.quantiser_table[quant_tbl_idx][i] = qtbl->quantval[jpeg_natural_order[i]];
404                         }
405                 }
406         }
407
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);
412
413         // Huffman tables (arithmetic is not supported).
414         VAHuffmanTableBufferJPEGBaseline huff;
415         memset(&huff, 0, sizeof(huff));
416
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;
423                 } else {
424                         assert(dc_hufftbl != nullptr);
425                         huff.load_huffman_table[huff_tbl_idx] = 1;
426
427                         for (int i = 0; i < 16; ++i) {
428                                 huff.huffman_table[huff_tbl_idx].num_dc_codes[i] = dc_hufftbl->bits[i + 1];
429                         }
430                         for (int i = 0; i < 12; ++i) {
431                                 huff.huffman_table[huff_tbl_idx].dc_values[i] = dc_hufftbl->huffval[i];
432                         }
433                         for (int i = 0; i < 16; ++i) {
434                                 huff.huffman_table[huff_tbl_idx].num_ac_codes[i] = ac_hufftbl->bits[i + 1];
435                         }
436                         for (int i = 0; i < 162; ++i) {
437                                 huff.huffman_table[huff_tbl_idx].ac_values[i] = ac_hufftbl->huffval[i];
438                         }
439                 }
440         }
441
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);
446
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");
463                         return nullptr;
464                 }
465         }
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;
471
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);
476
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);
482
483         VAResources resources = get_va_resources(dinfo.image_width, dinfo.image_height);
484         ReleaseVAResources release(resources);
485
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");
500
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).
506 #if 0
507         VAImage image;
508         va_status = vaDeriveImage(va_dpy->va_dpy, surf, &image);
509         CHECK_VASTATUS_RET(va_status, "vaDeriveImage");
510 #else
511         va_status = vaSyncSurface(va_dpy->va_dpy, resources.surface);
512         CHECK_VASTATUS_RET(va_status, "vaSyncSurface");
513
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");
516 #endif
517
518         void *mapped;
519         va_status = vaMapBuffer(va_dpy->va_dpy, resources.image.buf, &mapped);
520         CHECK_VASTATUS_RET(va_status, "vaMapBuffer");
521
522         shared_ptr<Frame> frame(new Frame);
523 #if 0
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) {
529                 uint8_t *dptr;
530                 size_t width;
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;
540                 } else {
541                         assert(false);
542                 }
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);
547                 }
548         }
549 #else
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);
557         } else {
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);
561                 }
562         }
563 #endif
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;
570
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);
577         }
578
579         va_status = vaUnmapBuffer(va_dpy->va_dpy, resources.image.buf);
580         CHECK_VASTATUS_RET(va_status, "vaUnmapBuffer");
581
582         return frame;
583 }