xref: /aosp_15_r20/external/skia/src/encode/SkJPEGWriteUtility.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2010 The Android Open Source Project
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 
9 #include "src/encode/SkJPEGWriteUtility.h"
10 
11 #include "include/core/SkStream.h"
12 #include "src/codec/SkJpegPriv.h"
13 
14 #include <csetjmp>
15 #include <cstddef>
16 
17 extern "C" {
18     #include "jerror.h"    // NO_G3_REWRITE
19     #include "jpeglib.h"   // NO_G3_REWRITE
20 }
21 
22 ///////////////////////////////////////////////////////////////////////////////
23 
sk_init_destination(j_compress_ptr cinfo)24 static void sk_init_destination(j_compress_ptr cinfo) {
25     skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;
26 
27     dest->next_output_byte = dest->fBuffer;
28     dest->free_in_buffer = skjpeg_destination_mgr::kBufferSize;
29 }
30 
sk_empty_output_buffer(j_compress_ptr cinfo)31 static boolean sk_empty_output_buffer(j_compress_ptr cinfo) {
32     skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;
33 
34 //  if (!dest->fStream->write(dest->fBuffer, skjpeg_destination_mgr::kBufferSize - dest->free_in_buffer))
35     if (!dest->fStream->write(dest->fBuffer,
36             skjpeg_destination_mgr::kBufferSize)) {
37         ERREXIT(cinfo, JERR_FILE_WRITE);
38         return FALSE;
39     }
40 
41     dest->next_output_byte = dest->fBuffer;
42     dest->free_in_buffer = skjpeg_destination_mgr::kBufferSize;
43     return TRUE;
44 }
45 
sk_term_destination(j_compress_ptr cinfo)46 static void sk_term_destination (j_compress_ptr cinfo) {
47     skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;
48 
49     size_t size = skjpeg_destination_mgr::kBufferSize - dest->free_in_buffer;
50     if (size > 0) {
51         if (!dest->fStream->write(dest->fBuffer, size)) {
52             ERREXIT(cinfo, JERR_FILE_WRITE);
53             return;
54         }
55     }
56 
57     dest->fStream->flush();
58 }
59 
skjpeg_destination_mgr(SkWStream * stream)60 skjpeg_destination_mgr::skjpeg_destination_mgr(SkWStream* stream) : fStream(stream) {
61     this->init_destination = sk_init_destination;
62     this->empty_output_buffer = sk_empty_output_buffer;
63     this->term_destination = sk_term_destination;
64 }
65 
skjpeg_error_exit(j_common_ptr cinfo)66 void skjpeg_error_exit(j_common_ptr cinfo) {
67     skjpeg_error_mgr* error = static_cast<skjpeg_error_mgr*>(cinfo->err);
68 
69     (*error->output_message)(cinfo);
70 
71     /* Let the memory manager delete any temp files before we die */
72     jpeg_destroy(cinfo);
73 
74     if (error->fStack[0] == nullptr) {
75         SK_ABORT("JPEG error with no jmp_buf set.");
76     }
77     longjmp(*error->fStack[0], -1);
78 }
79