1/*
2 * Copyright 2015 Google Inc.
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#include "SkJpegDecoderMgr.h"
9#include "SkJpegUtility_codec.h"
10
11/*
12 * Print information, warning, and error messages
13 */
14static void print_message(const j_common_ptr info, const char caller[]) {
15    char buffer[JMSG_LENGTH_MAX];
16    info->err->format_message(info, buffer);
17    SkCodecPrintf("libjpeg error %d <%s> from %s\n", info->err->msg_code, buffer, caller);
18}
19
20/*
21 * Reporting function for error and warning messages.
22 */
23static void output_message(j_common_ptr info) {
24    print_message(info, "output_message");
25}
26
27bool JpegDecoderMgr::returnFalse(const char caller[]) {
28    print_message((j_common_ptr) &fDInfo, caller);
29    return false;
30}
31
32SkCodec::Result JpegDecoderMgr::returnFailure(const char caller[], SkCodec::Result result) {
33    print_message((j_common_ptr) &fDInfo, caller);
34    return result;
35}
36
37SkColorType JpegDecoderMgr::getColorType() {
38    switch (fDInfo.jpeg_color_space) {
39        case JCS_GRAYSCALE:
40            return kGray_8_SkColorType;
41        default:
42            return kN32_SkColorType;
43    }
44}
45
46JpegDecoderMgr::JpegDecoderMgr(SkStream* stream)
47    : fSrcMgr(stream)
48    , fInit(false)
49{
50    // Error manager must be set before any calls to libjeg in order to handle failures
51    fDInfo.err = jpeg_std_error(&fErrorMgr);
52    fErrorMgr.error_exit = skjpeg_err_exit;
53}
54
55void JpegDecoderMgr::init() {
56    jpeg_create_decompress(&fDInfo);
57    fInit = true;
58    fDInfo.src = &fSrcMgr;
59    fDInfo.err->output_message = &output_message;
60}
61
62JpegDecoderMgr::~JpegDecoderMgr() {
63    if (fInit) {
64        jpeg_destroy_decompress(&fDInfo);
65    }
66}
67
68jmp_buf& JpegDecoderMgr::getJmpBuf() {
69    return fErrorMgr.fJmpBuf;
70}
71
72jpeg_decompress_struct* JpegDecoderMgr::dinfo() {
73    return &fDInfo;
74}
75