]> git.sesse.net Git - ffmpeg/blob - libavcodec/hapenc.c
Merge commit 'ebe8b5d947c41449c684f17c6826fe6bc46c0360'
[ffmpeg] / libavcodec / hapenc.c
1 /*
2  * Vidvox Hap encoder
3  * Copyright (C) 2015 Vittorio Giovara <vittorio.giovara@gmail.com>
4  * Copyright (C) 2015 Tom Butterworth <bangnoise@gmail.com>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * Hap encoder
26  *
27  * Fourcc: Hap1, Hap5, HapY
28  *
29  * https://github.com/Vidvox/hap/blob/master/documentation/HapVideoDRAFT.md
30  */
31
32 #include <stdint.h>
33 #include "snappy-c.h"
34
35 #include "libavutil/frame.h"
36 #include "libavutil/imgutils.h"
37 #include "libavutil/intreadwrite.h"
38 #include "libavutil/opt.h"
39
40 #include "avcodec.h"
41 #include "bytestream.h"
42 #include "hap.h"
43 #include "internal.h"
44 #include "texturedsp.h"
45
46 #define HAP_MAX_CHUNKS 64
47
48 enum HapHeaderLength {
49     HAP_HDR_4_BYTE = 4,
50     HAP_HDR_8_BYTE = 8,
51 };
52
53 static void compress_texture(AVCodecContext *avctx, const AVFrame *f)
54 {
55     HapContext *ctx = avctx->priv_data;
56     uint8_t *out = ctx->tex_buf;
57     int i, j;
58
59     for (j = 0; j < avctx->height; j += 4) {
60         for (i = 0; i < avctx->width; i += 4) {
61             uint8_t *p = f->data[0] + i * 4 + j * f->linesize[0];
62             const int step = ctx->tex_fun(out, f->linesize[0], p);
63             out += step;
64         }
65     }
66 }
67
68 /* section_length does not include the header */
69 static void hap_write_section_header(PutByteContext *pbc,
70                                      enum HapHeaderLength header_length,
71                                      int section_length,
72                                      enum HapSectionType section_type)
73 {
74     /* The first three bytes are the length of the section (not including the
75      * header) or zero if using an eight-byte header.
76      * For an eight-byte header, the length is in the last four bytes.
77      * The fourth byte stores the section type. */
78     bytestream2_put_le24(pbc, header_length == HAP_HDR_8_BYTE ? 0 : section_length);
79     bytestream2_put_byte(pbc, section_type);
80
81     if (header_length == HAP_HDR_8_BYTE) {
82         bytestream2_put_le32(pbc, section_length);
83     }
84 }
85
86 static int hap_compress_frame(AVCodecContext *avctx, uint8_t *dst)
87 {
88     HapContext *ctx = avctx->priv_data;
89     int i, final_size = 0;
90
91     for (i = 0; i < ctx->chunk_count; i++) {
92         HapChunk *chunk = &ctx->chunks[i];
93         uint8_t *chunk_src, *chunk_dst;
94         int ret;
95
96         if (i == 0) {
97             chunk->compressed_offset = 0;
98         } else {
99             chunk->compressed_offset = ctx->chunks[i-1].compressed_offset
100                                        + ctx->chunks[i-1].compressed_size;
101         }
102         chunk->uncompressed_size = ctx->tex_size / ctx->chunk_count;
103         chunk->uncompressed_offset = i * chunk->uncompressed_size;
104         chunk->compressed_size = ctx->max_snappy;
105         chunk_src = ctx->tex_buf + chunk->uncompressed_offset;
106         chunk_dst = dst + chunk->compressed_offset;
107
108         /* Compress with snappy too, write directly on packet buffer. */
109         ret = snappy_compress(chunk_src, chunk->uncompressed_size,
110                               chunk_dst, &chunk->compressed_size);
111         if (ret != SNAPPY_OK) {
112             av_log(avctx, AV_LOG_ERROR, "Snappy compress error.\n");
113             return AVERROR_BUG;
114         }
115
116         /* If there is no gain from snappy, just use the raw texture. */
117         if (chunk->compressed_size >= chunk->uncompressed_size) {
118             av_log(avctx, AV_LOG_VERBOSE,
119                    "Snappy buffer bigger than uncompressed (%lu >= %lu bytes).\n",
120                    chunk->compressed_size, chunk->uncompressed_size);
121             memcpy(chunk_dst, chunk_src, chunk->uncompressed_size);
122             chunk->compressor = HAP_COMP_NONE;
123             chunk->compressed_size = chunk->uncompressed_size;
124         } else {
125             chunk->compressor = HAP_COMP_SNAPPY;
126         }
127
128         final_size += chunk->compressed_size;
129     }
130
131     return final_size;
132 }
133
134 static int hap_decode_instructions_length(HapContext *ctx)
135 {
136     /* = Second-Stage Compressor Table + Chunk Size Table + headers for both sections
137      * = chunk_count + (4 * chunk_count) + 4 + 4 */
138     return (5 * ctx->chunk_count) + 8;
139 }
140
141 static int hap_header_length(HapContext *ctx)
142 {
143     /* Top section header (long version) */
144     int length = HAP_HDR_8_BYTE;
145
146     if (ctx->chunk_count > 1) {
147         /* Decode Instructions header (short) + Decode Instructions Container */
148         length += HAP_HDR_4_BYTE + hap_decode_instructions_length(ctx);
149     }
150
151     return length;
152 }
153
154 static void hap_write_frame_header(HapContext *ctx, uint8_t *dst, int frame_length)
155 {
156     PutByteContext pbc;
157     int i;
158
159     bytestream2_init_writer(&pbc, dst, frame_length);
160     if (ctx->chunk_count == 1) {
161         /* Write a simple header */
162         hap_write_section_header(&pbc, HAP_HDR_8_BYTE, frame_length - 8,
163                                  ctx->chunks[0].compressor | ctx->opt_tex_fmt);
164     } else {
165         /* Write a complex header with Decode Instructions Container */
166         hap_write_section_header(&pbc, HAP_HDR_8_BYTE, frame_length - 8,
167                                  HAP_COMP_COMPLEX | ctx->opt_tex_fmt);
168         hap_write_section_header(&pbc, HAP_HDR_4_BYTE, hap_decode_instructions_length(ctx),
169                                  HAP_ST_DECODE_INSTRUCTIONS);
170         hap_write_section_header(&pbc, HAP_HDR_4_BYTE, ctx->chunk_count,
171                                  HAP_ST_COMPRESSOR_TABLE);
172
173         for (i = 0; i < ctx->chunk_count; i++) {
174             bytestream2_put_byte(&pbc, ctx->chunks[i].compressor >> 4);
175         }
176
177         hap_write_section_header(&pbc, HAP_HDR_4_BYTE, ctx->chunk_count * 4,
178                                  HAP_ST_SIZE_TABLE);
179
180         for (i = 0; i < ctx->chunk_count; i++) {
181             bytestream2_put_le32(&pbc, ctx->chunks[i].compressed_size);
182         }
183     }
184 }
185
186 static int hap_encode(AVCodecContext *avctx, AVPacket *pkt,
187                       const AVFrame *frame, int *got_packet)
188 {
189     HapContext *ctx = avctx->priv_data;
190     int header_length = hap_header_length(ctx);
191     int final_data_size, ret;
192     int pktsize = FFMAX(ctx->tex_size, ctx->max_snappy * ctx->chunk_count) + header_length;
193
194     /* Allocate maximum size packet, shrink later. */
195     ret = ff_alloc_packet(pkt, pktsize);
196     if (ret < 0)
197         return ret;
198
199     /* DXTC compression. */
200     compress_texture(avctx, frame);
201
202     /* Compress (using Snappy) the frame */
203     final_data_size = hap_compress_frame(avctx, pkt->data + header_length);
204     if (final_data_size < 0)
205         return final_data_size;
206
207     /* Write header at the start. */
208     hap_write_frame_header(ctx, pkt->data, final_data_size + header_length);
209
210     av_shrink_packet(pkt, final_data_size + header_length);
211     pkt->flags |= AV_PKT_FLAG_KEY;
212     *got_packet = 1;
213     return 0;
214 }
215
216 static av_cold int hap_init(AVCodecContext *avctx)
217 {
218     HapContext *ctx = avctx->priv_data;
219     int ratio;
220     int corrected_chunk_count;
221     int ret = av_image_check_size(avctx->width, avctx->height, 0, avctx);
222
223     if (ret < 0) {
224         av_log(avctx, AV_LOG_ERROR, "Invalid video size %dx%d.\n",
225                avctx->width, avctx->height);
226         return ret;
227     }
228
229     if (avctx->width % 4 || avctx->height % 4) {
230         av_log(avctx, AV_LOG_ERROR, "Video size %dx%d is not multiple of 4.\n",
231                avctx->width, avctx->height);
232         return AVERROR_INVALIDDATA;
233     }
234
235     ff_texturedspenc_init(&ctx->dxtc);
236
237     switch (ctx->opt_tex_fmt) {
238     case HAP_FMT_RGBDXT1:
239         ratio = 8;
240         avctx->codec_tag = MKTAG('H', 'a', 'p', '1');
241         ctx->tex_fun = ctx->dxtc.dxt1_block;
242         break;
243     case HAP_FMT_RGBADXT5:
244         ratio = 4;
245         avctx->codec_tag = MKTAG('H', 'a', 'p', '5');
246         ctx->tex_fun = ctx->dxtc.dxt5_block;
247         break;
248     case HAP_FMT_YCOCGDXT5:
249         ratio = 4;
250         avctx->codec_tag = MKTAG('H', 'a', 'p', 'Y');
251         ctx->tex_fun = ctx->dxtc.dxt5ys_block;
252         break;
253     default:
254         av_log(avctx, AV_LOG_ERROR, "Invalid format %02X\n", ctx->opt_tex_fmt);
255         return AVERROR_INVALIDDATA;
256     }
257
258     /* Texture compression ratio is constant, so can we computer
259      * beforehand the final size of the uncompressed buffer. */
260     ctx->tex_size   = FFALIGN(avctx->width,  TEXTURE_BLOCK_W) *
261                       FFALIGN(avctx->height, TEXTURE_BLOCK_H) * 4 / ratio;
262
263     /* Round the chunk count to divide evenly on DXT block edges */
264     corrected_chunk_count = av_clip(ctx->opt_chunk_count, 1, HAP_MAX_CHUNKS);
265     while ((ctx->tex_size / (64 / ratio)) % corrected_chunk_count != 0) {
266         corrected_chunk_count--;
267     }
268     if (corrected_chunk_count != ctx->opt_chunk_count) {
269         av_log(avctx, AV_LOG_INFO, "%d chunks requested but %d used.\n",
270                                     ctx->opt_chunk_count, corrected_chunk_count);
271     }
272     ret = ff_hap_set_chunk_count(ctx, corrected_chunk_count, 1);
273     if (ret != 0)
274         return ret;
275
276     ctx->max_snappy = snappy_max_compressed_length(ctx->tex_size / corrected_chunk_count);
277
278     ctx->tex_buf  = av_malloc(ctx->tex_size);
279     if (!ctx->tex_buf)
280         return AVERROR(ENOMEM);
281
282     return 0;
283 }
284
285 static av_cold int hap_close(AVCodecContext *avctx)
286 {
287     HapContext *ctx = avctx->priv_data;
288
289     ff_hap_free_context(ctx);
290
291     return 0;
292 }
293
294 #define OFFSET(x) offsetof(HapContext, x)
295 #define FLAGS     AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
296 static const AVOption options[] = {
297     { "format", NULL, OFFSET(opt_tex_fmt), AV_OPT_TYPE_INT, { .i64 = HAP_FMT_RGBDXT1 }, HAP_FMT_RGBDXT1, HAP_FMT_YCOCGDXT5, FLAGS, "format" },
298         { "hap",       "Hap 1 (DXT1 textures)", 0, AV_OPT_TYPE_CONST, { .i64 = HAP_FMT_RGBDXT1   }, 0, 0, FLAGS, "format" },
299         { "hap_alpha", "Hap Alpha (DXT5 textures)", 0, AV_OPT_TYPE_CONST, { .i64 = HAP_FMT_RGBADXT5  }, 0, 0, FLAGS, "format" },
300         { "hap_q",     "Hap Q (DXT5-YCoCg textures)", 0, AV_OPT_TYPE_CONST, { .i64 = HAP_FMT_YCOCGDXT5 }, 0, 0, FLAGS, "format" },
301     { "chunks", "chunk count", OFFSET(opt_chunk_count), AV_OPT_TYPE_INT, {.i64 = 1 }, 1, HAP_MAX_CHUNKS, FLAGS, },
302     { NULL },
303 };
304
305 static const AVClass hapenc_class = {
306     .class_name = "Hap encoder",
307     .item_name  = av_default_item_name,
308     .option     = options,
309     .version    = LIBAVUTIL_VERSION_INT,
310 };
311
312 AVCodec ff_hap_encoder = {
313     .name           = "hap",
314     .long_name      = NULL_IF_CONFIG_SMALL("Vidvox Hap encoder"),
315     .type           = AVMEDIA_TYPE_VIDEO,
316     .id             = AV_CODEC_ID_HAP,
317     .priv_data_size = sizeof(HapContext),
318     .priv_class     = &hapenc_class,
319     .init           = hap_init,
320     .encode2        = hap_encode,
321     .close          = hap_close,
322     .pix_fmts       = (const enum AVPixelFormat[]) {
323         AV_PIX_FMT_RGBA, AV_PIX_FMT_NONE,
324     },
325     .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE |
326                       FF_CODEC_CAP_INIT_CLEANUP,
327 };