1 /*
2 * Copyright (C) 2017 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
17 #include <stdio.h> // stdio.h must appear before jpeglib.h
18 #include <jpeglib.h>
19
20 #include <glog/logging.h>
21 #include "host/frontend/vnc_server/jpeg_compressor.h"
22 #include "host/frontend/vnc_server/vnc_utils.h"
23
24 using cvd::vnc::JpegCompressor;
25
26 namespace {
InitCinfo(jpeg_compress_struct * cinfo,jpeg_error_mgr * err,std::uint16_t width,std::uint16_t height,int jpeg_quality)27 void InitCinfo(jpeg_compress_struct* cinfo, jpeg_error_mgr* err,
28 std::uint16_t width, std::uint16_t height, int jpeg_quality) {
29 cinfo->err = jpeg_std_error(err);
30 jpeg_create_compress(cinfo);
31
32 cinfo->image_width = width;
33 cinfo->image_height = height;
34 cinfo->input_components = cvd::vnc::BytesPerPixel();
35 cinfo->in_color_space = JCS_EXT_RGBX;
36
37 jpeg_set_defaults(cinfo);
38 jpeg_set_quality(cinfo, jpeg_quality, true);
39 }
40 } // namespace
41
Compress(const Message & frame,int jpeg_quality,std::uint16_t x,std::uint16_t y,std::uint16_t width,std::uint16_t height,int stride)42 cvd::Message JpegCompressor::Compress(const Message& frame,
43 int jpeg_quality, std::uint16_t x,
44 std::uint16_t y, std::uint16_t width,
45 std::uint16_t height,
46 int stride) {
47 jpeg_compress_struct cinfo{};
48 jpeg_error_mgr err{};
49 InitCinfo(&cinfo, &err, width, height, jpeg_quality);
50
51 auto* compression_buffer = buffer_.get();
52 auto compression_buffer_size = buffer_capacity_;
53 jpeg_mem_dest(&cinfo, &compression_buffer, &compression_buffer_size);
54 jpeg_start_compress(&cinfo, true);
55
56 while (cinfo.next_scanline < cinfo.image_height) {
57 auto row = static_cast<JSAMPROW>(const_cast<std::uint8_t*>(
58 &frame[(y * stride) +
59 (cinfo.next_scanline * stride) +
60 (x * BytesPerPixel())]));
61 jpeg_write_scanlines(&cinfo, &row, 1);
62 }
63 jpeg_finish_compress(&cinfo);
64 jpeg_destroy_compress(&cinfo);
65
66 UpdateBuffer(compression_buffer, compression_buffer_size);
67 return {compression_buffer, compression_buffer + compression_buffer_size};
68 }
69
UpdateBuffer(std::uint8_t * compression_buffer,unsigned long compression_buffer_size)70 void JpegCompressor::UpdateBuffer(std::uint8_t* compression_buffer,
71 unsigned long compression_buffer_size) {
72 if (buffer_.get() != compression_buffer) {
73 buffer_capacity_ = compression_buffer_size;
74 buffer_.reset(compression_buffer);
75 }
76 }
77