File: asciicast.c

package info (click to toggle)
termrec 0.19-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,148 kB
  • sloc: ansic: 8,430; makefile: 181; perl: 16; sh: 15
file content (574 lines) | stat: -rw-r--r-- 14,245 bytes parent folder | download
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
#include "config.h"
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "gettext.h"
#include "tty.h"
#include "ttyrec.h"
#include "formats.h"
#include "export.h"


/*******************/
/***** reading *****/
/*******************/

// Blasting many pages in a single frame is borderline legitimate, but let's
// have a sanity limit -- data that was actually recorded into separate
// frames with tiny but non-zero delays.
// Incidentally, this also allows avoiding managing a dynamic buffer.
// 1M is way too high but userspace stack is aplenty.
#define BUFFER_SIZE 1048576

// Reimplement stdio's FILE with only getc() and ungetc() methods -- all this
// needed only because multiple ungetcs don't work, especially not if the file
// had been read() before.
#define NIH_FILE_BUFFER 4096
#define NIH_NO_UNGET -2
struct nih_file
{
    int fd;
    int unget;
    int pos;
    int len;
    char buf[NIH_FILE_BUFFER];
};
typedef struct nih_file NIH_FILE;

static int nih_getc(NIH_FILE *f)
{
    if (f->unget != NIH_NO_UNGET)
    {
        int c = f->unget;
        f->unget = NIH_NO_UNGET;
        return c;
    }

    if (f->pos>=f->len)
    {
        f->len = read(f->fd, f->buf, NIH_FILE_BUFFER);
        if (f->len<=0)
            return EOF;
        f->pos = 0;
    }

    return (unsigned char)f->buf[f->pos++];
}

static void nih_ungetc(int c, NIH_FILE *f)
{
    f->unget = c;
}

#undef getc
#undef ungetc
#define getc(f) nih_getc(f)
#define ungetc(c,f) nih_ungetc(c,f)

#define EAT(x) do c=getc(f); while (c==' ' || c=='\t' || c=='\r' || c=='\n' x)

static bool eat_colon(NIH_FILE *f)
{
    int c;
    EAT();
    if (c != ':')
        return false;
    EAT();
    ungetc(c, f);
    return true;
}

static int64_t eat_int(NIH_FILE *f)
{
    int64_t x=0;
    while (1)
    {
        int c=getc(f);
        if (c>='0' && c<='9')
            x=x*10+c-'0';
        else
        {
            ungetc(c, f);
            return x;
        }
    }
}

// *1000000
static int64_t eat_float(NIH_FILE *f)
{
    int c;
    int64_t x=0;
    c=getc(f);
    while (c>='0' && c<='9')
        x=x*10+c-'0', c=getc(f);
    x*=1000000;

    if (c=='.')
    {
        int y=1000000;
        c=getc(f);
        while (c>='0' && c<='9')
            x+= (c-'0')*(y/=10), c=getc(f);
    }

    if (c=='e' || c=='E')
    {
        bool minus=false;
        c=getc(f);
        if (c=='+')
            c=getc(f);
        else if (c=='-')
            c=getc(f), minus=true;
        int e=0;
        while (c>='0' && c<='9')
            e=e*10+c-'0', c=getc(f);
        if (minus)
            while (e-->0)
                x/=10;
        else
            while (e-->0)
                x*=10;
    }

    ungetc(c, f);
    return x;
}

static int eat_hexdigit(NIH_FILE *f)
{
    int c=getc(f);
    if (c>='0' && c<='9')
        return c-'0';
    if (c>='a' && c<='f')
        return c+10-'a';
    if (c>='A' && c<='F')
        return c+10-'A';
    ungetc(c, f);
    return -1;
}

#define OUT(x) do if (--spc) *buf++=(x); else goto end; while (0)
static char* eat_string(NIH_FILE *f, char *buf)
{
    int spc=BUFFER_SIZE;
    uint16_t surrogate=0;

    while (1)
    {
        int c=getc(f);
        if (c==EOF || c=='"')
            break;
        if (c!='\\')
            OUT(c);
        else switch (c=getc(f))
        {
        case 'b':
            OUT('\b'); break;
        case 'f':
            OUT('\f'); break;
        case 'n':
            OUT('\n'); break;
        case 'r':
            OUT('\r'); break;
        case 't':
            OUT('\t'); break;
        case 'u':
            c = eat_hexdigit(f)<<12
              | eat_hexdigit(f)<<8
              | eat_hexdigit(f)<<4
              | eat_hexdigit(f);

            if (c < 0) // not a valid 16-bit hex value
                break;

            if (c < 0x80)
                OUT(c);
            else if (c < 0x800)
            {
                OUT(0xc0|c>>6);
                OUT(0x80|c&0x3f);
            }
            else if (c < 0xD800 || c > 0xDFFF)
            {
                OUT(0xe0|c>>12);
                OUT(0x80|c>>6&0x3f);
                OUT(0x80|c&0x3f);
            }
            // Note: we allow erroneous surrogate pairs separated by
            // something, silently ignore lone lead or trailing ones.
            else if (c < 0xDC00)
                surrogate = c;
            else if (surrogate)
            {
                c=((uint32_t)surrogate)<<10&0xffc00|c&0x3ff;
                c+=0x10000;
                OUT(0xf0|c>>18);
                OUT(0x80|c>>12&0x3f);
                OUT(0x80|c>>6&0x3f);
                OUT(0x80|c&0x3f);
                surrogate=0;
            }
            break;
        case '"': case '\\': case '/':
        default:
            OUT(c);    break;
        }
    }
end:
    *buf=0;
    return buf;
}

#define FAIL(x) do {const char* t=(x);return synch_print(t, strlen(t), arg);} while (0)
void do_play_asciicast(int fd, const char *obuf, int olen,
    void (*synch_init_wait)(const struct timeval *ts, void *arg),
    void (*synch_wait)(const struct timeval *tv, void *arg),
    void (*synch_print)(const char *buf, int len, void *arg),
    void *arg, const struct timeval *cont)
{
    NIH_FILE nih_f, *f=&nih_f;
    nih_f.fd=fd;
    nih_f.unget=NIH_NO_UNGET;
    nih_f.pos=nih_f.len=0;
    if (obuf)
    {
        memcpy(nih_f.buf, obuf, olen);
        nih_f.len = olen;
    }

    char buf[BUFFER_SIZE];
    int bracket_level = 0;
    int version = -1;
    int c;
    int sx=80, sy=25;
    struct timeval tv;
    tv.tv_sec = tv.tv_usec = 0;

    EAT();
    if (c != '{')
        FAIL("Not an asciicast: doesn't start with a JSON object.\n");

    // Read the header.
    while (1)
    {
expect_field:
        switch (c = getc(f))
        {
        case EOF:
            FAIL("Not an asciicast: end of file within header.\n");
        case ' ': case '\t': case '\r': case '\n':
            continue;
        case '"':
            eat_string(f, buf);
            if (!eat_colon(f))
                FAIL("Not an asciicast: no colon after field name.\n");
            if (bracket_level)
            {
skip_field:
                EAT();
                if (c==EOF)
                    FAIL("Not an asciicast: end of file within header.\n");
                else if (c=='"')
                    eat_string(f, buf);
                else if (c>='0' && c<='9')
                    ungetc(c, f), eat_float(f);
                else if (c=='{')
                {
                    bracket_level++;
                    goto expect_field;
                }
                else if (c=='n' && (c=getc(f))=='u'
                                && (c=getc(f))=='l'
                                && (c=getc(f))=='l')
                {}
                else
                    FAIL("Not an asciicast: junk within header.\n");
            }
            else if (!strcmp(buf, "version"))
            {
                int64_t v = eat_int(f);
                if (v == 1 || v == 2)
                    version = v;
                else
                    FAIL("Unsupported asciicast version.\n");
            }
            else if (!strcmp(buf, "width"))
                sx = eat_int(f);
            else if (!strcmp(buf, "height"))
                sy = eat_int(f);
            else if (!strcmp(buf, "timestamp"))
            {
                int64_t v = eat_float(f);
                tv.tv_sec =  v/1000000;
                tv.tv_usec = v%1000000;
            }
            else if (version == 1 && !strcmp(buf, "stdout"))
            {
                if (getc(f) != '[')
                    FAIL("Not an asciicast: v1 stdout not an array.\n");
                goto body;
            }
            else
                goto skip_field;

            EAT();
            if (c == '}')
            {
                bracket_level--;
                EAT();
            }
            if (c == '}')
            {
                ungetc(c, f);
                goto expect_field;
            }
            if (c == '[' && bracket_level == -1)
            {
                ungetc(c, f);
                goto body;
            }
            if (c != ',')
                FAIL("Not an asciicast: junk after a JSON field.\n");
            break;
        case '}':
            if (version == 2 && !bracket_level)
                goto body;
            bracket_level--;
            break;
        default:
            FAIL("Not an asciicast: bad header.\n");
        }
    }
    /* not reached */

body:
    synch_init_wait(&tv, arg);
    synch_print(buf, sprintf(buf, "\e%%G\e[8;%d;%dt", sy, sx), arg);
    uint64_t old_delay = 0;

    while (1)
    {
        EAT(|| c==',');
        if (c == EOF || c == '}' || c == ']')
            return;
        if (c != '[')
            FAIL("Malformed asciicast: frame not an array.\n");

        EAT();
        if (c>='0' && c<='9')
            ungetc(c, f);
        else
            FAIL("Malformed asciicast: expected duration.\n");

        int64_t delay = eat_float(f);
        if (version == 2)
        {
            delay -= old_delay;
            old_delay += delay;
        }
        tv.tv_sec =  delay/1000000;
        tv.tv_usec = delay%1000000;
        synch_wait(&tv, arg);

        EAT();
        if (c != ',')
            FAIL("Malformed asciicast: no comma after duration.\n");

        if (version == 2)
        {
            EAT();
            if (c != '"')
                FAIL("Malformed asciicast: expected event type.\n");
            eat_string(f, buf);
            EAT();
            if (c != ',')
                FAIL("Malformed asciicast: no comma after event type.\n");
        }

        EAT();
        if (c !='"')
            FAIL("Malformed asciicast: expected even-data string.\n");
        synch_print(buf, eat_string(f, buf) - buf, arg);

        EAT();
        if (c !=']')
            FAIL("Malformed asciicast: event not terminated.\n");
    }
}

void play_asciicast(FILE *f,
    void (*synch_init_wait)(const struct timeval *ts, void *arg),
    void (*synch_wait)(const struct timeval *tv, void *arg),
    void (*synch_print)(const char *buf, int len, void *arg),
    void *arg, const struct timeval *cont)
{
    do_play_asciicast(fileno(f), 0, 0,
                      synch_init_wait, synch_wait, synch_print, arg, cont);
}

/*******************/
/***** writing *****/
/*******************/

struct ac_state
{
    bool head_done;
    bool need_comma;
    char version;
    char putf[4];
    struct timeval ts;
};

void* record_asciicast_init(FILE *f, const struct timeval *tm)
{
    struct ac_state *as = malloc(sizeof(struct ac_state));
    as->head_done = false;
    as->need_comma = false;
    if (tm)
        as->ts = *tm;
    else
        as->ts.tv_sec=as->ts.tv_usec = 0;
    as->putf[0] = 0;
    as->version = 2;

    return as;
}

#define WANT(x) if (!len-- || *b++!=(x)) return 0
static int skip_utf_term_size(const char *b, int len)
{
    const char *buf0 = b;
    WANT('\e');
    WANT('%');
    WANT('G');
    WANT('\e');
    WANT('[');
    WANT('8');
    WANT(';');
    while (len && *b>='0' && *b<='9')
        len--, b++;
    WANT(';');
    while (len && *b>='0' && *b<='9')
        len--, b++;
    WANT('t');
    return b-buf0;
}
#undef WANT

static int skip_partial_utf(const char *b, int len)
{
    int part=0;
    while (part<4 && part<len && ((unsigned char)b[len-part-1])>=0x80
                              && ((unsigned char)b[len-part-1])<0xc0)
        part++;
    if (part>=len)
        return 0;
    char c = b[len-++part];
    if ((c&0xe0)==0xc0 && part<2)
        return part;
    if ((c&0xf0)==0xe0 && part<3)
        return part;
    if ((c&0xf8)==0xf0 && part<4)
        return part;
    return 0;
}

void record_asciicast(FILE *f, void* state, const struct timeval *tm, const char *buf, int len)
{
    struct ac_state *as = state;
    if (!as->head_done)
    {
        // need to play first frame to fetch screen size
        tty vt = tty_init(80, 25, 1);
        tty_write(vt, buf, len);
        fprintf(f, "{\"version\":%d, \"width\":%d, \"height\":%d",
            as->version, vt->sx, vt->sy);
        if (as->ts.tv_sec)
            fprintf(f, ", \"timestamp\":%lld", (long long int)as->ts.tv_sec);
        if (as->version == 1)
            fprintf(f, ", \"stdout\":[\n");
        else
            fprintf(f, "}\n");
        tty_free(vt);
        as->head_done = true;

        int skip = skip_utf_term_size(buf, len);
        buf+=skip;
        if (!(len-=skip))
            return;
    }

    char *buf2 = 0;
    int skip = strlen(as->putf);
    if (skip)
        if ((buf2 = malloc(skip + len)))
        {
            memcpy(buf2, as->putf, skip);
            memcpy(buf2+skip, buf, len);
            buf = buf2;
            len+=skip;
        }
        else
            return;
    skip = skip_partial_utf(buf, len);
    len-=skip;
    memcpy(as->putf, buf+len, skip);
    as->putf[skip]=0;

    if (!len)
        return;

    if (as->version == 1)
    {
        if (as->need_comma)
            fprintf(f, ",\n");
        else
            as->need_comma = true;
        struct timeval ts = *tm;
        if (as->ts.tv_sec || as->ts.tv_usec)
            tsub(ts, as->ts);
        else
            ts.tv_sec = ts.tv_usec = 0;
        as->ts = *tm;
        fprintf(f, "[%f, \"", ts.tv_sec+ts.tv_usec*0.000001);
    }
    else
        fprintf(f, "[%f, \"o\", \"", tm->tv_sec-as->ts.tv_sec+tm->tv_usec*0.000001);
    while (len-->0)
    {
        if (((unsigned char)*buf)<' ')
            if (*buf=='\r')
                fputs("\\r", f);
            else if (*buf=='\n')
                fputs("\\n", f);
            else
                fprintf(f, "\\u%04x", *buf);
        else if (*buf=='"')
            fputs("\\\"", f);
        else
            fputc(*buf, f);
        buf++;
    }
    fprintf(f, as->version==1? "\"]" : "\"]\n");
    if (buf2)
        free(buf2);
}

void record_asciicast_finish(FILE *f, void* state)
{
    struct ac_state *as = state;
    if (as->version == 1)
        fprintf(f, "\n]}\n");
    free(state);
}


void* record_asciicast_v1_init(FILE *f, const struct timeval *tm)
{
    struct ac_state *as = record_asciicast_init(f, tm);
    as->version=1;
    return as;
}