summaryrefslogtreecommitdiff
path: root/apps/codecs/libffmpegFLAC/shndec.c
blob: fb11f77bfa574e2c49e0816987a9872e6b5d12ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/*
 * Shorten decoder
 * Copyright (c) 2005 Jeff Muizelaar
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/**
 * @file shorten.c
 * Shorten decoder
 * @author Jeff Muizelaar
 *
 */
 
#include "bitstream.h"
#include "golomb.h"
#include "shndec.h"
#include "codeclib.h"

#define ULONGSIZE 2

#define WAVE_FORMAT_PCM 0x0001

#define TYPESIZE     4
#define CHANSIZE     0
#define LPCQSIZE     2
#define ENERGYSIZE   3
#define BITSHIFTSIZE 2

#define TYPE_S16HL 3  /* signed 16 bit shorts: high-low */
#define TYPE_S16LH 5  /* signed 16 bit shorts: low-high */

#define NWRAP 3
#define NSKIPSIZE 1

#define LPCQUANT 5
#define V2LPCQOFFSET (1 << LPCQUANT)

#define FNSIZE       2

#define VERBATIM_CKSIZE_SIZE  5
#define VERBATIM_BYTE_SIZE    8
#define CANONICAL_HEADER_SIZE 44

#define FFMAX(a,b) ((a) > (b) ? (a) : (b))
#define FFMIN(a,b) ((a) > (b) ? (b) : (a))
#define MKTAG(a,b,c,d) (a | (b << 8) | (c << 16) | (d << 24))

#define get_le16(gb) bswap_16(get_bits_long(gb, 16))
#define get_le32(gb) bswap_32(get_bits_long(gb, 32))

static uint32_t bswap_32(uint32_t x){
    x= ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
    return (x>>16) | (x<<16);
}

static uint16_t bswap_16(uint16_t x){
    return (x>>8) | (x<<8);
}

/* converts fourcc string to int */
static int ff_get_fourcc(const char *s){
    //assert( strlen(s)==4 );
    return (s[0]) + (s[1]<<8) + (s[2]<<16) + (s[3]<<24);
}

static unsigned int get_uint(ShortenContext *s, int k)
{
    if (s->version != 0)
        k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
    return get_ur_golomb_shorten(&s->gb, k);
}

#if defined(CPU_COLDFIRE)
static void coldfire_lshift_samples(int n, int shift, int32_t *samples) ICODE_ATTR_FLAC;
static void coldfire_lshift_samples(int n, int shift, int32_t *samples)
{
/*
    for (i = 0; i < n; i++)
        samples[i] =<< shift;
*/
    asm volatile (
            "move.l %[n], %%d0              \n" /* d0 = loop counter */
            "asr.l  #2, %%d0                \n"
            "beq l1_shift                   \n"
        "l2_shift:" /* main loop (unroll by 4) */
            "movem.l (%[x]), %%d4-%%d7      \n"
            "asl.l   %[s], %%d4             \n"
            "asl.l   %[s], %%d5             \n"
            "asl.l   %[s], %%d6             \n"
            "asl.l   %[s], %%d7             \n"
            "movem.l %%d4-%%d7, (%[x])      \n"
            "add.l  #16, %[x]               \n"

            "subq.l  #1, %%d0               \n"
            "bne l2_shift                   \n"
        "l1_shift:" /* any loops left? */
            "and.l  #3, %[n]                \n"
            "beq l4_shift                   \n"
        "l3_shift:" /* remaining loops */
            "move.l (%[x]), %%d4            \n"
            "asl.l  %[s], %%d4              \n"
            "move.l %%d4, (%[x])+           \n"

            "subq.l #1, %[n]                \n"
            "bne l3_shift                   \n"
        "l4_shift:" /* exit */
        : [n] "+d" (n),         /* d1 */
          [s] "+d" (shift),     /* d2 */
          [x] "+a" (samples)    /* a0 */
        :
        : "%d0", "%d4", "%d5", "%d6", "%d7"
    );
}
#endif

static inline void fix_bitshift(ShortenContext *s, int32_t *samples)
{
    int i;

    /* Wrapped samples don't get bitshifted, so we'll do them during
       the next iteration. */
    if (s->bitshift != 0) {
#if defined(CPU_COLDFIRE)
        coldfire_lshift_samples(s->blocksize, s->bitshift, samples - s->nwrap);
#else
        for (i = -s->nwrap; i < (s->blocksize - s->nwrap); i++)
            samples[i] <<= s->bitshift;
#endif
    }

    /* Also, when we have to remember to fix the wrapped samples when
       the bitshift changes.*/
    if (s->bitshift != s->last_bitshift) {
        if (s->last_bitshift != 0)
            for (i = -s->nwrap; i < 0; i++)
                samples[i] <<= s->last_bitshift;

        s->last_bitshift = s->bitshift;
    }
}

static inline void decode_subframe_lpc(ShortenContext *s, int32_t *decoded,
                                       int residual_size, int pred_order)
{
    int sum, i, j;
    int coeffs[MAX_PRED_ORDER];

    for (i=0; i<pred_order; i++) {
        coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
    }

    for (i=0; i < s->blocksize; i++) {
        sum = s->lpcqoffset;
        for (j=0; j<pred_order; j++)
            sum += coeffs[j] * decoded[i-j-1];

        decoded[i] =
            get_sr_golomb_shorten(&s->gb, residual_size) + (sum >> LPCQUANT);
    }
}

static inline int shorten_decode_frame(ShortenContext *s, int32_t *decoded,
                                       int32_t *offset)
{
    int i;
    int32_t sum;

    int cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
    switch (cmd) {
        case FN_ZERO:
        case FN_DIFF0:
        case FN_DIFF1:
        case FN_DIFF2:
        case FN_DIFF3:
        case FN_QLPC:
        {
            int residual_size = 0;
            int32_t coffset;
            if (cmd != FN_ZERO) {
                residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
                /* this is a hack as version 0 differed in defintion of
                   get_sr_golomb_shorten */
                if (s->version == 0)
                    residual_size--;
              }

            if (s->nmean == 0) {
                coffset = offset[0];
            } else {
                sum = (s->version < 2) ? 0 : s->nmean / 2;
                for (i=0; i<s->nmean; i++)
                    sum += offset[i];

                coffset = sum / s->nmean;
                if (s->version >= 2)
                    coffset >>= FFMIN(1, s->bitshift);
            }

            switch (cmd) {
                case FN_ZERO:
                    for (i=0; i<s->blocksize; i++)
                        decoded[i] = 0;
                    break;

                case FN_DIFF0:
                    for (i=0; i<s->blocksize; i++)
                        decoded[i] =
                            get_sr_golomb_shorten(&s->gb, residual_size) +
                            coffset;
                    break;

                case FN_DIFF1:
                    for (i=0; i<s->blocksize; i++)
                        decoded[i] =
                            get_sr_golomb_shorten(&s->gb, residual_size) +
                            decoded[i - 1];
                    break;

                case FN_DIFF2:
                    for (i=0; i<s->blocksize; i++)
                        decoded[i] =
                            get_sr_golomb_shorten(&s->gb, residual_size) +
                            2*decoded[i-1] - decoded[i-2];
                    break;

                case FN_DIFF3:
                    for (i=0; i<s->blocksize; i++)
                        decoded[i] =
                            get_sr_golomb_shorten(&s->gb, residual_size) +
                            3*decoded[i-1] - 3*decoded[i-2] + decoded[i-3];
                    break;

                case FN_QLPC:
                {
                    int pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
                    for (i=0; i<pred_order; i++)
                        decoded[i - pred_order] -= coffset;
                    decode_subframe_lpc(s, decoded, residual_size, pred_order);
                    if (coffset != 0) {
                        for (i=0; i < s->blocksize; i++)
                            decoded[i] += coffset;
                    }
                }
            }

            if (s->nmean > 0) {
                sum = (s->version < 2) ? 0 : s->blocksize / 2;
                for (i=0; i<s->blocksize; i++)
                    sum += decoded[i];

                for (i=1; i<s->nmean; i++)
                    offset[i-1] = offset[i];

                if (s->version < 2) {
                    offset[s->nmean - 1] = sum / s->blocksize;
                } else {
                    offset[s->nmean - 1] =
                        (sum / s->blocksize) << s->bitshift;
                }
            }

            fix_bitshift(s, decoded);
            break;
        }

        case FN_VERBATIM:
            i = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
            while (i--)
                get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
            break;

        case FN_BITSHIFT:
            s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
            break;

        case FN_BLOCKSIZE:
            s->blocksize = get_uint(s, av_log2(s->blocksize));
            break;

        case FN_QUIT:
            break;

        default:
            return FN_ERROR;
            break;
    }

    return cmd;
}

int shorten_decode_frames(ShortenContext *s, int *nsamples,
                          int32_t *decoded0, int32_t *decoded1,
                          int32_t *offset0, int32_t *offset1,
                          uint8_t *buf, int buf_size,
                          void (*yield)(void))
{
    int32_t *decoded, *offset;
    int cmd;

    *nsamples = 0;

    init_get_bits(&s->gb, buf, buf_size*8);
    get_bits(&s->gb, s->bitindex);

    int n = 0;
    while (n < NUM_DEC_LOOPS) {
        int chan = n%2;
        if (chan == 0) {
            decoded = decoded0 + s->nwrap + *nsamples;
            offset = offset0;
        } else {
            decoded = decoded1 + s->nwrap + *nsamples;
            offset = offset1;
        }

        yield();

        cmd = shorten_decode_frame(s, decoded, offset);

        if (cmd == FN_VERBATIM || cmd == FN_BITSHIFT || cmd == FN_BLOCKSIZE) {
            continue;
        } else if (cmd == FN_QUIT || cmd == FN_ERROR) {
            break;
        }

        *nsamples += chan * s->blocksize;
        n++;
    }

    if (*nsamples) {
        /* Wrap the samples for the next loop */
        int i;
        for (i = 0; i < s->nwrap; i++) {
            decoded0[i] = decoded0[*nsamples + i];
            decoded1[i] = decoded1[*nsamples + i];
        }

        /* Scale the samples for the pcmbuf */
        int scale = SHN_OUTPUT_DEPTH - s->bits_per_sample;
#if defined(CPU_COLDFIRE)
        coldfire_lshift_samples(*nsamples, scale, decoded0 + s->nwrap);
        coldfire_lshift_samples(*nsamples, scale, decoded1 + s->nwrap);
#else
        for (i = 0; i < *nsamples; i++) {
            decoded0[i + s->nwrap] <<= scale;
            decoded1[i + s->nwrap] <<= scale;
        }
#endif
    }

    return cmd;
}

static int decode_wave_header(ShortenContext *s,
                              uint8_t *header,
                              int header_size)
{
    GetBitContext hb;
    int len;

    init_get_bits(&hb, header, header_size*8);
    if (get_le32(&hb) != MKTAG('R','I','F','F')) {
        return -8;
    }

    int chunk_size = get_le32(&hb);

    if (get_le32(&hb) != MKTAG('W','A','V','E')) {
        return -9;
    }

    while (get_le32(&hb) != MKTAG('f','m','t',' ')) {
        len = get_le32(&hb);
        skip_bits(&hb, 8*len);
    }

    len = get_le32(&hb);
    if (len < 16) {
        return -10;
    }

    if (get_le16(&hb) != WAVE_FORMAT_PCM ) {
        return -11;
    }

    s->channels = get_le16(&hb);
    if (s->channels > MAX_CHANNELS) {
        return -3;
    }

    s->sample_rate = get_le32(&hb);

    skip_bits(&hb, 32);
    //s->bit_rate = 8*get_le32(&hb);

    int block_align = get_le16(&hb);
    s->totalsamples = (chunk_size - 36) / block_align;

    s->bits_per_sample = get_le16(&hb);
    if (s->bits_per_sample != 16) {
        return -12;
    }

    len -= 16;
    if (len > 0) {
        return len;
    }

    return 0;
}

int shorten_init(ShortenContext* s, uint8_t *buf, int buf_size)
{
    int i;

    s->blocksize = DEFAULT_BLOCK_SIZE;
    s->channels = 1;
    s->nmean = -1;

    init_get_bits(&s->gb, buf, buf_size*8);
    get_bits(&s->gb, s->bitindex);

    /* shorten signature */
    if (get_bits_long(&s->gb, 32) != bswap_32(ff_get_fourcc("ajkg"))) {
        return -1;
    }

    s->version = get_bits(&s->gb, 8);

    int internal_ftype = get_uint(s, TYPESIZE);
    if ((internal_ftype != TYPE_S16HL) && (internal_ftype != TYPE_S16LH)) {
        return -2;
    }

    s->channels = get_uint(s, CHANSIZE);
    if (s->channels > MAX_CHANNELS) {
        return -3;
    }

    /* get blocksize if version > 0 */
    int maxnlpc = 0;
    if (s->version > 0) {
        s->blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
        maxnlpc = get_uint(s, LPCQSIZE);
        s->nmean = get_uint(s, 0);

        int skip_bytes = get_uint(s, NSKIPSIZE);
        for (i=0; i<skip_bytes; i++) {
            skip_bits(&s->gb, 8);
        }
    }

    if (s->nmean > MAX_NMEAN) {
        return -4;
    }

    s->nwrap = FFMAX(NWRAP, maxnlpc);
    if (s->nwrap > MAX_NWRAP) {
        return -5;
    }

    if (s->version > 1)
        s->lpcqoffset = V2LPCQOFFSET;

    if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
        return -6;
    }

    uint8_t header[MAX_HEADER_SIZE];
    int header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
    if (header_size >= MAX_HEADER_SIZE || header_size < CANONICAL_HEADER_SIZE) {
        return -7;
    }

    for (i=0; i<header_size; i++)
        header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);

    s->header_bits = s->gb.index;

    return decode_wave_header(s, header, header_size);
}
opt">*x, t_pd *who, t_symbol *s) { t_inlet *ip = inlet_new(&x->gl_obj, who, s, 0); if (!x->gl_loading && x->gl_owner && glist_isvisible(x->gl_owner)) { gobj_vis(&x->gl_gobj, x->gl_owner, 0); gobj_vis(&x->gl_gobj, x->gl_owner, 1); canvas_fixlinesfor(x->gl_owner, &x->gl_obj); } if (!x->gl_loading) canvas_resortinlets(x); return (ip); } void canvas_rminlet(t_canvas *x, t_inlet *ip) { t_canvas *owner = x->gl_owner; int redraw = (owner && glist_isvisible(owner) && (!owner->gl_isdeleting) && glist_istoplevel(owner)); if (owner) canvas_deletelinesforio(owner, &x->gl_obj, ip, 0); if (redraw) gobj_vis(&x->gl_gobj, x->gl_owner, 0); inlet_free(ip); if (redraw) { gobj_vis(&x->gl_gobj, x->gl_owner, 1); canvas_fixlinesfor(x->gl_owner, &x->gl_obj); } } extern t_inlet *vinlet_getit(t_pd *x); extern void obj_moveinletfirst(t_object *x, t_inlet *i); void canvas_resortinlets(t_canvas *x) { int ninlets = 0, i, j, xmax; t_gobj *y, **vec, **vp, **maxp; for (ninlets = 0, y = x->gl_list; y; y = y->g_next) if (pd_class(&y->g_pd) == vinlet_class) ninlets++; if (ninlets < 2) return; vec = (t_gobj **)getbytes(ninlets * sizeof(*vec)); for (y = x->gl_list, vp = vec; y; y = y->g_next) if (pd_class(&y->g_pd) == vinlet_class) *vp++ = y; for (i = ninlets; i--;) { t_inlet *ip; for (vp = vec, xmax = -0x7fffffff, maxp = 0, j = ninlets; j--; vp++) { int x1, y1, x2, y2; t_gobj *g = *vp; if (!g) continue; gobj_getrect(g, x, &x1, &y1, &x2, &y2); if (x1 > xmax) xmax = x1, maxp = vp; } if (!maxp) break; y = *maxp; *maxp = 0; ip = vinlet_getit(&y->g_pd); obj_moveinletfirst(&x->gl_obj, ip); } freebytes(vec, ninlets * sizeof(*vec)); if (x->gl_owner && glist_isvisible(x->gl_owner)) canvas_fixlinesfor(x->gl_owner, &x->gl_obj); } t_outlet *canvas_addoutlet(t_canvas *x, t_pd *who, t_symbol *s) { t_outlet *op = outlet_new(&x->gl_obj, s); #ifdef ROCKBOX (void) who; #endif if (!x->gl_loading && x->gl_owner && glist_isvisible(x->gl_owner)) { gobj_vis(&x->gl_gobj, x->gl_owner, 0); gobj_vis(&x->gl_gobj, x->gl_owner, 1); canvas_fixlinesfor(x->gl_owner, &x->gl_obj); } if (!x->gl_loading) canvas_resortoutlets(x); return (op); } void canvas_rmoutlet(t_canvas *x, t_outlet *op) { t_canvas *owner = x->gl_owner; int redraw = (owner && glist_isvisible(owner) && (!owner->gl_isdeleting) && glist_istoplevel(owner)); if (owner) canvas_deletelinesforio(owner, &x->gl_obj, 0, op); if (redraw) gobj_vis(&x->gl_gobj, x->gl_owner, 0); outlet_free(op); if (redraw) { gobj_vis(&x->gl_gobj, x->gl_owner, 1); canvas_fixlinesfor(x->gl_owner, &x->gl_obj); } } extern t_outlet *voutlet_getit(t_pd *x); extern void obj_moveoutletfirst(t_object *x, t_outlet *i); void canvas_resortoutlets(t_canvas *x) { int noutlets = 0, i, j, xmax; t_gobj *y, **vec, **vp, **maxp; for (noutlets = 0, y = x->gl_list; y; y = y->g_next) if (pd_class(&y->g_pd) == voutlet_class) noutlets++; if (noutlets < 2) return; vec = (t_gobj **)getbytes(noutlets * sizeof(*vec)); for (y = x->gl_list, vp = vec; y; y = y->g_next) if (pd_class(&y->g_pd) == voutlet_class) *vp++ = y; for (i = noutlets; i--;) { t_outlet *ip; for (vp = vec, xmax = -0x7fffffff, maxp = 0, j = noutlets; j--; vp++) { int x1, y1, x2, y2; t_gobj *g = *vp; if (!g) continue; gobj_getrect(g, x, &x1, &y1, &x2, &y2); if (x1 > xmax) xmax = x1, maxp = vp; } if (!maxp) break; y = *maxp; *maxp = 0; ip = voutlet_getit(&y->g_pd); obj_moveoutletfirst(&x->gl_obj, ip); } freebytes(vec, noutlets * sizeof(*vec)); if (x->gl_owner && glist_isvisible(x->gl_owner)) canvas_fixlinesfor(x->gl_owner, &x->gl_obj); } /* ----------calculating coordinates and controlling appearance --------- */ static void graph_bounds(t_glist *x, t_floatarg x1, t_floatarg y1, t_floatarg x2, t_floatarg y2) { x->gl_x1 = x1; x->gl_x2 = x2; x->gl_y1 = y1; x->gl_y2 = y2; if (x->gl_x2 == x->gl_x1 || x->gl_y2 == x->gl_y1) { error("graph: empty bounds rectangle"); x1 = y1 = 0; x2 = y2 = 1; } glist_redraw(x); } static void graph_xticks(t_glist *x, t_floatarg point, t_floatarg inc, t_floatarg f) { x->gl_xtick.k_point = point; x->gl_xtick.k_inc = inc; x->gl_xtick.k_lperb = f; glist_redraw(x); } static void graph_yticks(t_glist *x, t_floatarg point, t_floatarg inc, t_floatarg f) { x->gl_ytick.k_point = point; x->gl_ytick.k_inc = inc; x->gl_ytick.k_lperb = f; glist_redraw(x); } static void graph_xlabel(t_glist *x, t_symbol *s, int argc, t_atom *argv) { int i; #ifdef ROCKBOX (void) s; #endif if (argc < 1) error("graph_xlabel: no y value given"); else { x->gl_xlabely = atom_getfloat(argv); argv++; argc--; x->gl_xlabel = (t_symbol **)t_resizebytes(x->gl_xlabel, x->gl_nxlabels * sizeof (t_symbol *), argc * sizeof (t_symbol *)); x->gl_nxlabels = argc; for (i = 0; i < argc; i++) x->gl_xlabel[i] = atom_gensym(&argv[i]); } glist_redraw(x); } static void graph_ylabel(t_glist *x, t_symbol *s, int argc, t_atom *argv) { int i; #ifdef ROCKBOX (void) s; #endif if (argc < 1) error("graph_ylabel: no x value given"); else { x->gl_ylabelx = atom_getfloat(argv); argv++; argc--; x->gl_ylabel = (t_symbol **)t_resizebytes(x->gl_ylabel, x->gl_nylabels * sizeof (t_symbol *), argc * sizeof (t_symbol *)); x->gl_nylabels = argc; for (i = 0; i < argc; i++) x->gl_ylabel[i] = atom_gensym(&argv[i]); } glist_redraw(x); } /****** routines to convert pixels to X or Y value and vice versa ******/ /* convert an x pixel value to an x coordinate value */ float glist_pixelstox(t_glist *x, float xpix) { /* if we appear as a text box on parent, our range in our coordinates (x1, etc.) specifies the coordinate range of a one-pixel square at top left of the window. */ if (!x->gl_isgraph) return (x->gl_x1 + (x->gl_x2 - x->gl_x1) * xpix); /* if we're a graph when shown on parent, but own our own window right now, our range in our coordinates (x1, etc.) is spread over the visible window size, given by screenx1, etc. */ else if (x->gl_isgraph && x->gl_havewindow) return (x->gl_x1 + (x->gl_x2 - x->gl_x1) * (xpix) / (x->gl_screenx2 - x->gl_screenx1)); /* otherwise, we appear in a graph within a parent glist, so get our screen rectangle on parent and transform. */ else { int x1, y1, x2, y2; if (!x->gl_owner) bug("glist_pixelstox"); graph_graphrect(&x->gl_gobj, x->gl_owner, &x1, &y1, &x2, &y2); return (x->gl_x1 + (x->gl_x2 - x->gl_x1) * (xpix - x1) / (x2 - x1)); } } float glist_pixelstoy(t_glist *x, float ypix) { if (!x->gl_isgraph) return (x->gl_y1 + (x->gl_y2 - x->gl_y1) * ypix); else if (x->gl_isgraph && x->gl_havewindow) return (x->gl_y1 + (x->gl_y2 - x->gl_y1) * (ypix) / (x->gl_screeny2 - x->gl_screeny1)); else { int x1, y1, x2, y2; if (!x->gl_owner) bug("glist_pixelstox"); graph_graphrect(&x->gl_gobj, x->gl_owner, &x1, &y1, &x2, &y2); return (x->gl_y1 + (x->gl_y2 - x->gl_y1) * (ypix - y1) / (y2 - y1)); } } /* convert an x coordinate value to an x pixel location in window */ float glist_xtopixels(t_glist *x, float xval) { if (!x->gl_isgraph) return ((xval - x->gl_x1) / (x->gl_x2 - x->gl_x1)); else if (x->gl_isgraph && x->gl_havewindow) return (x->gl_screenx2 - x->gl_screenx1) * (xval - x->gl_x1) / (x->gl_x2 - x->gl_x1); else { int x1, y1, x2, y2; if (!x->gl_owner) bug("glist_pixelstox"); graph_graphrect(&x->gl_gobj, x->gl_owner, &x1, &y1, &x2, &y2); return (x1 + (x2 - x1) * (xval - x->gl_x1) / (x->gl_x2 - x->gl_x1)); } } float glist_ytopixels(t_glist *x, float yval) { if (!x->gl_isgraph) return ((yval - x->gl_y1) / (x->gl_y2 - x->gl_y1)); else if (x->gl_isgraph && x->gl_havewindow) return (x->gl_screeny2 - x->gl_screeny1) * (yval - x->gl_y1) / (x->gl_y2 - x->gl_y1); else { int x1, y1, x2, y2; if (!x->gl_owner) bug("glist_pixelstox"); graph_graphrect(&x->gl_gobj, x->gl_owner, &x1, &y1, &x2, &y2); return (y1 + (y2 - y1) * (yval - x->gl_y1) / (x->gl_y2 - x->gl_y1)); } } /* convert an X screen distance to an X coordinate increment. This is terribly inefficient; but probably not a big enough CPU hog to warrant optimizing. */ float glist_dpixtodx(t_glist *x, float dxpix) { return (dxpix * (glist_pixelstox(x, 1) - glist_pixelstox(x, 0))); } float glist_dpixtody(t_glist *x, float dypix) { return (dypix * (glist_pixelstoy(x, 1) - glist_pixelstoy(x, 0))); } /* get the window location in pixels of a "text" object. The object's x and y positions are in pixels when the glist they're in is toplevel. If it's not, we convert to pixels on the parent window. */ int text_xpix(t_text *x, t_glist *glist) { if (glist->gl_havewindow || !glist->gl_isgraph) return (x->te_xpix); else return (glist_xtopixels(glist, glist->gl_x1 + (glist->gl_x2 - glist->gl_x1) * x->te_xpix / (glist->gl_screenx2 - glist->gl_screenx1))); } int text_ypix(t_text *x, t_glist *glist) { if (glist->gl_havewindow || !glist->gl_isgraph) return (x->te_ypix); else return (glist_ytopixels(glist, glist->gl_y1 + (glist->gl_y2 - glist->gl_y1) * x->te_ypix / (glist->gl_screeny2 - glist->gl_screeny1))); } /* redraw all the items in a glist. We construe this to mean redrawing in its own window and on parent, as needed in each case. This is too conservative -- for instance, when you draw an "open" rectangle on the parent, you shouldn't have to redraw the window! */ void glist_redraw(t_glist *x) { if (glist_isvisible(x)) { /* LATER fix the graph_vis() code to handle both cases */ if (glist_istoplevel(x)) { t_gobj *g; t_linetraverser t; t_outconnect *oc; for (g = x->gl_list; g; g = g->g_next) { gobj_vis(g, x, 0); gobj_vis(g, x, 1); } /* redraw all the lines */ linetraverser_start(&t, x); while((oc = linetraverser_next(&t))) #ifdef ROCKBOX ; #else /* ROCKBOX */ sys_vgui(".x%x.c coords l%x %d %d %d %d\n", glist_getcanvas(x), oc, t.tr_lx1, t.tr_ly1, t.tr_lx2, t.tr_ly2); #endif /* ROCKBOX */ } if (x->gl_owner) { graph_vis(&x->gl_gobj, x->gl_owner, 0); graph_vis(&x->gl_gobj, x->gl_owner, 1); } } } /* --------------------------- widget behavior ------------------- */ extern t_widgetbehavior text_widgetbehavior; /* Note that some code in here would also be useful for drawing graph decorations in toplevels... */ static void graph_vis(t_gobj *gr, t_glist *parent_glist, int vis) { t_glist *x = (t_glist *)gr; char tag[50]; t_gobj *g; int x1, y1, x2, y2; /* ordinary subpatches: just act like a text object */ if (!x->gl_isgraph) { text_widgetbehavior.w_visfn(gr, parent_glist, vis); return; } if (vis && canvas_showtext(x)) rtext_draw(glist_findrtext(parent_glist, &x->gl_obj)); graph_getrect(gr, parent_glist, &x1, &y1, &x2, &y2); if (!vis) rtext_erase(glist_findrtext(parent_glist, &x->gl_obj)); #ifdef ROCKBOX snprintf(tag, sizeof(tag), "graph%lx", (unsigned long) (intptr_t) x); #else sprintf(tag, "graph%x", (int)x); #endif if (vis) glist_drawiofor(parent_glist, &x->gl_obj, 1, tag, x1, y1, x2, y2); else glist_eraseiofor(parent_glist, &x->gl_obj, tag); /* if we look like a graph but have been moved to a toplevel, just show the bounding rectangle */ if (x->gl_havewindow) { #ifndef ROCKBOX if (vis) { sys_vgui(".x%x.c create polygon\ %d %d %d %d %d %d %d %d %d %d -tags %s -fill #c0c0c0\n", glist_getcanvas(x->gl_owner), x1, y1, x1, y2, x2, y2, x2, y1, x1, y1, tag); } else { sys_vgui(".x%x.c delete %s\n", glist_getcanvas(x->gl_owner), tag); } #endif return; } /* otherwise draw (or erase) us as a graph inside another glist. */ if (vis) { int i; float f; /* draw a rectangle around the graph */ #ifndef ROCKBOX sys_vgui(".x%x.c create line\ %d %d %d %d %d %d %d %d %d %d -tags %s\n", glist_getcanvas(x->gl_owner), x1, y1, x1, y2, x2, y2, x2, y1, x1, y1, tag); #endif /* draw ticks on horizontal borders. If lperb field is zero, this is disabled. */ if (x->gl_xtick.k_lperb) { float upix, lpix; if (y2 < y1) upix = y1, lpix = y2; else upix = y2, lpix = y1; for (i = 0, f = x->gl_xtick.k_point; f < 0.99 * x->gl_x2 + 0.01*x->gl_x1; i++, f += x->gl_xtick.k_inc) { #ifndef ROCKBOX int tickpix = (i % x->gl_xtick.k_lperb ? 2 : 4); sys_vgui(".x%x.c create line %d %d %d %d -tags %s\n", glist_getcanvas(x->gl_owner), (int)glist_xtopixels(x, f), (int)upix, (int)glist_xtopixels(x, f), (int)upix - tickpix, tag); sys_vgui(".x%x.c create line %d %d %d %d -tags %s\n", glist_getcanvas(x->gl_owner), (int)glist_xtopixels(x, f), (int)lpix, (int)glist_xtopixels(x, f), (int)lpix + tickpix, tag); #endif } for (i = 1, f = x->gl_xtick.k_point - x->gl_xtick.k_inc; f > 0.99 * x->gl_x1 + 0.01*x->gl_x2; i++, f -= x->gl_xtick.k_inc) { #ifndef ROCKBOX int tickpix = (i % x->gl_xtick.k_lperb ? 2 : 4); sys_vgui(".x%x.c create line %d %d %d %d -tags %s\n", glist_getcanvas(x->gl_owner), (int)glist_xtopixels(x, f), (int)upix, (int)glist_xtopixels(x, f), (int)upix - tickpix, tag); sys_vgui(".x%x.c create line %d %d %d %d -tags %s\n", glist_getcanvas(x->gl_owner), (int)glist_xtopixels(x, f), (int)lpix, (int)glist_xtopixels(x, f), (int)lpix + tickpix, tag); #endif } } /* draw ticks in vertical borders*/ if (x->gl_ytick.k_lperb) { float ubound, lbound; if (x->gl_y2 < x->gl_y1) ubound = x->gl_y1, lbound = x->gl_y2; else ubound = x->gl_y2, lbound = x->gl_y1; for (i = 0, f = x->gl_ytick.k_point; f < 0.99 * ubound + 0.01 * lbound; i++, f += x->gl_ytick.k_inc) { #ifndef ROCKBOX int tickpix = (i % x->gl_ytick.k_lperb ? 2 : 4); sys_vgui(".x%x.c create line %d %d %d %d -tags %s\n", glist_getcanvas(x->gl_owner), x1, (int)glist_ytopixels(x, f), x1 + tickpix, (int)glist_ytopixels(x, f), tag); sys_vgui(".x%x.c create line %d %d %d %d -tags %s\n", glist_getcanvas(x->gl_owner), x2, (int)glist_ytopixels(x, f), x2 - tickpix, (int)glist_ytopixels(x, f), tag); #endif } for (i = 1, f = x->gl_ytick.k_point - x->gl_ytick.k_inc; f > 0.99 * lbound + 0.01 * ubound; i++, f -= x->gl_ytick.k_inc) { #ifndef ROCKBOX int tickpix = (i % x->gl_ytick.k_lperb ? 2 : 4); sys_vgui(".x%x.c create line %d %d %d %d -tags %s\n", glist_getcanvas(x->gl_owner), x1, (int)glist_ytopixels(x, f), x1 + tickpix, (int)glist_ytopixels(x, f), tag); sys_vgui(".x%x.c create line %d %d %d %d -tags %s\n", glist_getcanvas(x->gl_owner), x2, (int)glist_ytopixels(x, f), x2 - tickpix, (int)glist_ytopixels(x, f), tag); #endif } } /* draw x labels */ for (i = 0; i < x->gl_nxlabels; i++) #ifdef ROCKBOX ; #else /* ROCKBOX */ sys_vgui(".x%x.c create text\ %d %d -text {%s} -font -*-courier-bold--normal--%d-* -tags %s\n", glist_getcanvas(x), (int)glist_xtopixels(x, atof(x->gl_xlabel[i]->s_name)), (int)glist_ytopixels(x, x->gl_xlabely), x->gl_xlabel[i]->s_name, glist_getfont(x), tag); #endif /* ROCKBOX */ /* draw y labels */ for (i = 0; i < x->gl_nylabels; i++) #ifdef ROCKBOX ; #else /* ROCKBOX */ sys_vgui(".x%x.c create text\ %d %d -text {%s} -font -*-courier-bold--normal--%d-* -tags %s\n", glist_getcanvas(x), (int)glist_xtopixels(x, x->gl_ylabelx), (int)glist_ytopixels(x, atof(x->gl_ylabel[i]->s_name)), x->gl_ylabel[i]->s_name, glist_getfont(x), tag); #endif /* ROCKBOX */ /* draw contents of graph as glist */ for (g = x->gl_list; g; g = g->g_next) gobj_vis(g, x, 1); } else { #ifndef ROCKBOX sys_vgui(".x%x.c delete %s\n", glist_getcanvas(x->gl_owner), tag); #endif for (g = x->gl_list; g; g = g->g_next) gobj_vis(g, x, 0); } } /* get the graph's rectangle, not counting extra swelling for controls to keep them inside the graph. This is the "logical" pixel size. */ static void graph_graphrect(t_gobj *z, t_glist *glist, int *xp1, int *yp1, int *xp2, int *yp2) { t_glist *x = (t_glist *)z; int x1 = text_xpix(&x->gl_obj, glist); int y1 = text_ypix(&x->gl_obj, glist); int x2, y2; #if 0 /* this used to adjust graph size when it was in another graph; now we just preserve the size. */ /* same logic here as in text_xpix(): */ if (glist->gl_havewindow) { x2 = x1 + x->gl_pixwidth; y2 = y1 + x->gl_pixheight; } else { x2 = glist_xtopixels(glist, glist->gl_x1 + (glist->gl_x2 - glist->gl_x1) * (x->gl_obj.te_xpix + x->gl_pixwidth) / (glist->gl_screenx2 - glist->gl_screenx1)); y2 = glist_ytopixels(glist, glist->gl_y1 + (glist->gl_y2 - glist->gl_y1) * (x->gl_obj.te_ypix + x->gl_pixheight) / (glist->gl_screeny2 - glist->gl_screeny1)); } #endif x2 = x1 + x->gl_pixwidth; y2 = y1 + x->gl_pixheight; *xp1 = x1; *yp1 = y1; *xp2 = x2; *yp2 = y2; } /* get the rectangle, enlarged to contain all the "contents" -- meaning their formal bounds rectangles. */ static void graph_getrect(t_gobj *z, t_glist *glist, int *xp1, int *yp1, int *xp2, int *yp2) { int x1 = 0x7fffffff, y1 = 0x7fffffff, x2 = -0x7fffffff, y2 = -0x7fffffff; t_glist *x = (t_glist *)z; if (x->gl_isgraph) { int hadwindow; t_gobj *g; t_text *ob; int x21, y21, x22, y22; graph_graphrect(z, glist, &x1, &y1, &x2, &y2); if (canvas_showtext(x)) { text_widgetbehavior.w_getrectfn(z, glist, &x21, &y21, &x22, &y22); if (x22 > x2) x2 = x22; if (y22 > y2) y2 = y22; } /* lie about whether we have our own window to affect gobj_getrect calls below. (LATER add argument to gobj_getrect()?) */ hadwindow = x->gl_havewindow; x->gl_havewindow = 0; for (g = x->gl_list; g; g = g->g_next) if ((!(ob = pd_checkobject(&g->g_pd))) || text_shouldvis(ob, x)) { /* don't do this for arrays, just let them hang outsize the box. */ if (pd_class(&g->g_pd) == garray_class) continue; gobj_getrect(g, x, &x21, &y21, &x22, &y22); if (x22 > x2) x2 = x22; if (y22 > y2) y2 = y22; } x->gl_havewindow = hadwindow; } else text_widgetbehavior.w_getrectfn(z, glist, &x1, &y1, &x2, &y2); *xp1 = x1; *yp1 = y1; *xp2 = x2; *yp2 = y2; } static void graph_displace(t_gobj *z, t_glist *glist, int dx, int dy) { t_glist *x = (t_glist *)z; if (!x->gl_isgraph) text_widgetbehavior.w_displacefn(z, glist, dx, dy); else { x->gl_obj.te_xpix += dx; x->gl_obj.te_ypix += dy; glist_redraw(x); canvas_fixlinesfor(glist_getcanvas(glist), &x->gl_obj); } } static void graph_select(t_gobj *z, t_glist *glist, int state) { t_glist *x = (t_glist *)z; if (!x->gl_isgraph) text_widgetbehavior.w_selectfn(z, glist, state); else { t_rtext *y = glist_findrtext(glist, &x->gl_obj); if (canvas_showtext(x)) rtext_select(y, state); #ifndef ROCKBOX sys_vgui(".x%x.c itemconfigure %sR -fill %s\n", glist, rtext_gettag(y), (state? "blue" : "black")); sys_vgui(".x%x.c itemconfigure graph%x -fill %s\n", glist_getcanvas(glist), z, (state? "blue" : "black")); #endif } } static void graph_activate(t_gobj *z, t_glist *glist, int state) { t_glist *x = (t_glist *)z; if (canvas_showtext(x)) text_widgetbehavior.w_activatefn(z, glist, state); } #if 0 static void graph_delete(t_gobj *z, t_glist *glist) { t_glist *x = (t_glist *)z; if (!x->gl_isgraph) text_widgetbehavior.w_deletefn(z, glist); else { t_gobj *y; while (y = x->gl_list) glist_delete(x, y); #if 0 /* I think this was just wrong. */ if (glist_isvisible(x)) sys_vgui(".x%x.c delete graph%x\n", glist_getcanvas(glist), x); #endif } } #endif static void graph_delete(t_gobj *z, t_glist *glist) { t_glist *x = (t_glist *)z; t_gobj *y; text_widgetbehavior.w_deletefn(z, glist); while((y = x->gl_list)) glist_delete(x, y); } #ifndef ROCKBOX static float graph_lastxpix, graph_lastypix; static void graph_motion(void *z, t_floatarg dx, t_floatarg dy) { t_glist *x = (t_glist *)z; float newxpix = graph_lastxpix + dx, newypix = graph_lastypix + dy; t_garray *a = (t_garray *)(x->gl_list); int oldx = 0.5 + glist_pixelstox(x, graph_lastxpix); int newx = 0.5 + glist_pixelstox(x, newxpix); t_sample *vec; int nelem, i; float oldy = glist_pixelstoy(x, graph_lastypix); float newy = glist_pixelstoy(x, newypix); graph_lastxpix = newxpix; graph_lastypix = newypix; /* verify that the array is OK */ if (!a || pd_class((t_pd *)a) != garray_class) return; if (!garray_getfloatarray(a, &nelem, &vec)) return; if (oldx < 0) oldx = 0; if (oldx >= nelem) oldx = nelem - 1; if (newx < 0) newx = 0; if (newx >= nelem) newx = nelem - 1; if (oldx < newx - 1) { for (i = oldx + 1; i <= newx; i++) vec[i] = newy + (oldy - newy) * ((float)(newx - i))/(float)(newx - oldx); } else if (oldx > newx + 1) { for (i = oldx - 1; i >= newx; i--) vec[i] = newy + (oldy - newy) * ((float)(newx - i))/(float)(newx - oldx); } else vec[newx] = newy; garray_redraw(a); } #endif static int graph_click(t_gobj *z, struct _glist *glist, int xpix, int ypix, int shift, int alt, int dbl, int doit) { t_glist *x = (t_glist *)z; t_gobj *y; int clickreturned = 0; if (!x->gl_isgraph) return (text_widgetbehavior.w_clickfn(z, glist, xpix, ypix, shift, alt, dbl, doit)); else if (x->gl_havewindow) return (0); else { for (y = x->gl_list; y; y = y->g_next) { int x1, y1, x2, y2; /* check if the object wants to be clicked */ if (canvas_hitbox(x, y, xpix, ypix, &x1, &y1, &x2, &y2) && (clickreturned = gobj_click(y, x, xpix, ypix, shift, alt, 0, doit))) break; } if (!doit) { if (y) canvas_setcursor(glist_getcanvas(x), clickreturned); else canvas_setcursor(glist_getcanvas(x), CURSOR_RUNMODE_NOTHING); } return (clickreturned); } }