+extern QGLWidget *global_share_widget;
+
+// TODO: Decode using VA-API if available.
+shared_ptr<Frame> decode_jpeg(const string &filename)
+{
+ shared_ptr<Frame> frame(new Frame);
+
+ jpeg_decompress_struct dinfo;
+ jpeg_error_mgr jerr;
+ dinfo.err = jpeg_std_error(&jerr);
+ jpeg_create_decompress(&dinfo);
+
+ FILE *fp = fopen(filename.c_str(), "rb");
+ if (fp == nullptr) {
+ perror(filename.c_str());
+ exit(1);
+ }
+ jpeg_stdio_src(&dinfo, fp);
+
+ jpeg_read_header(&dinfo, true);
+
+ if (dinfo.num_components != 3 ||
+ dinfo.comp_info[0].h_samp_factor != 2 ||
+ dinfo.comp_info[0].v_samp_factor != 2 ||
+ dinfo.comp_info[1].h_samp_factor != 1 ||
+ dinfo.comp_info[1].v_samp_factor != 2 ||
+ dinfo.comp_info[2].h_samp_factor != 1 ||
+ dinfo.comp_info[2].v_samp_factor != 2) {
+ fprintf(stderr, "Not 4:2:2 JPEG! (%d components, Y=%dx%d, Cb=%dx%d, Cr=%dx%d)\n",
+ dinfo.num_components,
+ dinfo.comp_info[0].h_samp_factor, dinfo.comp_info[0].v_samp_factor,
+ dinfo.comp_info[1].h_samp_factor, dinfo.comp_info[1].v_samp_factor,
+ dinfo.comp_info[2].h_samp_factor, dinfo.comp_info[2].v_samp_factor);
+ exit(1);
+ }
+ dinfo.raw_data_out = true;
+
+ jpeg_start_decompress(&dinfo);
+
+ frame->width = dinfo.output_width;
+ frame->height = dinfo.output_height;
+
+ unsigned chroma_width_blocks = (dinfo.output_width + 15) / 16;
+ unsigned width_blocks = chroma_width_blocks * 2;
+ unsigned height_blocks = (dinfo.output_height + 15) / 16;
+
+ // TODO: Decode into a PBO.
+ frame->y.reset(new uint8_t[width_blocks * (height_blocks * 2) * DCTSIZE2]);
+ frame->cb.reset(new uint8_t[chroma_width_blocks * (height_blocks * 2) * DCTSIZE2]);
+ frame->cr.reset(new uint8_t[chroma_width_blocks * (height_blocks * 2) * DCTSIZE2]);
+
+ JSAMPROW yptr[16], cbptr[16], crptr[16];
+ JSAMPARRAY data[3] = { yptr, cbptr, crptr };
+ for (unsigned y = 0; y < height_blocks; ++y) {
+ for (unsigned yy = 0; yy < DCTSIZE * 2; ++yy) {
+ yptr[yy] = frame->y.get() + (y * DCTSIZE * 2 + yy) * width_blocks * DCTSIZE;
+ cbptr[yy] = frame->cb.get() + (y * DCTSIZE * 2 + yy) * chroma_width_blocks * DCTSIZE;
+ crptr[yy] = frame->cr.get() + (y * DCTSIZE * 2 + yy) * chroma_width_blocks * DCTSIZE;
+ }
+
+ jpeg_read_raw_data(&dinfo, data, /*num_lines=*/16);
+ }
+
+ (void) jpeg_finish_decompress(&dinfo);
+ jpeg_destroy_decompress(&dinfo);
+ fclose(fp);
+
+ return frame;
+}