Statistics
| Branch: | Revision:

ffmpeg / libavcodec / jpeg_ls.c @ bb54f6ab

History | View | Annotate | Download (25.2 KB)

1
/*
2
 * JPEG-LS encoder and decoder
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
#include "golomb.h"
24

    
25
/**
26
 * @file jpeg_ls.c
27
 * JPEG-LS encoder and decoder.
28
 */
29

    
30
typedef struct JpeglsContext{
31
    AVCodecContext *avctx;
32
    AVFrame picture;
33
}JpeglsContext;
34

    
35
typedef struct JLSState{
36
    int T1, T2, T3;
37
    int A[367], B[367], C[365], N[367];
38
    int limit, reset, bpp, qbpp, maxval, range;
39
    int near, twonear;
40
    int run_index[3];
41
}JLSState;
42

    
43
static const uint8_t log2_run[32]={
44
 0, 0, 0, 0, 1, 1, 1, 1,
45
 2, 2, 2, 2, 3, 3, 3, 3,
46
 4, 4, 5, 5, 6, 6, 7, 7,
47
 8, 9,10,11,12,13,14,15
48
};
49

    
50
/*
51
* Uncomment this to significantly speed up decoding of broken JPEG-LS
52
* (or test broken JPEG-LS decoder) and slow down ordinary decoding a bit.
53
*
54
* There is no Golomb code with length >= 32 bits possible, so check and
55
* avoid situation of 32 zeros, FFmpeg Golomb decoder is painfully slow
56
* on this errors.
57
*/
58
//#define JLS_BROKEN
59

    
60
/********** Functions for both encoder and decoder **********/
61

    
62
/**
63
 * Calculate initial JPEG-LS parameters
64
 */
65
static void ls_init_state(JLSState *state){
66
    int i;
67

    
68
    state->twonear = state->near * 2 + 1;
69
    state->range = ((state->maxval + state->twonear - 1) / state->twonear) + 1;
70

    
71
    // QBPP = ceil(log2(RANGE))
72
    for(state->qbpp = 0; (1 << state->qbpp) < state->range; state->qbpp++);
73

    
74
    if(state->bpp < 8)
75
        state->limit = 16 + 2 * state->bpp - state->qbpp;
76
    else
77
        state->limit = (4 * state->bpp) - state->qbpp;
78

    
79
    for(i = 0; i < 367; i++) {
80
        state->A[i] = FFMAX((state->range + 32) >> 6, 2);
81
        state->N[i] = 1;
82
    }
83

    
84
}
85

    
86
/**
87
 * Calculate quantized gradient value, used for context determination
88
 */
89
static inline int quantize(JLSState *s, int v){ //FIXME optimize
90
    if(v==0) return 0;
91
    if(v < 0){
92
        if(v <= -s->T3) return -4;
93
        if(v <= -s->T2) return -3;
94
        if(v <= -s->T1) return -2;
95
        if(v <  -s->near) return -1;
96
        return 0;
97
    }else{
98
        if(v <= s->near) return 0;
99
        if(v <  s->T1) return 1;
100
        if(v <  s->T2) return 2;
101
        if(v <  s->T3) return 3;
102
        return 4;
103
    }
104
}
105

    
106
/**
107
 * Custom value clipping function used in T1, T2, T3 calculation
108
 */
109
static inline int iso_clip(int v, int vmin, int vmax){
110
    if(v > vmax || v < vmin) return vmin;
111
    else                     return v;
112
}
113

    
114
/**
115
 * Calculate JPEG-LS codec values
116
 */
117
static void reset_ls_coding_parameters(JLSState *s, int reset_all){
118
    const int basic_t1= 3;
119
    const int basic_t2= 7;
120
    const int basic_t3= 21;
121
    int factor;
122

    
123
    if(s->maxval==0 || reset_all) s->maxval= (1 << s->bpp) - 1;
124

    
125
    if(s->maxval >=128){
126
        factor= (FFMIN(s->maxval, 4095) + 128)>>8;
127

    
128
        if(s->T1==0     || reset_all)
129
            s->T1= iso_clip(factor*(basic_t1-2) + 2 + 3*s->near, s->near+1, s->maxval);
130
        if(s->T2==0     || reset_all)
131
            s->T2= iso_clip(factor*(basic_t2-3) + 3 + 5*s->near, s->T1, s->maxval);
132
        if(s->T3==0     || reset_all)
133
            s->T3= iso_clip(factor*(basic_t3-4) + 4 + 7*s->near, s->T2, s->maxval);
134
    }else{
135
        factor= 256 / (s->maxval + 1);
136

    
137
        if(s->T1==0     || reset_all)
138
            s->T1= iso_clip(FFMAX(2, basic_t1/factor + 3*s->near), s->near+1, s->maxval);
139
        if(s->T2==0     || reset_all)
140
            s->T2= iso_clip(FFMAX(3, basic_t2/factor + 5*s->near), s->T1, s->maxval);
141
        if(s->T3==0     || reset_all)
142
            s->T3= iso_clip(FFMAX(4, basic_t3/factor + 6*s->near), s->T2, s->maxval);
143
    }
144

    
145
    if(s->reset==0  || reset_all) s->reset= 64;
146
//    av_log(NULL, AV_LOG_DEBUG, "[JPEG-LS RESET] T=%i,%i,%i\n", s->T1, s->T2, s->T3);
147
}
148

    
149

    
150
/********** Decoder-specific functions **********/
151

    
152
/**
153
 * Decode LSE block with initialization parameters
154
 */
155
static int decode_lse(MJpegDecodeContext *s)
156
{
157
    int len, id;
158

    
159
    /* XXX: verify len field validity */
160
    len = get_bits(&s->gb, 16);
161
    id = get_bits(&s->gb, 8);
162

    
163
    switch(id){
164
    case 1:
165
        s->maxval= get_bits(&s->gb, 16);
166
        s->t1= get_bits(&s->gb, 16);
167
        s->t2= get_bits(&s->gb, 16);
168
        s->t3= get_bits(&s->gb, 16);
169
        s->reset= get_bits(&s->gb, 16);
170

    
171
//        reset_ls_coding_parameters(s, 0);
172
        //FIXME quant table?
173
        break;
174
    case 2:
175
    case 3:
176
        av_log(s->avctx, AV_LOG_ERROR, "palette not supported\n");
177
        return -1;
178
    case 4:
179
        av_log(s->avctx, AV_LOG_ERROR, "oversize image not supported\n");
180
        return -1;
181
    default:
182
        av_log(s->avctx, AV_LOG_ERROR, "invalid id %d\n", id);
183
        return -1;
184
    }
185
//    av_log(s->avctx, AV_LOG_DEBUG, "ID=%i, T=%i,%i,%i\n", id, s->t1, s->t2, s->t3);
186

    
187
    return 0;
188
}
189

    
190
static void inline downscale_state(JLSState *state, int Q){
191
    if(state->N[Q] == state->reset){
192
        state->A[Q] >>=1;
193
        state->B[Q] >>=1;
194
        state->N[Q] >>=1;
195
    }
196
    state->N[Q]++;
197
}
198

    
199
static inline int update_state_regular(JLSState *state, int Q, int err){
200
    state->A[Q] += FFABS(err);
201
    err *= state->twonear;
202
    state->B[Q] += err;
203

    
204
    downscale_state(state, Q);
205

    
206
    if(state->B[Q] <= -state->N[Q]) {
207
        state->B[Q]= FFMAX(state->B[Q] + state->N[Q], 1-state->N[Q]);
208
        if(state->C[Q] > -128)
209
            state->C[Q]--;
210
    }else if(state->B[Q] > 0){
211
        state->B[Q]= FFMIN(state->B[Q] - state->N[Q], 0);
212
        if(state->C[Q] < 127)
213
            state->C[Q]++;
214
    }
215

    
216
    return err;
217
}
218

    
219
/**
220
 * Get context-dependent Golomb code, decode it and update context
221
 */
222
static inline int ls_get_code_regular(GetBitContext *gb, JLSState *state, int Q){
223
    int k, ret;
224

    
225
    for(k = 0; (state->N[Q] << k) < state->A[Q]; k++);
226

    
227
#ifdef JLS_BROKEN
228
    if(!show_bits_long(gb, 32))return -1;
229
#endif
230
    ret = get_ur_golomb_jpegls(gb, k, state->limit, state->qbpp);
231

    
232
    /* decode mapped error */
233
    if(ret & 1)
234
        ret = -((ret + 1) >> 1);
235
    else
236
        ret >>= 1;
237

    
238
    /* for NEAR=0, k=0 and 2*B[Q] <= - N[Q] mapping is reversed */
239
    if(!state->near && !k && (2 * state->B[Q] <= -state->N[Q]))
240
        ret = -(ret + 1);
241

    
242
    ret= update_state_regular(state, Q, ret);
243

    
244
    return ret;
245
}
246

    
247
/**
248
 * Get Golomb code, decode it and update state for run termination
249
 */
250
static inline int ls_get_code_runterm(GetBitContext *gb, JLSState *state, int RItype, int limit_add){
251
    int k, ret, temp, map;
252
    int Q = 365 + RItype;
253

    
254
    temp=  state->A[Q];
255
    if(RItype)
256
        temp += state->N[Q] >> 1;
257

    
258
    for(k = 0; (state->N[Q] << k) < temp; k++);
259

    
260
#ifdef JLS_BROKEN
261
    if(!show_bits_long(gb, 32))return -1;
262
#endif
263
    ret = get_ur_golomb_jpegls(gb, k, state->limit - limit_add - 1, state->qbpp);
264

    
265
    /* decode mapped error */
266
    map = 0;
267
    if(!k && (RItype || ret) && (2 * state->B[Q] < state->N[Q]))
268
        map = 1;
269
    ret += RItype + map;
270

    
271
    if(ret & 1){
272
        ret = map - ((ret + 1) >> 1);
273
        state->B[Q]++;
274
    } else {
275
        ret = ret >> 1;
276
    }
277

    
278
    /* update state */
279
    state->A[Q] += FFABS(ret) - RItype;
280
    ret *= state->twonear;
281
    downscale_state(state, Q);
282

    
283
    return ret;
284
}
285

    
286
#define R(a, i   ) (bits == 8 ?  ((uint8_t*)(a))[i]    :  ((uint16_t*)(a))[i]  )
287
#define W(a, i, v) (bits == 8 ? (((uint8_t*)(a))[i]=v) : (((uint16_t*)(a))[i]=v))
288
/**
289
 * Decode one line of image
290
 */
291
static inline void ls_decode_line(JLSState *state, MJpegDecodeContext *s, void *last, void *dst, int last2, int w, int stride, int comp, int bits){
292
    int i, x = 0;
293
    int Ra, Rb, Rc, Rd;
294
    int D0, D1, D2;
295

    
296
    while(x < w) {
297
        int err, pred;
298

    
299
        /* compute gradients */
300
        Ra = x ? R(dst, x - stride) : R(last, x);
301
        Rb = R(last, x);
302
        Rc = x ? R(last, x - stride) : last2;
303
        Rd = (x >= w - stride) ? R(last, x) : R(last, x + stride);
304
        D0 = Rd - Rb;
305
        D1 = Rb - Rc;
306
        D2 = Rc - Ra;
307
        /* run mode */
308
        if((FFABS(D0) <= state->near) && (FFABS(D1) <= state->near) && (FFABS(D2) <= state->near)) {
309
            int r;
310
            int RItype;
311

    
312
            /* decode full runs while available */
313
            while(get_bits1(&s->gb)) {
314
                int r;
315
                r = 1 << log2_run[state->run_index[comp]];
316
                if(x + r * stride > w) {
317
                    r = (w - x) / stride;
318
                }
319
                for(i = 0; i < r; i++) {
320
                    W(dst, x, Ra);
321
                    x += stride;
322
                }
323
                /* if EOL reached, we stop decoding */
324
                if(r != (1 << log2_run[state->run_index[comp]]))
325
                    return;
326
                if(state->run_index[comp] < 31)
327
                    state->run_index[comp]++;
328
                if(x + stride > w)
329
                    return;
330
            }
331
            /* decode aborted run */
332
            r = log2_run[state->run_index[comp]];
333
            if(r)
334
                r = get_bits_long(&s->gb, r);
335
            for(i = 0; i < r; i++) {
336
                W(dst, x, Ra);
337
                x += stride;
338
            }
339

    
340
            /* decode run termination value */
341
            Rb = R(last, x);
342
            RItype = (FFABS(Ra - Rb) <= state->near) ? 1 : 0;
343
            err = ls_get_code_runterm(&s->gb, state, RItype, log2_run[state->run_index[comp]]);
344
            if(state->run_index[comp])
345
                state->run_index[comp]--;
346

    
347
            if(state->near && RItype){
348
                pred = Ra + err;
349
            } else {
350
                if(Rb < Ra)
351
                    pred = Rb - err;
352
                else
353
                    pred = Rb + err;
354
            }
355
        } else { /* regular mode */
356
            int context, sign;
357

    
358
            context = quantize(state, D0) * 81 + quantize(state, D1) * 9 + quantize(state, D2);
359
            pred = mid_pred(Ra, Ra + Rb - Rc, Rb);
360

    
361
            if(context < 0){
362
                context = -context;
363
                sign = 1;
364
            }else{
365
                sign = 0;
366
            }
367

    
368
            if(sign){
369
                pred = clip(pred - state->C[context], 0, state->maxval);
370
                err = -ls_get_code_regular(&s->gb, state, context);
371
            } else {
372
                pred = clip(pred + state->C[context], 0, state->maxval);
373
                err = ls_get_code_regular(&s->gb, state, context);
374
            }
375

    
376
            /* we have to do something more for near-lossless coding */
377
            pred += err;
378
        }
379
        if(state->near){
380
            if(pred < -state->near)
381
                pred += state->range * state->twonear;
382
            else if(pred > state->maxval + state->near)
383
                pred -= state->range * state->twonear;
384
            pred = clip(pred, 0, state->maxval);
385
        }
386

    
387
        pred &= state->maxval;
388
        W(dst, x, pred);
389
        x += stride;
390
    }
391
}
392

    
393
static int ls_decode_picture(MJpegDecodeContext *s, int near, int point_transform, int ilv){
394
    int i, t = 0;
395
    uint8_t *zero, *last, *cur;
396
    JLSState *state;
397
    int off = 0, stride = 1, width, shift;
398

    
399
    zero = av_mallocz(s->picture.linesize[0]);
400
    last = zero;
401
    cur = s->picture.data[0];
402

    
403
    state = av_mallocz(sizeof(JLSState));
404
    /* initialize JPEG-LS state from JPEG parameters */
405
    state->near = near;
406
    state->bpp = (s->bits < 2) ? 2 : s->bits;
407
    state->maxval = s->maxval;
408
    state->T1 = s->t1;
409
    state->T2 = s->t2;
410
    state->T3 = s->t3;
411
    state->reset = s->reset;
412
    reset_ls_coding_parameters(state, 0);
413
    ls_init_state(state);
414

    
415
    if(s->bits <= 8)
416
        shift = point_transform + (8 - s->bits);
417
    else
418
        shift = point_transform + (16 - s->bits);
419

    
420
//    av_log(s->avctx, AV_LOG_DEBUG, "JPEG-LS params: %ix%i NEAR=%i MV=%i T(%i,%i,%i) RESET=%i, LIMIT=%i, qbpp=%i, RANGE=%i\n",s->width,s->height,state->near,state->maxval,state->T1,state->T2,state->T3,state->reset,state->limit,state->qbpp, state->range);
421
//    av_log(s->avctx, AV_LOG_DEBUG, "JPEG params: ILV=%i Pt=%i BPP=%i, scan = %i\n", ilv, point_transform, s->bits, s->cur_scan);
422
    if(ilv == 0) { /* separate planes */
423
        off = s->cur_scan - 1;
424
        stride = (s->nb_components > 1) ? 3 : 1;
425
        width = s->width * stride;
426
        cur += off;
427
        for(i = 0; i < s->height; i++) {
428
            if(s->bits <= 8){
429
                ls_decode_line(state, s, last, cur, t, width, stride, off,  8);
430
                t = last[0];
431
            }else{
432
                ls_decode_line(state, s, last, cur, t, width, stride, off, 16);
433
                t = *((uint16_t*)last);
434
            }
435
            last = cur;
436
            cur += s->picture.linesize[0];
437

    
438
            if (s->restart_interval && !--s->restart_count) {
439
                align_get_bits(&s->gb);
440
                skip_bits(&s->gb, 16); /* skip RSTn */
441
            }
442
        }
443
    } else if(ilv == 1) { /* line interleaving */
444
        int j;
445
        int Rc[3] = {0, 0, 0};
446
        memset(cur, 0, s->picture.linesize[0]);
447
        width = s->width * 3;
448
        for(i = 0; i < s->height; i++) {
449
            for(j = 0; j < 3; j++) {
450
                ls_decode_line(state, s, last + j, cur + j, Rc[j], width, 3, j, 8);
451
                Rc[j] = last[j];
452

    
453
                if (s->restart_interval && !--s->restart_count) {
454
                    align_get_bits(&s->gb);
455
                    skip_bits(&s->gb, 16); /* skip RSTn */
456
                }
457
            }
458
            last = cur;
459
            cur += s->picture.linesize[0];
460
        }
461
    } else if(ilv == 2) { /* sample interleaving */
462
        av_log(s->avctx, AV_LOG_ERROR, "Sample interleaved images are not supported.\n");
463
        av_free(state);
464
        av_free(zero);
465
        return -1;
466
    }
467

    
468
    if(shift){ /* we need to do point transform or normalize samples */
469
        int x, w;
470

    
471
        w = s->width * s->nb_components;
472

    
473
        if(s->bits <= 8){
474
            uint8_t *src = s->picture.data[0];
475

    
476
            for(i = 0; i < s->height; i++){
477
                for(x = off; x < w; x+= stride){
478
                    src[x] <<= shift;
479
                }
480
                src += s->picture.linesize[0];
481
            }
482
        }else{
483
            uint16_t *src = s->picture.data[0];
484

    
485
            for(i = 0; i < s->height; i++){
486
                for(x = 0; x < w; x++){
487
                    src[x] <<= shift;
488
                }
489
                src += s->picture.linesize[0]/2;
490
            }
491
        }
492
    }
493
    av_free(state);
494
    av_free(zero);
495

    
496
    return 0;
497
}
498

    
499
#if defined(CONFIG_ENCODERS) && defined(CONFIG_JPEGLS_ENCODER)
500
/********** Encoder-specific functions **********/
501

    
502
/**
503
 * Encode error from regular symbol
504
 */
505
static inline void ls_encode_regular(JLSState *state, PutBitContext *pb, int Q, int err){
506
    int k;
507
    int val;
508
    int map;
509

    
510
    for(k = 0; (state->N[Q] << k) < state->A[Q]; k++);
511

    
512
    map = !state->near && !k && (2 * state->B[Q] <= -state->N[Q]);
513

    
514
    if(err < 0)
515
        err += state->range;
516
    if(err >= ((state->range + 1) >> 1)) {
517
        err -= state->range;
518
        val = 2 * FFABS(err) - 1 - map;
519
    } else
520
        val = 2 * err + map;
521

    
522
    set_ur_golomb_jpegls(pb, val, k, state->limit, state->qbpp);
523

    
524
    update_state_regular(state, Q, err);
525
}
526

    
527
/**
528
 * Encode error from run termination
529
 */
530
static inline void ls_encode_runterm(JLSState *state, PutBitContext *pb, int RItype, int err, int limit_add){
531
    int k;
532
    int val, map;
533
    int Q = 365 + RItype;
534
    int temp;
535

    
536
    temp = state->A[Q];
537
    if(RItype)
538
        temp += state->N[Q] >> 1;
539
    for(k = 0; (state->N[Q] << k) < temp; k++);
540
    map = 0;
541
    if(!k && err && (2 * state->B[Q] < state->N[Q]))
542
        map = 1;
543

    
544
    if(err < 0)
545
        val = - (2 * err) - 1 - RItype + map;
546
    else
547
        val = 2 * err - RItype - map;
548
    set_ur_golomb_jpegls(pb, val, k, state->limit - limit_add - 1, state->qbpp);
549

    
550
    if(err < 0)
551
        state->B[Q]++;
552
    state->A[Q] += (val + 1 - RItype) >> 1;
553

    
554
    downscale_state(state, Q);
555
}
556

    
557
/**
558
 * Encode run value as specified by JPEG-LS standard
559
 */
560
static inline void ls_encode_run(JLSState *state, PutBitContext *pb, int run, int comp, int trail){
561
    while(run >= (1 << log2_run[state->run_index[comp]])){
562
        put_bits(pb, 1, 1);
563
        run -= 1 << log2_run[state->run_index[comp]];
564
        if(state->run_index[comp] < 31)
565
            state->run_index[comp]++;
566
    }
567
    /* if hit EOL, encode another full run, else encode aborted run */
568
    if(!trail && run) {
569
        put_bits(pb, 1, 1);
570
    }else if(trail){
571
        put_bits(pb, 1, 0);
572
        if(log2_run[state->run_index[comp]])
573
            put_bits(pb, log2_run[state->run_index[comp]], run);
574
    }
575
}
576

    
577
/**
578
 * Encode one line of image
579
 */
580
static inline void ls_encode_line(JLSState *state, PutBitContext *pb, void *last, void *cur, int last2, int w, int stride, int comp, int bits){
581
    int x = 0;
582
    int Ra, Rb, Rc, Rd;
583
    int D0, D1, D2;
584

    
585
    while(x < w) {
586
        int err, pred, sign;
587

    
588
        /* compute gradients */
589
        Ra = x ? R(cur, x - stride) : R(last, x);
590
        Rb = R(last, x);
591
        Rc = x ? R(last, x - stride) : last2;
592
        Rd = (x >= w - stride) ? R(last, x) : R(last, x + stride);
593
        D0 = Rd - Rb;
594
        D1 = Rb - Rc;
595
        D2 = Rc - Ra;
596

    
597
        /* run mode */
598
        if((FFABS(D0) <= state->near) && (FFABS(D1) <= state->near) && (FFABS(D2) <= state->near)) {
599
            int RUNval, RItype, run;
600

    
601
            run = 0;
602
            RUNval = Ra;
603
            while(x < w && (FFABS(R(cur, x) - RUNval) <= state->near)){
604
                run++;
605
                W(cur, x, Ra);
606
                x += stride;
607
            }
608
            ls_encode_run(state, pb, run, comp, x < w);
609
            if(x >= w)
610
                return;
611
            Rb = R(last, x);
612
            RItype = (FFABS(Ra - Rb) <= state->near);
613
            pred = RItype ? Ra : Rb;
614
            err = R(cur, x) - pred;
615

    
616
            if(!RItype && Ra > Rb)
617
                err = -err;
618

    
619
            if(state->near){
620
                if(err > 0)
621
                    err = (state->near + err) / state->twonear;
622
                else
623
                    err = -(state->near - err) / state->twonear;
624

    
625
                if(RItype || (Rb >= Ra))
626
                    Ra = clip(pred + err * state->twonear, 0, state->maxval);
627
                else
628
                    Ra = clip(pred - err * state->twonear, 0, state->maxval);
629
                W(cur, x, Ra);
630
            }
631
            if(err < 0)
632
                err += state->range;
633
            if(err >= ((state->range + 1) >> 1))
634
                err -= state->range;
635

    
636
            ls_encode_runterm(state, pb, RItype, err, log2_run[state->run_index[comp]]);
637

    
638
            if(state->run_index[comp] > 0)
639
                state->run_index[comp]--;
640
        } else { /* regular mode */
641
            int context;
642

    
643
            context = quantize(state, D0) * 81 + quantize(state, D1) * 9 + quantize(state, D2);
644
            pred = mid_pred(Ra, Ra + Rb - Rc, Rb);
645

    
646
            if(context < 0){
647
                context = -context;
648
                sign = 1;
649
                pred = clip(pred - state->C[context], 0, state->maxval);
650
                err = pred - R(cur, x);
651
            }else{
652
                sign = 0;
653
                pred = clip(pred + state->C[context], 0, state->maxval);
654
                err = R(cur, x) - pred;
655
            }
656

    
657
            if(state->near){
658
                if(err > 0)
659
                    err = (state->near + err) / state->twonear;
660
                else
661
                    err = -(state->near - err) / state->twonear;
662
                if(!sign)
663
                    Ra = clip(pred + err * state->twonear, 0, state->maxval);
664
                else
665
                    Ra = clip(pred - err * state->twonear, 0, state->maxval);
666
                W(cur, x, Ra);
667
            }
668

    
669
            ls_encode_regular(state, pb, context, err);
670
        }
671
        x += stride;
672
    }
673
}
674

    
675
static void ls_store_lse(JLSState *state, PutBitContext *pb){
676
    /* Test if we have default params and don't need to store LSE */
677
    JLSState state2;
678
    memset(&state2, 0, sizeof(JLSState));
679
    state2.bpp = state->bpp;
680
    state2.near = state->near;
681
    reset_ls_coding_parameters(&state2, 1);
682
    if(state->T1 == state2.T1 && state->T2 == state2.T2 && state->T3 == state2.T3 && state->reset == state2.reset)
683
        return;
684
    /* store LSE type 1 */
685
    put_marker(pb, LSE);
686
    put_bits(pb, 16, 13);
687
    put_bits(pb, 8,   1);
688
    put_bits(pb, 16, state->maxval);
689
    put_bits(pb, 16, state->T1);
690
    put_bits(pb, 16, state->T2);
691
    put_bits(pb, 16, state->T3);
692
    put_bits(pb, 16, state->reset);
693
}
694

    
695
static int encode_picture_ls(AVCodecContext *avctx, unsigned char *buf, int buf_size, void *data){
696
    JpeglsContext * const s = avctx->priv_data;
697
    AVFrame *pict = data;
698
    AVFrame * const p= (AVFrame*)&s->picture;
699
    const int near = avctx->prediction_method;
700
    PutBitContext pb, pb2;
701
    GetBitContext gb;
702
    uint8_t *buf2, *zero, *cur, *last;
703
    JLSState *state;
704
    int i, size;
705
    int comps;
706

    
707
    buf2 = av_malloc(buf_size);
708

    
709
    init_put_bits(&pb, buf, buf_size);
710
    init_put_bits(&pb2, buf2, buf_size);
711

    
712
    *p = *pict;
713
    p->pict_type= FF_I_TYPE;
714
    p->key_frame= 1;
715

    
716
    if(avctx->pix_fmt == PIX_FMT_GRAY8 || avctx->pix_fmt == PIX_FMT_GRAY16)
717
        comps = 1;
718
    else
719
        comps = 3;
720

    
721
    /* write our own JPEG header, can't use mjpeg_picture_header */
722
    put_marker(&pb, SOI);
723
    put_marker(&pb, SOF48);
724
    put_bits(&pb, 16, 8 + comps * 3); // header size depends on components
725
    put_bits(&pb,  8, (avctx->pix_fmt == PIX_FMT_GRAY16) ? 16 : 8); // bpp
726
    put_bits(&pb, 16, avctx->height);
727
    put_bits(&pb, 16, avctx->width);
728
    put_bits(&pb,  8, comps);         // components
729
    for(i = 1; i <= comps; i++) {
730
        put_bits(&pb,  8, i);    // component ID
731
        put_bits(&pb,  8, 0x11); // subsampling: none
732
        put_bits(&pb,  8, 0);    // Tiq, used by JPEG-LS ext
733
    }
734

    
735
    put_marker(&pb, SOS);
736
    put_bits(&pb, 16, 6 + comps * 2);
737
    put_bits(&pb,  8, comps);
738
    for(i = 1; i <= comps; i++) {
739
        put_bits(&pb,  8, i);  // component ID
740
        put_bits(&pb,  8, 0);  // mapping index: none
741
    }
742
    put_bits(&pb,  8, near);
743
    put_bits(&pb,  8, (comps > 1) ? 1 : 0); // interleaving: 0 - plane, 1 - line
744
    put_bits(&pb,  8, 0); // point transform: none
745

    
746
    state = av_mallocz(sizeof(JLSState));
747
    /* initialize JPEG-LS state from JPEG parameters */
748
    state->near = near;
749
    state->bpp = (avctx->pix_fmt == PIX_FMT_GRAY16) ? 16 : 8;
750
    reset_ls_coding_parameters(state, 0);
751
    ls_init_state(state);
752

    
753
    ls_store_lse(state, &pb);
754

    
755
    zero = av_mallocz(p->linesize[0]);
756
    last = zero;
757
    cur = p->data[0];
758
    if(avctx->pix_fmt == PIX_FMT_GRAY8){
759
        int t = 0;
760

    
761
        for(i = 0; i < avctx->height; i++) {
762
            ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0,  8);
763
            t = last[0];
764
            last = cur;
765
            cur += p->linesize[0];
766
        }
767
    }else if(avctx->pix_fmt == PIX_FMT_GRAY16){
768
        int t = 0;
769

    
770
        for(i = 0; i < avctx->height; i++) {
771
            ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0, 16);
772
            t = *((uint16_t*)last);
773
            last = cur;
774
            cur += p->linesize[0];
775
        }
776
    }else if(avctx->pix_fmt == PIX_FMT_RGB24){
777
        int j, width;
778
        int Rc[3] = {0, 0, 0};
779

    
780
        width = avctx->width * 3;
781
        for(i = 0; i < avctx->height; i++) {
782
            for(j = 0; j < 3; j++) {
783
                ls_encode_line(state, &pb2, last + j, cur + j, Rc[j], width, 3, j, 8);
784
                Rc[j] = last[j];
785
            }
786
            last = cur;
787
            cur += s->picture.linesize[0];
788
        }
789
    }else if(avctx->pix_fmt == PIX_FMT_BGR24){
790
        int j, width;
791
        int Rc[3] = {0, 0, 0};
792

    
793
        width = avctx->width * 3;
794
        for(i = 0; i < avctx->height; i++) {
795
            for(j = 2; j >= 0; j--) {
796
                ls_encode_line(state, &pb2, last + j, cur + j, Rc[j], width, 3, j, 8);
797
                Rc[j] = last[j];
798
            }
799
            last = cur;
800
            cur += s->picture.linesize[0];
801
        }
802
    }
803

    
804
    av_free(zero);
805
    av_free(state);
806

    
807
    flush_put_bits(&pb2);
808
    /* do escape coding */
809
    size = put_bits_count(&pb2) >> 3;
810
    init_get_bits(&gb, buf2, size);
811
    while(get_bits_count(&gb) < size * 8){
812
        int v;
813
        v = get_bits(&gb, 8);
814
        put_bits(&pb, 8, v);
815
        if(v == 0xFF){
816
            v = get_bits(&gb, 7);
817
            put_bits(&pb, 8, v);
818
        }
819
    }
820
    align_put_bits(&pb);
821
    av_free(buf2);
822

    
823
    /* End of image */
824
    put_marker(&pb, EOI);
825
    flush_put_bits(&pb);
826

    
827
    emms_c();
828

    
829
    return put_bits_count(&pb) >> 3;
830
}
831

    
832
static int encode_init_ls(AVCodecContext *ctx) {
833
    JpeglsContext *c = (JpeglsContext*)ctx->priv_data;
834

    
835
    c->avctx = ctx;
836
    ctx->coded_frame = &c->picture;
837

    
838
    if(ctx->pix_fmt != PIX_FMT_GRAY8 && ctx->pix_fmt != PIX_FMT_GRAY16 && ctx->pix_fmt != PIX_FMT_RGB24 && ctx->pix_fmt != PIX_FMT_BGR24){
839
        av_log(ctx, AV_LOG_ERROR, "Only grayscale and RGB24/BGR24 images are supported\n");
840
        return -1;
841
    }
842
    return 0;
843
}
844

    
845
AVCodec jpegls_encoder = { //FIXME avoid MPV_* lossless jpeg shouldnt need them
846
    "jpegls",
847
    CODEC_TYPE_VIDEO,
848
    CODEC_ID_JPEGLS,
849
    sizeof(JpeglsContext),
850
    encode_init_ls,
851
    encode_picture_ls,
852
    NULL,
853
    .pix_fmts= (enum PixelFormat[]){PIX_FMT_BGR24, PIX_FMT_RGB24, PIX_FMT_GRAY8, PIX_FMT_GRAY16, -1},
854
};
855
#endif