]> git.sesse.net Git - ffmpeg/blob - libavcodec/jpeglsenc.c
avcodec/jpeglsenc: Don't modify frame we don't own
[ffmpeg] / libavcodec / jpeglsenc.c
1 /*
2  * JPEG-LS encoder
3  * Copyright (c) 2003 Michael Niedermayer
4  * Copyright (c) 2006 Konstantin Shishkov
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  * JPEG-LS encoder.
26  */
27
28 #include "avcodec.h"
29 #include "bytestream.h"
30 #include "get_bits.h"
31 #include "put_bits.h"
32 #include "golomb.h"
33 #include "internal.h"
34 #include "mathops.h"
35 #include "mjpeg.h"
36 #include "mjpegenc.h"
37 #include "jpegls.h"
38
39 typedef struct JPEGLSContext {
40     AVClass *class;
41
42     int pred;
43 } JPEGLSContext;
44
45 static inline void put_marker_byteu(PutByteContext *pb, enum JpegMarker code)
46 {
47     bytestream2_put_byteu(pb, 0xff);
48     bytestream2_put_byteu(pb, code);
49 }
50
51 static inline void put_marker_byte(PutByteContext *pb, enum JpegMarker code)
52 {
53     bytestream2_put_byte(pb, 0xff);
54     bytestream2_put_byte(pb, code);
55 }
56
57 /**
58  * Encode error from regular symbol
59  */
60 static inline void ls_encode_regular(JLSState *state, PutBitContext *pb, int Q,
61                                      int err)
62 {
63     int k;
64     int val;
65     int map;
66
67     for (k = 0; (state->N[Q] << k) < state->A[Q]; k++)
68         ;
69
70     map = !state->near && !k && (2 * state->B[Q] <= -state->N[Q]);
71
72     if (err < 0)
73         err += state->range;
74     if (err >= (state->range + 1 >> 1)) {
75         err -= state->range;
76         val  = 2 * FFABS(err) - 1 - map;
77     } else
78         val = 2 * err + map;
79
80     set_ur_golomb_jpegls(pb, val, k, state->limit, state->qbpp);
81
82     ff_jpegls_update_state_regular(state, Q, err);
83 }
84
85 /**
86  * Encode error from run termination
87  */
88 static inline void ls_encode_runterm(JLSState *state, PutBitContext *pb,
89                                      int RItype, int err, int limit_add)
90 {
91     int k;
92     int val, map;
93     int Q = 365 + RItype;
94     int temp;
95
96     temp = state->A[Q];
97     if (RItype)
98         temp += state->N[Q] >> 1;
99     for (k = 0; (state->N[Q] << k) < temp; k++)
100         ;
101     map = 0;
102     if (!k && err && (2 * state->B[Q] < state->N[Q]))
103         map = 1;
104
105     if (err < 0)
106         val = -(2 * err) - 1 - RItype + map;
107     else
108         val = 2 * err - RItype - map;
109     set_ur_golomb_jpegls(pb, val, k, state->limit - limit_add - 1, state->qbpp);
110
111     if (err < 0)
112         state->B[Q]++;
113     state->A[Q] += (val + 1 - RItype) >> 1;
114
115     ff_jpegls_downscale_state(state, Q);
116 }
117
118 /**
119  * Encode run value as specified by JPEG-LS standard
120  */
121 static inline void ls_encode_run(JLSState *state, PutBitContext *pb, int run,
122                                  int comp, int trail)
123 {
124     while (run >= (1 << ff_log2_run[state->run_index[comp]])) {
125         put_bits(pb, 1, 1);
126         run -= 1 << ff_log2_run[state->run_index[comp]];
127         if (state->run_index[comp] < 31)
128             state->run_index[comp]++;
129     }
130     /* if hit EOL, encode another full run, else encode aborted run */
131     if (!trail && run) {
132         put_bits(pb, 1, 1);
133     } else if (trail) {
134         put_bits(pb, 1, 0);
135         if (ff_log2_run[state->run_index[comp]])
136             put_bits(pb, ff_log2_run[state->run_index[comp]], run);
137     }
138 }
139
140 /**
141  * Encode one line of image
142  */
143 static inline void ls_encode_line(JLSState *state, PutBitContext *pb,
144                                   void *last, void *cur, const void *in, int last2, int w,
145                                   int stride, int comp, int bits)
146 {
147     int x = 0;
148     int Ra, Rb, Rc, Rd;
149     int D0, D1, D2;
150
151     while (x < w) {
152         int err, pred, sign;
153
154         /* compute gradients */
155         Ra = x ? R(cur, x - stride) : R(last, x);
156         Rb = R(last, x);
157         Rc = x ? R(last, x - stride) : last2;
158         Rd = (x >= w - stride) ? R(last, x) : R(last, x + stride);
159         D0 = Rd - Rb;
160         D1 = Rb - Rc;
161         D2 = Rc - Ra;
162
163         /* run mode */
164         if ((FFABS(D0) <= state->near) &&
165             (FFABS(D1) <= state->near) &&
166             (FFABS(D2) <= state->near)) {
167             int RUNval, RItype, run;
168
169             run    = 0;
170             RUNval = Ra;
171             while (x < w && (FFABS(R(in, x) - RUNval) <= state->near)) {
172                 run++;
173                 W(cur, x, Ra);
174                 x += stride;
175             }
176             ls_encode_run(state, pb, run, comp, x < w);
177             if (x >= w)
178                 return;
179             Rb     = R(last, x);
180             RItype = FFABS(Ra - Rb) <= state->near;
181             pred   = RItype ? Ra : Rb;
182             err    = R(in, x) - pred;
183
184             if (!RItype && Ra > Rb)
185                 err = -err;
186
187             if (state->near) {
188                 if (err > 0)
189                     err =  (state->near + err) / state->twonear;
190                 else
191                     err = -(state->near - err) / state->twonear;
192
193                 if (RItype || (Rb >= Ra))
194                     Ra = av_clip(pred + err * state->twonear, 0, state->maxval);
195                 else
196                     Ra = av_clip(pred - err * state->twonear, 0, state->maxval);
197                 W(cur, x, Ra);
198             } else
199                 W(cur, x, R(in, x));
200
201             if (err < 0)
202                 err += state->range;
203             if (err >= state->range + 1 >> 1)
204                 err -= state->range;
205
206             ls_encode_runterm(state, pb, RItype, err,
207                               ff_log2_run[state->run_index[comp]]);
208
209             if (state->run_index[comp] > 0)
210                 state->run_index[comp]--;
211         } else { /* regular mode */
212             int context;
213
214             context = ff_jpegls_quantize(state, D0) * 81 +
215                       ff_jpegls_quantize(state, D1) *  9 +
216                       ff_jpegls_quantize(state, D2);
217             pred    = mid_pred(Ra, Ra + Rb - Rc, Rb);
218
219             if (context < 0) {
220                 context = -context;
221                 sign    = 1;
222                 pred    = av_clip(pred - state->C[context], 0, state->maxval);
223                 err     = pred - R(in, x);
224             } else {
225                 sign = 0;
226                 pred = av_clip(pred + state->C[context], 0, state->maxval);
227                 err  = R(in, x) - pred;
228             }
229
230             if (state->near) {
231                 if (err > 0)
232                     err =  (state->near + err) / state->twonear;
233                 else
234                     err = -(state->near - err) / state->twonear;
235                 if (!sign)
236                     Ra = av_clip(pred + err * state->twonear, 0, state->maxval);
237                 else
238                     Ra = av_clip(pred - err * state->twonear, 0, state->maxval);
239                 W(cur, x, Ra);
240             } else
241                 W(cur, x, R(in, x));
242
243             ls_encode_regular(state, pb, context, err);
244         }
245         x += stride;
246     }
247 }
248
249 static void ls_store_lse(JLSState *state, PutByteContext *pb)
250 {
251     /* Test if we have default params and don't need to store LSE */
252     JLSState state2 = { 0 };
253     state2.bpp  = state->bpp;
254     state2.near = state->near;
255     ff_jpegls_reset_coding_parameters(&state2, 1);
256     if (state->T1 == state2.T1 &&
257         state->T2 == state2.T2 &&
258         state->T3 == state2.T3 &&
259         state->reset == state2.reset)
260         return;
261     /* store LSE type 1 */
262     put_marker_byteu(pb, LSE);
263     bytestream2_put_be16u(pb, 13);
264     bytestream2_put_byteu(pb, 1);
265     bytestream2_put_be16u(pb, state->maxval);
266     bytestream2_put_be16u(pb, state->T1);
267     bytestream2_put_be16u(pb, state->T2);
268     bytestream2_put_be16u(pb, state->T3);
269     bytestream2_put_be16u(pb, state->reset);
270 }
271
272 static int encode_picture_ls(AVCodecContext *avctx, AVPacket *pkt,
273                              const AVFrame *pict, int *got_packet)
274 {
275     JPEGLSContext *ctx = avctx->priv_data;
276     const AVFrame *const p = pict;
277     PutByteContext pb;
278     PutBitContext pb2;
279     GetBitContext gb;
280     uint8_t *buf2 = NULL;
281     uint8_t *zero = NULL;
282     const uint8_t *in;
283     uint8_t *last, *cur;
284     JLSState *state = NULL;
285     int i, size, ret;
286     int comps;
287
288 #if FF_API_PRIVATE_OPT
289 FF_DISABLE_DEPRECATION_WARNINGS
290     if (avctx->prediction_method)
291         ctx->pred = avctx->prediction_method;
292 FF_ENABLE_DEPRECATION_WARNINGS
293 #endif
294
295     if (avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
296         avctx->pix_fmt == AV_PIX_FMT_GRAY16)
297         comps = 1;
298     else
299         comps = 3;
300
301     if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width  *avctx->height * comps * 4 +
302                                 AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
303         return ret;
304
305     buf2 = av_malloc(pkt->size);
306     if (!buf2)
307         goto memfail;
308
309     bytestream2_init_writer(&pb, pkt->data, pkt->size);
310     init_put_bits(&pb2, buf2, pkt->size);
311
312     /* write our own JPEG header, can't use mjpeg_picture_header */
313     put_marker_byteu(&pb, SOI);
314     put_marker_byteu(&pb, SOF48);
315     bytestream2_put_be16u(&pb, 8 + comps * 3); // header size depends on components
316     bytestream2_put_byteu(&pb, (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8);  // bpp
317     bytestream2_put_be16u(&pb, avctx->height);
318     bytestream2_put_be16u(&pb, avctx->width);
319     bytestream2_put_byteu(&pb, comps);          // components
320     for (i = 1; i <= comps; i++) {
321         bytestream2_put_byteu(&pb, i);     // component ID
322         bytestream2_put_byteu(&pb, 0x11);  // subsampling: none
323         bytestream2_put_byteu(&pb, 0);     // Tiq, used by JPEG-LS ext
324     }
325
326     put_marker_byteu(&pb, SOS);
327     bytestream2_put_be16u(&pb, 6 + comps * 2);
328     bytestream2_put_byteu(&pb, comps);
329     for (i = 1; i <= comps; i++) {
330         bytestream2_put_byteu(&pb, i);   // component ID
331         bytestream2_put_byteu(&pb, 0);   // mapping index: none
332     }
333     bytestream2_put_byteu(&pb, ctx->pred);
334     bytestream2_put_byteu(&pb, (comps > 1) ? 1 : 0);  // interleaving: 0 - plane, 1 - line
335     bytestream2_put_byteu(&pb, 0);  // point transform: none
336
337     state = av_mallocz(sizeof(JLSState));
338     if (!state)
339         goto memfail;
340
341     /* initialize JPEG-LS state from JPEG parameters */
342     state->near = ctx->pred;
343     state->bpp  = (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8;
344     ff_jpegls_reset_coding_parameters(state, 0);
345     ff_jpegls_init_state(state);
346
347     ls_store_lse(state, &pb);
348
349     zero = last = av_calloc(FFABS(p->linesize[0]), 2);
350     if (!zero)
351         goto memfail;
352     cur = zero + FFABS(p->linesize[0]);
353
354     in = p->data[0];
355     if (avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
356         int t = 0;
357
358         for (i = 0; i < avctx->height; i++) {
359             ls_encode_line(state, &pb2, last, cur, in, t, avctx->width, 1, 0, 8);
360             t    = last[0];
361             FFSWAP(void *, last, cur);
362             in += p->linesize[0];
363         }
364     } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY16) {
365         int t = 0;
366
367         for (i = 0; i < avctx->height; i++) {
368             ls_encode_line(state, &pb2, last, cur, in, t, avctx->width, 1, 0, 16);
369             t    = *((uint16_t *)last);
370             FFSWAP(void *, last, cur);
371             in += p->linesize[0];
372         }
373     } else if (avctx->pix_fmt == AV_PIX_FMT_RGB24) {
374         int j, width;
375         int Rc[3] = { 0, 0, 0 };
376
377         width = avctx->width * 3;
378         for (i = 0; i < avctx->height; i++) {
379             for (j = 0; j < 3; j++) {
380                 ls_encode_line(state, &pb2, last + j, cur + j, in + j, Rc[j],
381                                width, 3, j, 8);
382                 Rc[j] = last[j];
383             }
384             FFSWAP(void *, last, cur);
385             in += p->linesize[0];
386         }
387     } else if (avctx->pix_fmt == AV_PIX_FMT_BGR24) {
388         int j, width;
389         int Rc[3] = { 0, 0, 0 };
390
391         width = avctx->width * 3;
392         for (i = 0; i < avctx->height; i++) {
393             for (j = 2; j >= 0; j--) {
394                 ls_encode_line(state, &pb2, last + j, cur + j, in + j, Rc[j],
395                                width, 3, j, 8);
396                 Rc[j] = last[j];
397             }
398             FFSWAP(void *, last, cur);
399             in += p->linesize[0];
400         }
401     }
402
403     av_freep(&zero);
404     av_freep(&state);
405
406     /* the specification says that after doing 0xff escaping unused bits in
407      * the last byte must be set to 0, so just append 7 "optional" zero bits
408      * to avoid special-casing. */
409     put_bits(&pb2, 7, 0);
410     size = put_bits_count(&pb2);
411     flush_put_bits(&pb2);
412     /* do escape coding */
413     init_get_bits(&gb, buf2, size);
414     size -= 7;
415     while (get_bits_count(&gb) < size) {
416         int v;
417         v = get_bits(&gb, 8);
418         bytestream2_put_byte(&pb, v);
419         if (v == 0xFF) {
420             v = get_bits(&gb, 7);
421             bytestream2_put_byte(&pb, v);
422         }
423     }
424     av_freep(&buf2);
425
426     /* End of image */
427     put_marker_byte(&pb, EOI);
428
429     emms_c();
430
431     pkt->size   = bytestream2_tell_p(&pb);
432     pkt->flags |= AV_PKT_FLAG_KEY;
433     *got_packet = 1;
434     return 0;
435
436 memfail:
437     av_freep(&buf2);
438     av_freep(&state);
439     av_freep(&zero);
440     return AVERROR(ENOMEM);
441 }
442
443 static av_cold int encode_init_ls(AVCodecContext *ctx)
444 {
445 #if FF_API_CODED_FRAME
446 FF_DISABLE_DEPRECATION_WARNINGS
447     ctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
448     ctx->coded_frame->key_frame = 1;
449 FF_ENABLE_DEPRECATION_WARNINGS
450 #endif
451
452     if (ctx->pix_fmt != AV_PIX_FMT_GRAY8  &&
453         ctx->pix_fmt != AV_PIX_FMT_GRAY16 &&
454         ctx->pix_fmt != AV_PIX_FMT_RGB24  &&
455         ctx->pix_fmt != AV_PIX_FMT_BGR24) {
456         av_log(ctx, AV_LOG_ERROR,
457                "Only grayscale and RGB24/BGR24 images are supported\n");
458         return -1;
459     }
460     return 0;
461 }
462
463 #define OFFSET(x) offsetof(JPEGLSContext, x)
464 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
465 static const AVOption options[] = {
466 { "pred", "Prediction method", OFFSET(pred), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, VE, "pred" },
467     { "left",   NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "pred" },
468     { "plane",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, "pred" },
469     { "median", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, INT_MIN, INT_MAX, VE, "pred" },
470
471     { NULL},
472 };
473
474 static const AVClass jpegls_class = {
475     .class_name = "jpegls",
476     .item_name  = av_default_item_name,
477     .option     = options,
478     .version    = LIBAVUTIL_VERSION_INT,
479 };
480
481 AVCodec ff_jpegls_encoder = {
482     .name           = "jpegls",
483     .long_name      = NULL_IF_CONFIG_SMALL("JPEG-LS"),
484     .type           = AVMEDIA_TYPE_VIDEO,
485     .id             = AV_CODEC_ID_JPEGLS,
486     .priv_data_size = sizeof(JPEGLSContext),
487     .priv_class     = &jpegls_class,
488     .init           = encode_init_ls,
489     .capabilities   = AV_CODEC_CAP_FRAME_THREADS,
490     .encode2        = encode_picture_ls,
491     .pix_fmts       = (const enum AVPixelFormat[]) {
492         AV_PIX_FMT_BGR24, AV_PIX_FMT_RGB24,
493         AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16,
494         AV_PIX_FMT_NONE
495     },
496     .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE |
497                       FF_CODEC_CAP_INIT_CLEANUP,
498 };