summaryrefslogtreecommitdiffstats
path: root/media/img_utils/src/TiffIfd.cpp
blob: 3fb00cc56f218bbe2e8b966b2147eb8f5a5c7c88 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/*
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "TiffIfd"

#include <img_utils/TagDefinitions.h>
#include <img_utils/TiffHelpers.h>
#include <img_utils/TiffIfd.h>
#include <img_utils/TiffWriter.h>

#include <utils/Log.h>

namespace android {
namespace img_utils {

TiffIfd::TiffIfd(uint32_t ifdId)
        : mNextIfd(), mIfdId(ifdId), mStripOffsetsInitialized(false) {}

TiffIfd::~TiffIfd() {}

status_t TiffIfd::addEntry(const sp<TiffEntry>& entry) {
    size_t size = mEntries.size();
    if (size >= MAX_IFD_ENTRIES) {
        ALOGW("%s: Failed to add entry for tag 0x%x to IFD %u, too many entries in IFD!",
                __FUNCTION__, entry->getTag(), mIfdId);
        return BAD_INDEX;
    }

    if (mEntries.add(entry) < 0) {
        ALOGW("%s: Failed to add entry for tag 0x%x to ifd %u.", __FUNCTION__, entry->getTag(),
                mIfdId);
        return BAD_INDEX;
    }
    return OK;
}

sp<TiffEntry> TiffIfd::getEntry(uint16_t tag) const {
    ssize_t index = mEntries.indexOfTag(tag);
    if (index < 0) {
        ALOGW("%s: No entry for tag 0x%x in ifd %u.", __FUNCTION__, tag, mIfdId);
        return NULL;
    }
    return mEntries[index];
}

void TiffIfd::removeEntry(uint16_t tag) {
    ssize_t index = mEntries.indexOfTag(tag);
    if (index >= 0) {
        mEntries.removeAt(index);
    }
}


void TiffIfd::setNextIfd(const sp<TiffIfd>& ifd) {
    mNextIfd = ifd;
}

sp<TiffIfd> TiffIfd::getNextIfd() const {
    return mNextIfd;
}

uint32_t TiffIfd::checkAndGetOffset(uint32_t offset) const {
    size_t size = mEntries.size();

    if (size > MAX_IFD_ENTRIES) {
        ALOGW("%s: Could not calculate IFD offsets, IFD %u contains too many entries.",
                __FUNCTION__, mIfdId);
        return BAD_OFFSET;
    }

    if (size <= 0) {
        ALOGW("%s: Could not calculate IFD offsets, IFD %u contains no entries.", __FUNCTION__,
                mIfdId);
        return BAD_OFFSET;
    }

    if (offset == BAD_OFFSET) {
        ALOGW("%s: Could not calculate IFD offsets, IFD %u had a bad initial offset.",
                __FUNCTION__, mIfdId);
        return BAD_OFFSET;
    }

    uint32_t ifdSize = calculateIfdSize(size);
    WORD_ALIGN(ifdSize);
    return offset + ifdSize;
}

status_t TiffIfd::writeData(uint32_t offset, /*out*/EndianOutput* out) const {
    assert((offset % TIFF_WORD_SIZE) == 0);
    status_t ret = OK;

    ALOGV("%s: IFD %u written to offset %u", __FUNCTION__, mIfdId, offset );
    uint32_t valueOffset = checkAndGetOffset(offset);
    if (valueOffset == 0) {
        return BAD_VALUE;
    }

    size_t size = mEntries.size();

    // Writer IFD header (2 bytes, number of entries).
    uint16_t header = static_cast<uint16_t>(size);
    BAIL_ON_FAIL(out->write(&header, 0, 1), ret);

    // Write tag entries
    for (size_t i = 0; i < size; ++i) {
        BAIL_ON_FAIL(mEntries[i]->writeTagInfo(valueOffset, out), ret);
        valueOffset += mEntries[i]->getSize();
    }

    // Writer IFD footer (4 bytes, offset to next IFD).
    uint32_t footer = (mNextIfd != NULL) ? offset + getSize() : 0;
    BAIL_ON_FAIL(out->write(&footer, 0, 1), ret);

    assert(out->getCurrentOffset() == offset + calculateIfdSize(size));

    // Write zeroes till word aligned
    ZERO_TILL_WORD(out, calculateIfdSize(size), ret);

    // Write values for each tag entry
    for (size_t i = 0; i < size; ++i) {
        size_t last = out->getCurrentOffset();
        // Only write values that are too large to fit in the 12-byte TIFF entry
        if (mEntries[i]->getSize() > OFFSET_SIZE) {
            BAIL_ON_FAIL(mEntries[i]->writeData(out->getCurrentOffset(), out), ret);
        }
        size_t next = out->getCurrentOffset();
        size_t diff = (next - last);
        size_t actual = mEntries[i]->getSize();
        if (diff != actual) {
            ALOGW("Sizes do not match for tag %x. Expected %zu, received %zu",
                    mEntries[i]->getTag(), actual, diff);
        }
    }

    assert(out->getCurrentOffset() == offset + getSize());

    return ret;
}

size_t TiffIfd::getSize() const {
    size_t size = mEntries.size();
    uint32_t total = calculateIfdSize(size);
    WORD_ALIGN(total);
    for (size_t i = 0; i < size; ++i) {
        total += mEntries[i]->getSize();
    }
    return total;
}

uint32_t TiffIfd::getId() const {
    return mIfdId;
}

uint32_t TiffIfd::getComparableValue() const {
    return mIfdId;
}

status_t TiffIfd::validateAndSetStripTags() {
    sp<TiffEntry> widthEntry = getEntry(TAG_IMAGEWIDTH);
    if (widthEntry == NULL) {
        ALOGE("%s: IFD %u doesn't have a ImageWidth tag set", __FUNCTION__, mIfdId);
        return BAD_VALUE;
    }

    sp<TiffEntry> heightEntry = getEntry(TAG_IMAGELENGTH);
    if (heightEntry == NULL) {
        ALOGE("%s: IFD %u doesn't have a ImageLength tag set", __FUNCTION__, mIfdId);
        return BAD_VALUE;
    }

    sp<TiffEntry> samplesEntry = getEntry(TAG_SAMPLESPERPIXEL);
    if (samplesEntry == NULL) {
        ALOGE("%s: IFD %u doesn't have a SamplesPerPixel tag set", __FUNCTION__, mIfdId);
        return BAD_VALUE;
    }

    sp<TiffEntry> bitsEntry = getEntry(TAG_BITSPERSAMPLE);
    if (bitsEntry == NULL) {
        ALOGE("%s: IFD %u doesn't have a BitsPerSample tag set", __FUNCTION__, mIfdId);
        return BAD_VALUE;
    }

    uint32_t width = *(widthEntry->getData<uint32_t>());
    uint32_t height = *(heightEntry->getData<uint32_t>());
    uint16_t bitsPerSample = *(bitsEntry->getData<uint16_t>());
    uint16_t samplesPerPixel = *(samplesEntry->getData<uint16_t>());

    if ((bitsPerSample % 8) != 0) {
        ALOGE("%s: BitsPerSample %d in IFD %u is not byte-aligned.", __FUNCTION__,
                bitsPerSample, mIfdId);
        return BAD_VALUE;
    }

    uint32_t bytesPerSample = bitsPerSample / 8;

    // Choose strip size as close to 8kb as possible without splitting rows.
    // If the row length is >8kb, each strip will only contain a single row.
    const uint32_t rowLengthBytes = bytesPerSample * samplesPerPixel * width;
    const uint32_t idealChunkSize = (1 << 13); // 8kb
    uint32_t rowsPerChunk = idealChunkSize / rowLengthBytes;
    rowsPerChunk = (rowsPerChunk == 0) ? 1 : rowsPerChunk;
    const uint32_t actualChunkSize = rowLengthBytes * rowsPerChunk;

    const uint32_t lastChunkRows = height % rowsPerChunk;
    const uint32_t lastChunkSize = lastChunkRows * rowLengthBytes;

    if (actualChunkSize > /*max strip size for TIFF/EP*/65536) {
        ALOGE("%s: Strip length too long.", __FUNCTION__);
        return BAD_VALUE;
    }

    size_t numStrips = height / rowsPerChunk;

    // Add another strip for the incomplete chunk.
    if (lastChunkRows > 0) {
        numStrips += 1;
    }

    // Put each row in it's own strip
    uint32_t rowsPerStripVal = rowsPerChunk;
    sp<TiffEntry> rowsPerStrip = TiffWriter::uncheckedBuildEntry(TAG_ROWSPERSTRIP, LONG, 1,
            UNDEFINED_ENDIAN, &rowsPerStripVal);

    if (rowsPerStrip == NULL) {
        ALOGE("%s: Could not build entry for RowsPerStrip tag.", __FUNCTION__);
        return BAD_VALUE;
    }

    Vector<uint32_t> byteCounts;

    for (size_t i = 0; i < numStrips; ++i) {
        if (lastChunkRows > 0 && i == (numStrips - 1)) {
            byteCounts.add(lastChunkSize);
        } else {
            byteCounts.add(actualChunkSize);
        }
    }

    // Set byte counts for each strip
    sp<TiffEntry> stripByteCounts = TiffWriter::uncheckedBuildEntry(TAG_STRIPBYTECOUNTS, LONG,
            static_cast<uint32_t>(numStrips), UNDEFINED_ENDIAN, byteCounts.array());

    if (stripByteCounts == NULL) {
        ALOGE("%s: Could not build entry for StripByteCounts tag.", __FUNCTION__);
        return BAD_VALUE;
    }

    Vector<uint32_t> stripOffsetsVector;
    stripOffsetsVector.resize(numStrips);

    // Set uninitialized offsets
    sp<TiffEntry> stripOffsets = TiffWriter::uncheckedBuildEntry(TAG_STRIPOFFSETS, LONG,
            static_cast<uint32_t>(numStrips), UNDEFINED_ENDIAN, stripOffsetsVector.array());

    if (stripOffsets == NULL) {
        ALOGE("%s: Could not build entry for StripOffsets tag.", __FUNCTION__);
        return BAD_VALUE;
    }

    if(addEntry(stripByteCounts) != OK) {
        ALOGE("%s: Could not add entry for StripByteCounts to IFD %u", __FUNCTION__, mIfdId);
        return BAD_VALUE;
    }

    if(addEntry(rowsPerStrip) != OK) {
        ALOGE("%s: Could not add entry for StripByteCounts to IFD %u", __FUNCTION__, mIfdId);
        return BAD_VALUE;
    }

    if(addEntry(stripOffsets) != OK) {
        ALOGE("%s: Could not add entry for StripByteCounts to IFD %u", __FUNCTION__, mIfdId);
        return BAD_VALUE;
    }

    mStripOffsetsInitialized = true;
    return OK;
}

bool TiffIfd::uninitializedOffsets() const {
    return mStripOffsetsInitialized;
}

status_t TiffIfd::setStripOffset(uint32_t offset) {

    // Get old offsets and bytecounts
    sp<TiffEntry> oldOffsets = getEntry(TAG_STRIPOFFSETS);
    if (oldOffsets == NULL) {
        ALOGE("%s: IFD %u does not contain StripOffsets entry.", __FUNCTION__, mIfdId);
        return BAD_VALUE;
    }

    sp<TiffEntry> stripByteCounts = getEntry(TAG_STRIPBYTECOUNTS);
    if (stripByteCounts == NULL) {
        ALOGE("%s: IFD %u does not contain StripByteCounts entry.", __FUNCTION__, mIfdId);
        return BAD_VALUE;
    }

    uint32_t offsetsCount = oldOffsets->getCount();
    uint32_t byteCount = stripByteCounts->getCount();
    if (offsetsCount != byteCount) {
        ALOGE("%s: StripOffsets count (%u) doesn't match StripByteCounts count (%u) in IFD %u",
            __FUNCTION__, offsetsCount, byteCount, mIfdId);
        return BAD_VALUE;
    }

    const uint32_t* stripByteCountsArray = stripByteCounts->getData<uint32_t>();

    size_t numStrips = offsetsCount;

    Vector<uint32_t> stripOffsets;

    // Calculate updated byte offsets
    for (size_t i = 0; i < numStrips; ++i) {
        stripOffsets.add(offset);
        offset += stripByteCountsArray[i];
    }

    sp<TiffEntry> newOffsets = TiffWriter::uncheckedBuildEntry(TAG_STRIPOFFSETS, LONG,
            static_cast<uint32_t>(numStrips), UNDEFINED_ENDIAN, stripOffsets.array());

    if (newOffsets == NULL) {
        ALOGE("%s: Coult not build updated offsets entry in IFD %u", __FUNCTION__, mIfdId);
        return BAD_VALUE;
    }

    if (addEntry(newOffsets) != OK) {
        ALOGE("%s: Failed to add updated offsets entry in IFD %u", __FUNCTION__, mIfdId);
        return BAD_VALUE;
    }
    return OK;
}

uint32_t TiffIfd::getStripSize() const {
    sp<TiffEntry> stripByteCounts = getEntry(TAG_STRIPBYTECOUNTS);
    if (stripByteCounts == NULL) {
        ALOGE("%s: IFD %u does not contain StripByteCounts entry.", __FUNCTION__, mIfdId);
        return BAD_VALUE;
    }

    uint32_t count = stripByteCounts->getCount();
    const uint32_t* byteCounts = stripByteCounts->getData<uint32_t>();

    uint32_t total = 0;
    for (size_t i = 0; i < static_cast<size_t>(count); ++i) {
        total += byteCounts[i];
    }
    return total;
}

String8 TiffIfd::toString() const {
    size_t s = mEntries.size();
    String8 output;
    output.appendFormat("[ifd: %x, num_entries: %zu, entries:\n", getId(), s);
    for(size_t i = 0; i < mEntries.size(); ++i) {
        output.append("\t");
        output.append(mEntries[i]->toString());
        output.append("\n");
    }
    output.append(", next_ifd: %x]", ((mNextIfd != NULL) ? mNextIfd->getId() : 0));
    return output;
}

void TiffIfd::log() const {
    size_t s = mEntries.size();
    ALOGI("[ifd: %x, num_entries: %zu, entries:\n", getId(), s);
    for(size_t i = 0; i < s; ++i) {
        ALOGI("\t%s", mEntries[i]->toString().string());
    }
    ALOGI(", next_ifd: %x]", ((mNextIfd != NULL) ? mNextIfd->getId() : 0));
}

} /*namespace img_utils*/
} /*namespace android*/