2 * Snappy decompression algorithm
3 * Copyright (c) 2015 Luca Barbato
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "libavutil/mem.h"
24 #include "bytestream.h"
34 static int64_t bytestream2_get_levarint(GetByteContext *gb)
41 tmp = bytestream2_get_byte(gb);
42 if (shift > 31 || ((tmp & 127LL) << shift) > INT_MAX)
43 return AVERROR_INVALIDDATA;
44 val |= (tmp & 127) << shift;
51 static int snappy_literal(GetByteContext *gb, uint8_t *p, int size, int val)
57 len += bytestream2_get_le32(gb);
60 len += bytestream2_get_le24(gb);
63 len += bytestream2_get_le16(gb);
66 len += bytestream2_get_byte(gb);
73 return AVERROR_INVALIDDATA;
75 bytestream2_get_buffer(gb, p, len);
80 static int snappy_copy(uint8_t *start, uint8_t *p, int size,
81 unsigned int off, int len)
85 if (off > p - start || size < len)
86 return AVERROR_INVALIDDATA;
90 for (i = 0; i < len; i++)
96 static int snappy_copy1(GetByteContext *gb, uint8_t *start, uint8_t *p,
99 int len = 4 + (val & 0x7);
100 unsigned int off = bytestream2_get_byte(gb) | (val & 0x38) << 5;
102 return snappy_copy(start, p, size, off, len);
105 static int snappy_copy2(GetByteContext *gb, uint8_t *start, uint8_t *p,
109 unsigned int off = bytestream2_get_le16(gb);
111 return snappy_copy(start, p, size, off, len);
114 static int snappy_copy4(GetByteContext *gb, uint8_t *start, uint8_t *p,
118 unsigned int off = bytestream2_get_le32(gb);
120 return snappy_copy(start, p, size, off, len);
123 static int64_t decode_len(GetByteContext *gb)
125 int64_t len = bytestream2_get_levarint(gb);
127 if (len < 0 || len > UINT_MAX)
128 return AVERROR_INVALIDDATA;
133 int64_t ff_snappy_peek_uncompressed_length(GetByteContext *gb)
135 int pos = bytestream2_get_bytes_left(gb);
136 int64_t len = decode_len(gb);
138 bytestream2_seek(gb, -pos, SEEK_END);
143 int ff_snappy_uncompress(GetByteContext *gb, uint8_t *buf, int64_t *size)
145 int64_t len = decode_len(gb);
153 return AVERROR_BUFFER_TOO_SMALL;
158 while (bytestream2_get_bytes_left(gb) > 0) {
159 uint8_t s = bytestream2_get_byte(gb);
164 ret = snappy_literal(gb, p, len, val);
167 ret = snappy_copy1(gb, buf, p, len, val);
170 ret = snappy_copy2(gb, buf, p, len, val);
173 ret = snappy_copy4(gb, buf, p, len, val);