blob: 2b19c138a458a4ee84d77091e123d1c433150595 [file] [log] [blame]
Jan Sebechlebsky5cb39962023-11-22 17:33:07 +01001/*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16// #define LOG_NDEBUG 0
17#define LOG_TAG "JpegUtil"
18#include "JpegUtil.h"
19
20#include <cstddef>
21#include <cstdint>
22#include <memory>
Jan Sebechlebsky9ae496f2023-12-05 15:56:28 +010023#include <vector>
Jan Sebechlebsky5cb39962023-11-22 17:33:07 +010024
25#include "android/hardware_buffer.h"
26#include "jpeglib.h"
27#include "log/log.h"
28#include "ui/GraphicBuffer.h"
29#include "ui/GraphicBufferMapper.h"
30#include "utils/Errors.h"
31
32namespace android {
33namespace companion {
34namespace virtualcamera {
35namespace {
36
37constexpr int kJpegQuality = 80;
38
39class LibJpegContext {
40 public:
Jan Sebechlebsky9ae496f2023-12-05 15:56:28 +010041 LibJpegContext(int width, int height, const size_t outBufferSize,
42 void* outBuffer)
43 : mWidth(width),
Jan Sebechlebsky5cb39962023-11-22 17:33:07 +010044 mHeight(height),
45 mDstBufferSize(outBufferSize),
46 mDstBuffer(outBuffer) {
47 // Initialize error handling for libjpeg.
48 // We call jpeg_std_error to initialize standard error
49 // handling and then override:
50 // * output_message not to print to stderr, but use ALOG instead.
51 // * error_exit not to terminate the process, but failure flag instead.
52 mCompressStruct.err = jpeg_std_error(&mErrorMgr);
53 mCompressStruct.err->output_message = onOutputError;
54 mCompressStruct.err->error_exit = onErrorExit;
55 jpeg_create_compress(&mCompressStruct);
56
57 // Configure input image parameters.
58 mCompressStruct.image_width = width;
59 mCompressStruct.image_height = height;
60 mCompressStruct.input_components = 3;
61 mCompressStruct.in_color_space = JCS_YCbCr;
62 // We pass pointer to this instance as a client data so we can
63 // access this object from the static callbacks invoked by
64 // libjpeg.
65 mCompressStruct.client_data = this;
66
67 // Configure destination manager for libjpeg.
68 mCompressStruct.dest = &mDestinationMgr;
69 mDestinationMgr.init_destination = onInitDestination;
70 mDestinationMgr.empty_output_buffer = onEmptyOutputBuffer;
71 mDestinationMgr.term_destination = onTermDestination;
72 mDestinationMgr.next_output_byte = reinterpret_cast<JOCTET*>(mDstBuffer);
73 mDestinationMgr.free_in_buffer = mDstBufferSize;
74
75 // Configure everything else based on input configuration above.
76 jpeg_set_defaults(&mCompressStruct);
77
78 // Set quality and colorspace.
79 jpeg_set_quality(&mCompressStruct, kJpegQuality, 1);
80 jpeg_set_colorspace(&mCompressStruct, JCS_YCbCr);
81
82 // Configure RAW input mode - this let's libjpeg know we're providing raw,
83 // subsampled YCbCr data.
84 mCompressStruct.raw_data_in = 1;
85 mCompressStruct.dct_method = JDCT_IFAST;
86
87 // Configure sampling factors - this states that every 2 Y
88 // samples share 1 Cb & 1 Cr component vertically & horizontally (YUV420).
89 mCompressStruct.comp_info[0].h_samp_factor = 2;
90 mCompressStruct.comp_info[0].v_samp_factor = 2;
91 mCompressStruct.comp_info[1].h_samp_factor = 1;
92 mCompressStruct.comp_info[1].v_samp_factor = 1;
93 mCompressStruct.comp_info[2].h_samp_factor = 1;
94 mCompressStruct.comp_info[2].v_samp_factor = 1;
95 }
96
Jan Sebechlebsky9ae496f2023-12-05 15:56:28 +010097 bool compress(const android_ycbcr& ycbr) {
Jan Sebechlebsky5cb39962023-11-22 17:33:07 +010098 // Prepare arrays of pointers to scanlines of each plane.
99 std::vector<JSAMPROW> yLines(mHeight);
100 std::vector<JSAMPROW> cbLines(mHeight / 2);
101 std::vector<JSAMPROW> crLines(mHeight / 2);
102
Jan Sebechlebsky9ae496f2023-12-05 15:56:28 +0100103 uint8_t* y = static_cast<uint8_t*>(ycbr.y);
104 uint8_t* cb = static_cast<uint8_t*>(ycbr.cb);
105 uint8_t* cr = static_cast<uint8_t*>(ycbr.cr);
Jan Sebechlebsky5cb39962023-11-22 17:33:07 +0100106
107 // Since UV samples might be interleaved (semiplanar) we need to copy
108 // them to separate planes, since libjpeg doesn't directly
109 // support processing semiplanar YUV.
110 const int c_samples = (mWidth / 2) * (mHeight / 2);
111 std::vector<uint8_t> cb_plane(c_samples);
112 std::vector<uint8_t> cr_plane(c_samples);
113
114 // TODO(b/301023410) - Use libyuv or ARM SIMD for "unzipping" the data.
115 for (int i = 0; i < c_samples; ++i) {
116 cb_plane[i] = *cb;
117 cr_plane[i] = *cr;
Jan Sebechlebsky9ae496f2023-12-05 15:56:28 +0100118 cb += ycbr.chroma_step;
119 cr += ycbr.chroma_step;
Jan Sebechlebsky5cb39962023-11-22 17:33:07 +0100120 }
121
122 // Collect pointers to individual scanline of each plane.
123 for (int i = 0; i < mHeight; ++i) {
Jan Sebechlebsky9ae496f2023-12-05 15:56:28 +0100124 yLines[i] = y + i * ycbr.ystride;
Jan Sebechlebsky5cb39962023-11-22 17:33:07 +0100125 }
126 for (int i = 0; i < (mHeight / 2); ++i) {
127 cbLines[i] = cb_plane.data() + i * (mWidth / 2);
128 crLines[i] = cr_plane.data() + i * (mWidth / 2);
129 }
130
Jan Sebechlebsky9ae496f2023-12-05 15:56:28 +0100131 return compress(yLines, cbLines, crLines);
132 }
133
134 bool compressBlackImage() {
135 // We only really need to prepare one scanline for Y and one shared scanline
136 // for Cb & Cr.
137 std::vector<uint8_t> yLine(mWidth, 0);
138 std::vector<uint8_t> chromaLine(mWidth / 2, 0xff / 2);
139
140 std::vector<JSAMPROW> yLines(mHeight, yLine.data());
141 std::vector<JSAMPROW> cLines(mHeight / 2, chromaLine.data());
142
143 return compress(yLines, cLines, cLines);
144 }
145
146 private:
147 void setSuccess(const boolean success) {
148 mSuccess = success;
149 }
150
151 void initDestination() {
152 mDestinationMgr.next_output_byte = reinterpret_cast<JOCTET*>(mDstBuffer);
153 mDestinationMgr.free_in_buffer = mDstBufferSize;
154 ALOGV("%s:%d jpeg start: %p [%zu]", __FUNCTION__, __LINE__, mDstBuffer,
155 mDstBufferSize);
156 }
157
158 void termDestination() {
159 mEncodedSize = mDstBufferSize - mDestinationMgr.free_in_buffer;
160 ALOGV("%s:%d Done with jpeg: %zu", __FUNCTION__, __LINE__, mEncodedSize);
161 }
162
163 // Perform actual compression.
164 //
165 // Takes vector of pointers to Y / Cb / Cr scanlines as an input. Length of
166 // each vector needs to correspond to height of corresponding plane.
167 //
168 // Returns true if compression is successful, false otherwise.
169 bool compress(std::vector<JSAMPROW>& yLines, std::vector<JSAMPROW>& cbLines,
170 std::vector<JSAMPROW>& crLines) {
Jan Sebechlebsky5cb39962023-11-22 17:33:07 +0100171 jpeg_start_compress(&mCompressStruct, TRUE);
172
173 while (mCompressStruct.next_scanline < mCompressStruct.image_height) {
174 const uint32_t batchSize = DCTSIZE * 2;
175 const uint32_t nl = mCompressStruct.next_scanline;
176 JSAMPARRAY planes[3]{&yLines[nl], &cbLines[nl / 2], &crLines[nl / 2]};
177
178 uint32_t done = jpeg_write_raw_data(&mCompressStruct, planes, batchSize);
179
180 if (done != batchSize) {
181 ALOGE("%s: compressed %u lines, expected %u (total %u/%u)",
182 __FUNCTION__, done, batchSize, mCompressStruct.next_scanline,
183 mCompressStruct.image_height);
184 return false;
185 }
186 }
187 jpeg_finish_compress(&mCompressStruct);
188 return mSuccess;
189 }
190
Jan Sebechlebsky5cb39962023-11-22 17:33:07 +0100191 // === libjpeg callbacks below ===
192
193 static void onOutputError(j_common_ptr cinfo) {
194 char buffer[JMSG_LENGTH_MAX];
195 (*cinfo->err->format_message)(cinfo, buffer);
196 ALOGE("libjpeg error: %s", buffer);
197 };
198
199 static void onErrorExit(j_common_ptr cinfo) {
200 static_cast<LibJpegContext*>(cinfo->client_data)->setSuccess(false);
201 };
202
203 static void onInitDestination(j_compress_ptr cinfo) {
204 static_cast<LibJpegContext*>(cinfo->client_data)->initDestination();
205 }
206
207 static int onEmptyOutputBuffer(j_compress_ptr cinfo __unused) {
208 ALOGV("%s:%d Out of buffer", __FUNCTION__, __LINE__);
209 return 0;
210 }
211
212 static void onTermDestination(j_compress_ptr cinfo) {
213 static_cast<LibJpegContext*>(cinfo->client_data)->termDestination();
214 }
215
216 jpeg_compress_struct mCompressStruct;
217 jpeg_error_mgr mErrorMgr;
218 jpeg_destination_mgr mDestinationMgr;
219
Jan Sebechlebsky5cb39962023-11-22 17:33:07 +0100220 // Dimensions of the input image.
221 int mWidth;
222 int mHeight;
223
224 // Destination buffer and it's capacity.
225 size_t mDstBufferSize;
226 void* mDstBuffer;
227
228 // This will be set to size of encoded data
229 // written to the outputBuffer when encoding finishes.
230 size_t mEncodedSize;
231 // Set to true/false based on whether the encoding
232 // was successful.
233 boolean mSuccess = true;
234};
235
236} // namespace
237
Jan Sebechlebsky5cb39962023-11-22 17:33:07 +0100238bool compressJpeg(int width, int height, const android_ycbcr& ycbcr,
239 size_t outBufferSize, void* outBuffer) {
Jan Sebechlebsky9ae496f2023-12-05 15:56:28 +0100240 return LibJpegContext(width, height, outBufferSize, outBuffer).compress(ycbcr);
241}
242
243bool compressBlackJpeg(int width, int height, size_t outBufferSize,
244 void* outBuffer) {
245 return LibJpegContext(width, height, outBufferSize, outBuffer)
246 .compressBlackImage();
Jan Sebechlebsky5cb39962023-11-22 17:33:07 +0100247}
248
249} // namespace virtualcamera
250} // namespace companion
251} // namespace android