Make SkCodec support peek() and read()
- Update SkCodec's dox to point out that some of the data must be
read twice in order to decode
- Add an accessor that reports how much is needed for reading twice
- Make SkCodec default to use peek()
If an input stream supports peek()ing, peek() instead of reading.
This way the stream need not implement rewind()
- Make SkCodec use read() + rewind() as a backup
So that streams without peek() implemented can still function
properly (assuming they can rewind).
- read everything we may need to determine the format once
In SkCodec::NewFromStream, peek()/read() 14 bytes, which is enough
to read all of the types we support. Pass the buffer to each subtype,
which will have enough info to determine whether it is the right
type. This simplifies the code and results in less reading and
rewinding.
- NOTE: SkWbmpCodec needs the following number of bytes for the header
+ 1 (type)
+ 1 (reserved)
+ 3 (width - bytes needed to support up to 0xFFFF)
+ 3 (height - bytes needed to support up to 0xFFFF)
= 8
- in SkWebpCodec, support using read + rewind as a backup if peek does
not work.
A change in Android will add peek() to JavaInputStreamAdapter.
BUG=skia:3257
Review URL: https://codereview.chromium.org/1472123002
diff --git a/src/codec/SkWebpCodec.cpp b/src/codec/SkWebpCodec.cpp
index 3c61b93..2137877 100644
--- a/src/codec/SkWebpCodec.cpp
+++ b/src/codec/SkWebpCodec.cpp
@@ -20,26 +20,26 @@
#include "webp/decode.h"
#include "webp/encode.h"
-bool SkWebpCodec::IsWebp(SkStream* stream) {
+bool SkWebpCodec::IsWebp(const void* buf, size_t bytesRead) {
// WEBP starts with the following:
// RIFFXXXXWEBPVP
// Where XXXX is unspecified.
- const char LENGTH = 14;
- char bytes[LENGTH];
- if (stream->read(&bytes, LENGTH) != LENGTH) {
- return false;
- }
- return !memcmp(bytes, "RIFF", 4) && !memcmp(&bytes[8], "WEBPVP", 6);
+ const char* bytes = static_cast<const char*>(buf);
+ return bytesRead >= 14 && !memcmp(bytes, "RIFF", 4) && !memcmp(&bytes[8], "WEBPVP", 6);
}
-static const size_t WEBP_VP8_HEADER_SIZE = 30;
-
// Parse headers of RIFF container, and check for valid Webp (VP8) content.
// NOTE: This calls peek instead of read, since onGetPixels will need these
// bytes again.
static bool webp_parse_header(SkStream* stream, SkImageInfo* info) {
unsigned char buffer[WEBP_VP8_HEADER_SIZE];
- if (!stream->peek(buffer, WEBP_VP8_HEADER_SIZE)) {
+ SkASSERT(WEBP_VP8_HEADER_SIZE <= SkCodec::MinBufferedBytesNeeded());
+
+ const size_t bytesPeeked = stream->peek(buffer, WEBP_VP8_HEADER_SIZE);
+ if (bytesPeeked != WEBP_VP8_HEADER_SIZE) {
+ // Use read + rewind as a backup
+ if (stream->read(buffer, WEBP_VP8_HEADER_SIZE) != WEBP_VP8_HEADER_SIZE
+ || !stream->rewind())
return false;
}