summaryrefslogtreecommitdiff
path: root/apps/plugins/lua/lcode.c
blob: cff626b7fa6df8307dad49803a0236ebc71f336f (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
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
/*
** $Id: lcode.c,v 2.25.1.3 2007/12/28 15:32:23 roberto Exp $
** Code generator for Lua
** See Copyright Notice in lua.h
*/


#include <stdlib.h>

#define lcode_c
#define LUA_CORE

#include "lua.h"

#include "lcode.h"
#include "ldebug.h"
#include "ldo.h"
#include "lgc.h"
#include "llex.h"
#include "lmem.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lparser.h"
#include "ltable.h"


#define hasjumps(e)	((e)->t != (e)->f)


static int isnumeral(expdesc *e) {
  return (e->k == VKNUM && e->t == NO_JUMP && e->f == NO_JUMP);
}


void luaK_nil (FuncState *fs, int from, int n) {
  Instruction *previous;
  if (fs->pc > fs->lasttarget) {  /* no jumps to current position? */
    if (fs->pc == 0) {  /* function start? */
      if (from >= fs->nactvar)
        return;  /* positions are already clean */
    }
    else {
      previous = &fs->f->code[fs->pc-1];
      if (GET_OPCODE(*previous) == OP_LOADNIL) {
        int pfrom = GETARG_A(*previous);
        int pto = GETARG_B(*previous);
        if (pfrom <= from && from <= pto+1) {  /* can connect both? */
          if (from+n-1 > pto)
            SETARG_B(*previous, from+n-1);
          return;
        }
      }
    }
  }
  luaK_codeABC(fs, OP_LOADNIL, from, from+n-1, 0);  /* else no optimization */
}


int luaK_jump (FuncState *fs) {
  int jpc = fs->jpc;  /* save list of jumps to here */
  int j;
  fs->jpc = NO_JUMP;
  j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP);
  luaK_concat(fs, &j, jpc);  /* keep them on hold */
  return j;
}


void luaK_ret (FuncState *fs, int first, int nret) {
  luaK_codeABC(fs, OP_RETURN, first, nret+1, 0);
}


static int condjump (FuncState *fs, OpCode op, int A, int B, int C) {
  luaK_codeABC(fs, op, A, B, C);
  return luaK_jump(fs);
}


static void fixjump (FuncState *fs, int pc, int dest) {
  Instruction *jmp = &fs->f->code[pc];
  int offset = dest-(pc+1);
  lua_assert(dest != NO_JUMP);
  if (abs(offset) > MAXARG_sBx)
    luaX_syntaxerror(fs->ls, "control structure too long");
  SETARG_sBx(*jmp, offset);
}


/*
** returns current `pc' and marks it as a jump target (to avoid wrong
** optimizations with consecutive instructions not in the same basic block).
*/
int luaK_getlabel (FuncState *fs) {
  fs->lasttarget = fs->pc;
  return fs->pc;
}


static int getjump (FuncState *fs, int pc) {
  int offset = GETARG_sBx(fs->f->code[pc]);
  if (offset == NO_JUMP)  /* point to itself represents end of list */
    return NO_JUMP;  /* end of list */
  else
    return (pc+1)+offset;  /* turn offset into absolute position */
}


static Instruction *getjumpcontrol (FuncState *fs, int pc) {
  Instruction *pi = &fs->f->code[pc];
  if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1))))
    return pi-1;
  else
    return pi;
}


/*
** check whether list has any jump that do not produce a value
** (or produce an inverted value)
*/
static int need_value (FuncState *fs, int list) {
  for (; list != NO_JUMP; list = getjump(fs, list)) {
    Instruction i = *getjumpcontrol(fs, list);
    if (GET_OPCODE(i) != OP_TESTSET) return 1;
  }
  return 0;  /* not found */
}


static int patchtestreg (FuncState *fs, int node, int reg) {
  Instruction *i = getjumpcontrol(fs, node);
  if (GET_OPCODE(*i) != OP_TESTSET)
    return 0;  /* cannot patch other instructions */
  if (reg != NO_REG && reg != GETARG_B(*i))
    SETARG_A(*i, reg);
  else  /* no register to put value or register already has the value */
    *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i));

  return 1;
}


static void removevalues (FuncState *fs, int list) {
  for (; list != NO_JUMP; list = getjump(fs, list))
      patchtestreg(fs, list, NO_REG);
}


static void patchlistaux (FuncState *fs, int list, int vtarget, int reg,
                          int dtarget) {
  while (list != NO_JUMP) {
    int next = getjump(fs, list);
    if (patchtestreg(fs, list, reg))
      fixjump(fs, list, vtarget);
    else
      fixjump(fs, list, dtarget);  /* jump to default target */
    list = next;
  }
}


static void dischargejpc (FuncState *fs) {
  patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc);
  fs->jpc = NO_JUMP;
}


void luaK_patchlist (FuncState *fs, int list, int target) {
  if (target == fs->pc)
    luaK_patchtohere(fs, list);
  else {
    lua_assert(target < fs->pc);
    patchlistaux(fs, list, target, NO_REG, target);
  }
}


void luaK_patchtohere (FuncState *fs, int list) {
  luaK_getlabel(fs);
  luaK_concat(fs, &fs->jpc, list);
}


void luaK_concat (FuncState *fs, int *l1, int l2) {
  if (l2 == NO_JUMP) return;
  else if (*l1 == NO_JUMP)
    *l1 = l2;
  else {
    int list = *l1;
    int next;
    while ((next = getjump(fs, list)) != NO_JUMP)  /* find last element */
      list = next;
    fixjump(fs, list, l2);
  }
}


void luaK_checkstack (FuncState *fs, int n) {
  int newstack = fs->freereg + n;
  if (newstack > fs->f->maxstacksize) {
    if (newstack >= MAXSTACK)
      luaX_syntaxerror(fs->ls, "function or expression too complex");
    fs->f->maxstacksize = cast_byte(newstack);
  }
}


void luaK_reserveregs (FuncState *fs, int n) {
  luaK_checkstack(fs, n);
  fs->freereg += n;
}


static void freereg (FuncState *fs, int reg) {
  if (!ISK(reg) && reg >= fs->nactvar) {
    fs->freereg--;
    lua_assert(reg == fs->freereg);
  }
}


static void freeexp (FuncState *fs, expdesc *e) {
  if (e->k == VNONRELOC)
    freereg(fs, e->u.s.info);
}


static int addk (FuncState *fs, TValue *k, TValue *v) {
  lua_State *L = fs->L;
  TValue *idx = luaH_set(L, fs->h, k);
  Proto *f = fs->f;
  int oldsize = f->sizek;
  if (ttisnumber(idx)) {
    lua_assert(luaO_rawequalObj(&fs->f->k[cast_int(nvalue(idx))], v));
    return cast_int(nvalue(idx));
  }
  else {  /* constant not found; create a new entry */
    setnvalue(idx, cast_num(fs->nk));
    luaM_growvector(L, f->k, fs->nk, f->sizek, TValue,
                    MAXARG_Bx, "constant table overflow");
    while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
    setobj(L, &f->k[fs->nk], v);
    luaC_barrier(L, f, v);
    return fs->nk++;
  }
}


int luaK_stringK (FuncState *fs, TString *s) {
  TValue o;
  setsvalue(fs->L, &o, s);
  return addk(fs, &o, &o);
}


int luaK_numberK (FuncState *fs, lua_Number r) {
  TValue o;
  setnvalue(&o, r);
  return addk(fs, &o, &o);
}


static int boolK (FuncState *fs, int b) {
  TValue o;
  setbvalue(&o, b);
  return addk(fs, &o, &o);
}


static int nilK (FuncState *fs) {
  TValue k, v;
  setnilvalue(&v);
  /* cannot use nil as key; instead use table itself to represent nil */
  sethvalue(fs->L, &k, fs->h);
  return addk(fs, &k, &v);
}


void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) {
  if (e->k == VCALL) {  /* expression is an open function call? */
    SETARG_C(getcode(fs, e), nresults+1);
  }
  else if (e->k == VVARARG) {
    SETARG_B(getcode(fs, e), nresults+1);
    SETARG_A(getcode(fs, e), fs->freereg);
    luaK_reserveregs(fs, 1);
  }
}


void luaK_setoneret (FuncState *fs, expdesc *e) {
  if (e->k == VCALL) {  /* expression is an open function call? */
    e->k = VNONRELOC;
    e->u.s.info = GETARG_A(getcode(fs, e));
  }
  else if (e->k == VVARARG) {
    SETARG_B(getcode(fs, e), 2);
    e->k = VRELOCABLE;  /* can relocate its simple result */
  }
}


void luaK_dischargevars (FuncState *fs, expdesc *e) {
  switch (e->k) {
    case VLOCAL: {
      e->k = VNONRELOC;
      break;
    }
    case VUPVAL: {
      e->u.s.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.s.info, 0);
      e->k = VRELOCABLE;
      break;
    }
    case VGLOBAL: {
      e->u.s.info = luaK_codeABx(fs, OP_GETGLOBAL, 0, e->u.s.info);
      e->k = VRELOCABLE;
      break;
    }
    case VINDEXED: {
      freereg(fs, e->u.s.aux);
      freereg(fs, e->u.s.info);
      e->u.s.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.s.info, e->u.s.aux);
      e->k = VRELOCABLE;
      break;
    }
    case VVARARG:
    case VCALL: {
      luaK_setoneret(fs, e);
      break;
    }
    default: break;  /* there is one value available (somewhere) */
  }
}


static int code_label (FuncState *fs, int A, int b, int jump) {
  luaK_getlabel(fs);  /* those instructions may be jump targets */
  return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump);
}


static void discharge2reg (FuncState *fs, expdesc *e, int reg) {
  luaK_dischargevars(fs, e);
  switch (e->k) {
    case VNIL: {
      luaK_nil(fs, reg, 1);
      break;
    }
    case VFALSE:  case VTRUE: {
      luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0);
      break;
    }
    case VK: {
      luaK_codeABx(fs, OP_LOADK, reg, e->u.s.info);
      break;
    }
    case VKNUM: {
      luaK_codeABx(fs, OP_LOADK, reg, luaK_numberK(fs, e->u.nval));
      break;
    }
    case VRELOCABLE: {
      Instruction *pc = &getcode(fs, e);
      SETARG_A(*pc, reg);
      break;
    }
    case VNONRELOC: {
      if (reg != e->u.s.info)
        luaK_codeABC(fs, OP_MOVE, reg, e->u.s.info, 0);
      break;
    }
    default: {
      lua_assert(e->k == VVOID || e->k == VJMP);
      return;  /* nothing to do... */
    }
  }
  e->u.s.info = reg;
  e->k = VNONRELOC;
}


static void discharge2anyreg (FuncState *fs, expdesc *e) {
  if (e->k != VNONRELOC) {
    luaK_reserveregs(fs, 1);
    discharge2reg(fs, e, fs->freereg-1);
  }
}


static void exp2reg (FuncState *fs, expdesc *e, int reg) {
  discharge2reg(fs, e, reg);
  if (e->k == VJMP)
    luaK_concat(fs, &e->t, e->u.s.info);  /* put this jump in `t' list */
  if (hasjumps(e)) {
    int final;  /* position after whole expression */
    int p_f = NO_JUMP;  /* position of an eventual LOAD false */
    int p_t = NO_JUMP;  /* position of an eventual LOAD true */
    if (need_value(fs, e->t) || need_value(fs, e->f)) {
      int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs);
      p_f = code_label(fs, reg, 0, 1);
      p_t = code_label(fs, reg, 1, 0);
      luaK_patchtohere(fs, fj);
    }
    final = luaK_getlabel(fs);
    patchlistaux(fs, e->f, final, reg, p_f);
    patchlistaux(fs, e->t, final, reg, p_t);
  }
  e->f = e->t = NO_JUMP;
  e->u.s.info = reg;
  e->k = VNONRELOC;
}


void luaK_exp2nextreg (FuncState *fs, expdesc *e) {
  luaK_dischargevars(fs, e);
  freeexp(fs, e);
  luaK_reserveregs(fs, 1);
  exp2reg(fs, e, fs->freereg - 1);
}


int luaK_exp2anyreg (FuncState *fs, expdesc *e) {
  luaK_dischargevars(fs, e);
  if (e->k == VNONRELOC) {
    if (!hasjumps(e)) return e->u.s.info;  /* exp is already in a register */
    if (e->u.s.info >= fs->nactvar) {  /* reg. is not a local? */
      exp2reg(fs, e, e->u.s.info);  /* put value on it */
      return e->u.s.info;
    }
  }
  luaK_exp2nextreg(fs, e);  /* default */
  return e->u.s.info;
}


void luaK_exp2val (FuncState *fs, expdesc *e) {
  if (hasjumps(e))
    luaK_exp2anyreg(fs, e);
  else
    luaK_dischargevars(fs, e);
}


int luaK_exp2RK (FuncState *fs, expdesc *e) {
  luaK_exp2val(fs, e);
  switch (e->k) {
    case VKNUM:
    case VTRUE:
    case VFALSE:
    case VNIL: {
      if (fs->nk <= MAXINDEXRK) {  /* constant fit in RK operand? */
        e->u.s.info = (e->k == VNIL)  ? nilK(fs) :
                      (e->k == VKNUM) ? luaK_numberK(fs, e->u.nval) :
                                        boolK(fs, (e->k == VTRUE));
        e->k = VK;
        return RKASK(e->u.s.info);
      }
      else break;
    }
    case VK: {
      if (e->u.s.info <= MAXINDEXRK)  /* constant fit in argC? */
        return RKASK(e->u.s.info);
      else break;
    }
    default: break;
  }
  /* not a constant in the right range: put it in a register */
  return luaK_exp2anyreg(fs, e);
}


void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) {
  switch (var->k) {
    case VLOCAL: {
      freeexp(fs, ex);
      exp2reg(fs, ex, var->u.s.info);
      return;
    }
    case VUPVAL: {
      int e = luaK_exp2anyreg(fs, ex);
      luaK_codeABC(fs, OP_SETUPVAL, e, var->u.s.info, 0);
      break;
    }
    case VGLOBAL: {
      int e = luaK_exp2anyreg(fs, ex);
      luaK_codeABx(fs, OP_SETGLOBAL, e, var->u.s.info);
      break;
    }
    case VINDEXED: {
      int e = luaK_exp2RK(fs, ex);
      luaK_codeABC(fs, OP_SETTABLE, var->u.s.info, var->u.s.aux, e);
      break;
    }
    default: {
      lua_assert(0);  /* invalid var kind to store */
      break;
    }
  }
  freeexp(fs, ex);
}


void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {
  int func;
  luaK_exp2anyreg(fs, e);
  freeexp(fs, e);
  func = fs->freereg;
  luaK_reserveregs(fs, 2);
  luaK_codeABC(fs, OP_SELF, func, e->u.s.info, luaK_exp2RK(fs, key));
  freeexp(fs, key);
  e->u.s.info = func;
  e->k = VNONRELOC;
}


static void invertjump (FuncState *fs, expdesc *e) {
  Instruction *pc = getjumpcontrol(fs, e->u.s.info);
  lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET &&
                                           GET_OPCODE(*pc) != OP_TEST);
  SETARG_A(*pc, !(GETARG_A(*pc)));
}


static int jumponcond (FuncState *fs, expdesc *e, int cond) {
  if (e->k == VRELOCABLE) {
    Instruction ie = getcode(fs, e);
    if (GET_OPCODE(ie) == OP_NOT) {
      fs->pc--;  /* remove previous OP_NOT */
      return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond);
    }
    /* else go through */
  }
  discharge2anyreg(fs, e);
  freeexp(fs, e);
  return condjump(fs, OP_TESTSET, NO_REG, e->u.s.info, cond);
}


void luaK_goiftrue (FuncState *fs, expdesc *e) {
  int pc;  /* pc of last jump */
  luaK_dischargevars(fs, e);
  switch (e->k) {
    case VK: case VKNUM: case VTRUE: {
      pc = NO_JUMP;  /* always true; do nothing */
      break;
    }
    case VFALSE: {
      pc = luaK_jump(fs);  /* always jump */
      break;
    }
    case VJMP: {
      invertjump(fs, e);
      pc = e->u.s.info;
      break;
    }
    default: {
      pc = jumponcond(fs, e, 0);
      break;
    }
  }
  luaK_concat(fs, &e->f, pc);  /* insert last jump in `f' list */
  luaK_patchtohere(fs, e->t);
  e->t = NO_JUMP;
}


static void luaK_goiffalse (FuncState *fs, expdesc *e) {
  int pc;  /* pc of last jump */
  luaK_dischargevars(fs, e);
  switch (e->k) {
    case VNIL: case VFALSE: {
      pc = NO_JUMP;  /* always false; do nothing */
      break;
    }
    case VTRUE: {
      pc = luaK_jump(fs);  /* always jump */
      break;
    }
    case VJMP: {
      pc = e->u.s.info;
      break;
    }
    default: {
      pc = jumponcond(fs, e, 1);
      break;
    }
  }
  luaK_concat(fs, &e->t, pc);  /* insert last jump in `t' list */
  luaK_patchtohere(fs, e->f);
  e->f = NO_JUMP;
}


static void codenot (FuncState *fs, expdesc *e) {
  luaK_dischargevars(fs, e);
  switch (e->k) {
    case VNIL: case VFALSE: {
      e->k = VTRUE;
      break;
    }
    case VK: case VKNUM: case VTRUE: {
      e->k = VFALSE;
      break;
    }
    case VJMP: {
      invertjump(fs, e);
      break;
    }
    case VRELOCABLE:
    case VNONRELOC: {
      discharge2anyreg(fs, e);
      freeexp(fs, e);
      e->u.s.info = luaK_codeABC(fs, OP_NOT, 0, e->u.s.info, 0);
      e->k = VRELOCABLE;
      break;
    }
    default: {
      lua_assert(0);  /* cannot happen */
      break;
    }
  }
  /* interchange true and false lists */
  { int temp = e->f; e->f = e->t; e->t = temp; }
  removevalues(fs, e->f);
  removevalues(fs, e->t);
}


void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {
  t->u.s.aux = luaK_exp2RK(fs, k);
  t->k = VINDEXED;
}


static int constfolding (OpCode op, expdesc *e1, expdesc *e2) {
  lua_Number v1, v2, r;
  if (!isnumeral(e1) || !isnumeral(e2)) return 0;
  v1 = e1->u.nval;
  v2 = e2->u.nval;
  switch (op) {
    case OP_ADD: r = luai_numadd(v1, v2); break;
    case OP_SUB: r = luai_numsub(v1, v2); break;
    case OP_MUL: r = luai_nummul(v1, v2); break;
    case OP_DIV:
      if (v2 == 0) return 0;  /* do not attempt to divide by 0 */
      r = luai_numdiv(v1, v2); break;
    case OP_MOD:
      if (v2 == 0) return 0;  /* do not attempt to divide by 0 */
      r = luai_nummod(v1, v2); break;
    case OP_POW: r = luai_numpow(v1, v2); break;
    case OP_UNM: r = luai_numunm(v1); break;
    case OP_LEN: return 0;  /* no constant folding for 'len' */
    default: lua_assert(0); r = 0; break;
  }
  if (luai_numisnan(r)) return 0;  /* do not attempt to produce NaN */
  e1->u.nval = r;
  return 1;
}


static void codearith (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2) {
  if (constfolding(op, e1, e2))
    return;
  else {
    int o2 = (op != OP_UNM && op != OP_LEN) ? luaK_exp2RK(fs, e2) : 0;
    int o1 = luaK_exp2RK(fs, e1);
    if (o1 > o2) {
      freeexp(fs, e1);
      freeexp(fs, e2);
    }
    else {
      freeexp(fs, e2);
      freeexp(fs, e1);
    }
    e1->u.s.info = luaK_codeABC(fs, op, 0, o1, o2);
    e1->k = VRELOCABLE;
  }
}


static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1,
                                                          expdesc *e2) {
  int o1 = luaK_exp2RK(fs, e1);
  int o2 = luaK_exp2RK(fs, e2);
  freeexp(fs, e2);
  freeexp(fs, e1);
  if (cond == 0 && op != OP_EQ) {
    int temp;  /* exchange args to replace by `<' or `<=' */
    temp = o1; o1 = o2; o2 = temp;  /* o1 <==> o2 */
    cond = 1;
  }
  e1->u.s.info = condjump(fs, op, cond, o1, o2);
  e1->k = VJMP;
}


void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e) {
  expdesc e2;
  e2.t = e2.f = NO_JUMP; e2.k = VKNUM; e2.u.nval = 0;
  switch (op) {
    case OPR_MINUS: {
      if (!isnumeral(e))
        luaK_exp2anyreg(fs, e);  /* cannot operate on non-numeric constants */
      codearith(fs, OP_UNM, e, &e2);
      break;
    }
    case OPR_NOT: codenot(fs, e); break;
    case OPR_LEN: {
      luaK_exp2anyreg(fs, e);  /* cannot operate on constants */
      codearith(fs, OP_LEN, e, &e2);
      break;
    }
    default: lua_assert(0);
  }
}


void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
  switch (op) {
    case OPR_AND: {
      luaK_goiftrue(fs, v);
      break;
    }
    case OPR_OR: {
      luaK_goiffalse(fs, v);
      break;
    }
    case OPR_CONCAT: {
      luaK_exp2nextreg(fs, v);  /* operand must be on the `stack' */
      break;
    }
    case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV:
    case OPR_MOD: case OPR_POW: {
      if (!isnumeral(v)) luaK_exp2RK(fs, v);
      break;
    }
    default: {
      luaK_exp2RK(fs, v);
      break;
    }
  }
}


void luaK_posfix (FuncState *fs, BinOpr op, expdesc *e1, expdesc *e2) {
  switch (op) {
    case OPR_AND: {
      lua_assert(e1->t == NO_JUMP);  /* list must be closed */
      luaK_dischargevars(fs, e2);
      luaK_concat(fs, &e2->f, e1->f);
      *e1 = *e2;
      break;
    }
    case OPR_OR: {
      lua_assert(e1->f == NO_JUMP);  /* list must be closed */
      luaK_dischargevars(fs, e2);
      luaK_concat(fs, &e2->t, e1->t);
      *e1 = *e2;
      break;
    }
    case OPR_CONCAT: {
      luaK_exp2val(fs, e2);
      if (e2->k == VRELOCABLE && GET_OPCODE(getcode(fs, e2)) == OP_CONCAT) {
        lua_assert(e1->u.s.info == GETARG_B(getcode(fs, e2))-1);
        freeexp(fs, e1);
        SETARG_B(getcode(fs, e2), e1->u.s.info);
        e1->k = VRELOCABLE; e1->u.s.info = e2->u.s.info;
      }
      else {
        luaK_exp2nextreg(fs, e2);  /* operand must be on the 'stack' */
        codearith(fs, OP_CONCAT, e1, e2);
      }
      break;
    }
    case OPR_ADD: codearith(fs, OP_ADD, e1, e2); break;
    case OPR_SUB: codearith(fs, OP_SUB, e1, e2); break;
    case OPR_MUL: codearith(fs, OP_MUL, e1, e2); break;
    case OPR_DIV: codearith(fs, OP_DIV, e1, e2); break;
    case OPR_MOD: codearith(fs, OP_MOD, e1, e2); break;
    case OPR_POW: codearith(fs, OP_POW, e1, e2); break;
    case OPR_EQ: codecomp(fs, OP_EQ, 1, e1, e2); break;
    case OPR_NE: codecomp(fs, OP_EQ, 0, e1, e2); break;
    case OPR_LT: codecomp(fs, OP_LT, 1, e1, e2); break;
    case OPR_LE: codecomp(fs, OP_LE, 1, e1, e2); break;
    case OPR_GT: codecomp(fs, OP_LT, 0, e1, e2); break;
    case OPR_GE: codecomp(fs, OP_LE, 0, e1, e2); break;
    default: lua_assert(0);
  }
}


void luaK_fixline (FuncState *fs, int line) {
  fs->f->lineinfo[fs->pc - 1] = line;
}


static int luaK_code (FuncState *fs, Instruction i, int line) {
  Proto *f = fs->f;
  dischargejpc(fs);  /* `pc' will change */
  /* put new instruction in code array */
  luaM_growvector(fs->L, f->code, fs->pc, f->sizecode, Instruction,
                  MAX_INT, "code size overflow");
  f->code[fs->pc] = i;
  /* save corresponding line information */
  luaM_growvector(fs->L, f->lineinfo, fs->pc, f->sizelineinfo, int,
                  MAX_INT, "code size overflow");
  f->lineinfo[fs->pc] = line;
  return fs->pc++;
}


int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) {
  lua_assert(getOpMode(o) == iABC);
  lua_assert(getBMode(o) != OpArgN || b == 0);
  lua_assert(getCMode(o) != OpArgN || c == 0);
  return luaK_code(fs, CREATE_ABC(o, a, b, c), fs->ls->lastline);
}


int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) {
  lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx);
  lua_assert(getCMode(o) == OpArgN);
  return luaK_code(fs, CREATE_ABx(o, a, bc), fs->ls->lastline);
}


void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) {
  int c =  (nelems - 1)/LFIELDS_PER_FLUSH + 1;
  int b = (tostore == LUA_MULTRET) ? 0 : tostore;
  lua_assert(tostore != 0);
  if (c <= MAXARG_C)
    luaK_codeABC(fs, OP_SETLIST, base, b, c);
  else {
    luaK_codeABC(fs, OP_SETLIST, base, b, 0);
    luaK_code(fs, cast(Instruction, c), fs->ls->lastline);
  }
  fs->freereg = base + 1;  /* free registers with list values */
}

wb">const char*str, bool join) { if (join) lrc_buffer_used--; size_t siz = rb->strlen(str)+1; char *pos = &lrc_buffer[lrc_buffer_used]; if (lrc_buffer_used + siz > lrc_buffer_end) return NULL; rb->strcpy(pos, str); lrc_buffer_used += siz; return pos; } static void *alloc_buf(size_t siz) { siz = (siz+3) & ~3; if (lrc_buffer_used + siz > lrc_buffer_end) return NULL; lrc_buffer_end -= siz; return &lrc_buffer[lrc_buffer_end]; } static void *new_lrc_word(long time_start, char *word, bool join) { struct lrc_word *lrc_word; if ((lrc_word = alloc_buf(sizeof(struct lrc_word))) == NULL) return NULL; if ((lrc_word->word = lrcbufadd(word, join)) == NULL) return NULL; lrc_word->time_start = time_start; return lrc_word; } static bool add_lrc_line(struct lrc_line *lrc_line, char *word) { lrc_line->nword = 0; lrc_line->next = NULL; lrc_line->words = NULL; if (word) { if ((lrc_line->words = new_lrc_word(-1, word, false)) == NULL) return false; lrc_line->nword++; } *current.ll_tail = lrc_line; current.ll_tail = &(lrc_line->next); current.nlrcline++; return true; } static struct lrc_line *get_lrc_line(int idx) { static struct lrc_line *lrc_line = NULL; static int n = 0; if (idx < n) { lrc_line = current.ll_head; n = 0; } while (n < idx && lrc_line) { lrc_line = lrc_line->next; n++; } return lrc_line; } static char *get_lrc_str(struct lrc_line *lrc_line) { return lrc_line->words[lrc_line->nword-1].word; } static long get_time_start(struct lrc_line *lrc_line) { if (!lrc_line) return current.length+20; long time = lrc_line->time_start + current.offset; return time < 0? 0: time; } static void set_time_start(struct lrc_line *lrc_line, long time_start) { time_start -= current.offset; time_start -= time_start%10; if (lrc_line->time_start != time_start) { lrc_line->time_start = time_start; current.changed_lrc = true; } } #define get_word_time_start(x) get_time_start((struct lrc_line *)(x)) #define set_word_time_start(x, t) set_time_start((struct lrc_line *)(x), (t)) static int format_time_tag(char *buf, long t) { return rb->snprintf(buf, 16, "%02ld:%02ld.%02ld", t/60000, (t/1000)%60, (t/10)%100); } /* find start of next line */ static const char *lrc_skip_space(const char *str) { #ifdef HAVE_LCD_BITMAP if (prefs.wrap) { while (*str && *str != '\n' && isspace(*str)) str++; } #endif if (*str == '\n') str++; return str; } #ifdef HAVE_LCD_BITMAP static bool isbrchr(const unsigned char *str, int len) { const unsigned char *p = "!,-.:;? 、。!,.:;?―"; if (isspace(*str)) return true; while(*p) { int n = rb->utf8seek(p, 1); if (len == n && !rb->strncmp(p, str, len)) return true; p += n; } return false; } #endif /* calculate how many lines is needed to display and store it. * create cache if there is enough space in lrc_buffer. */ static struct lrc_brpos *calc_brpos(struct lrc_line *lrc_line, int i) { struct lrc_brpos *lrc_brpos; struct lrc_word *lrc_word; int nlrcbrpos = 0, max_lrcbrpos; #ifdef HAVE_LCD_BITMAP uifont = rb->screens[0]->getuifont(); struct font* pf = rb->font_get(uifont); unsigned short ch; #endif struct snap { int count, width; int nword; int word_count, word_width; const unsigned char *str; } #ifndef HAVE_LCD_CHARCELLS sp, #endif cr; lrc_buffer_used = (lrc_buffer_used+3)&~3; /* 4 bytes aligned */ lrc_brpos = (struct lrc_brpos *) &lrc_buffer[lrc_buffer_used]; max_lrcbrpos = (lrc_buffer_end-lrc_buffer_used) / sizeof(struct lrc_brpos); if (!lrc_line) { /* calc info for all lrcs and store them if possible */ size_t buffer_used = lrc_buffer_used; bool too_many_lines = false; current.too_many_lines = true; for (lrc_line = current.ll_head; lrc_line; lrc_line = lrc_line->next) { FOR_NB_SCREENS(i) { lrc_brpos = calc_brpos(lrc_line, i); if (!too_many_lines) { lrc_buffer_used += lrc_line->nline[i]*sizeof(struct lrc_brpos); if (nlrcbrpos + lrc_line->nline[i] >= max_lrcbrpos) { too_many_lines = true; lrc_buffer_used = buffer_used; calc_brpos(lrc_line, i); } } nlrcbrpos += lrc_line->nline[i]; } } current.too_many_lines = too_many_lines; lrc_buffer_used = buffer_used; current.nlrcbrpos = nlrcbrpos; return NULL; } if (!current.too_many_lines) { /* use stored infos. */ struct lrc_line *temp_lrc = current.ll_head; for (; temp_lrc != lrc_line; temp_lrc = temp_lrc->next) { lrc_brpos += temp_lrc->nline[SCREEN_MAIN]; #ifdef HAVE_REMOTE_LCD lrc_brpos += temp_lrc->nline[SCREEN_REMOTE]; #endif } #if NB_SCREENS >= 2 while (i) lrc_brpos += lrc_line->nline[--i]; #endif return lrc_brpos; } /* calculate number of lines, line width and char count for each line. */ lrc_line->width = 0; cr.nword = lrc_line->nword; lrc_word = lrc_line->words+cr.nword; cr.str = (lrc_word-1)->word; #ifndef HAVE_LCD_CHARCELLS sp.word_count = 0; sp.word_width = 0; sp.nword = 0; sp.count = 0; sp.width = 0; #endif do { cr.count = 0; cr.width = 0; #ifndef HAVE_LCD_CHARCELLS sp.str = NULL; #endif while (1) { while(cr.nword > 0 && cr.str >= (lrc_word-1)->word) { cr.nword--; lrc_word--; lrc_word->count = 0; lrc_word->width = 0; } if (*cr.str == 0 || *cr.str == '\n') break; int c, w; #ifdef HAVE_LCD_CHARCELLS c = rb->utf8seek(cr.str, 1); w = 1; #else c = ((intptr_t)rb->utf8decode(cr.str, &ch) - (intptr_t)cr.str); if (rb->is_diacritic(ch, NULL)) w = 0; else w = rb->font_get_width(pf, ch); if (cr.count && prefs.wrap && isbrchr(cr.str, c)) { /* remember position of last space */ rb->memcpy(&sp, &cr, sizeof(struct snap)); sp.word_count = lrc_word->count; sp.word_width = lrc_word->width; if (!isspace(*cr.str) && cr.width+w <= vp_lyrics[i].width) { sp.count += c; sp.width += w; sp.word_count += c; sp.word_width += w; sp.str += c; } } if (cr.count && cr.width+w > vp_lyrics[i].width) { if (sp.str != NULL) /* wrap */ { rb->memcpy(&cr, &sp, sizeof(struct snap)); lrc_word = lrc_line->words+cr.nword; lrc_word->count = sp.word_count; lrc_word->width = sp.word_width; } break; } #endif cr.count += c; cr.width += w; lrc_word->count += c; lrc_word->width += w; cr.str += c; } lrc_line->width += cr.width; lrc_brpos->count = cr.count; lrc_brpos->width = cr.width; nlrcbrpos++; lrc_brpos++; cr.str = lrc_skip_space(cr.str); } while (*cr.str && nlrcbrpos < max_lrcbrpos); lrc_line->nline[i] = nlrcbrpos; while (cr.nword > 0) { cr.nword--; lrc_word--; lrc_word->count = 0; lrc_word->width = 0; } return lrc_brpos-nlrcbrpos; } /* sort lyrics by time using stable sort. */ static void sort_lrcs(void) { struct lrc_line *p = current.ll_head, **q = NULL, *t; long time_max = 0; current.ll_head = NULL; current.ll_tail = &current.ll_head; while (p != NULL) { t = p->next; /* remove problematic lrc_lines. * it would cause problem in display_lrc_line() if nword is 0. */ if (p->nword) { q = p->time_start >= time_max? current.ll_tail: &current.ll_head; while ((*q) && (*q)->time_start <= p->time_start) q = &((*q)->next); p->next = *q; *q = p; if (!p->next) { time_max = p->time_start; current.ll_tail = &p->next; } } p = t; } if (!current.too_many_lines) calc_brpos(NULL, 0); /* stored data depends on order of lrcs if exist */ } static void init_time_tag(void) { struct lrc_line *lrc_line = current.ll_head; int nline = 0; if (current.type == TXT || current.type == ID3_USLT) { /* set time tag according to length of audio and total line count * for not synched lyrics, so that scroll speed is almost constant. */ for (; lrc_line; lrc_line = lrc_line->next) { lrc_line->time_start = nline * current.length / current.nlrcbrpos; lrc_line->time_start -= lrc_line->time_start%10; lrc_line->old_time_start = -1; nline += lrc_line->nline[SCREEN_MAIN]; #ifdef HAVE_REMOTE_LCD nline += lrc_line->nline[SCREEN_REMOTE]; #endif } } else { /* reset timetags to the value read from file */ for (; lrc_line; lrc_line = lrc_line->next) { lrc_line->time_start = lrc_line->old_time_start; } sort_lrcs(); } current.changed_lrc = false; } /******************************* * Serch lrc file. *******************************/ /* search in same or parent directries of playing file. * assume playing file is /aaa/bbb/ccc/ddd.mp3, * this function searchs lrc file following order. * /aaa/bbb/ccc/ddd.lrc * /aaa/bbb/ddd.lrc * /aaa/ddd.lrc * /ddd.lrc */ /* taken from apps/recorder/albumart.c */ static void fix_filename(char* name) { static const char invalid_chars[] = "*/:<>?\\|"; while (1) { if (*name == 0) return; if (*name == '"') *name = '\''; else if (rb->strchr(invalid_chars, *name)) *name = '_'; name++; } } static bool find_lrc_file_helper(const char *base_dir) { char fname[MAX_PATH]; char *names[3] = {NULL, NULL, NULL}; char *p, *dir; int i, len; /* /aaa/bbb/ccc/ddd.mp3 * dir <--q names[0] */ /* assuming file name starts with '/' */ rb->strcpy(temp_buf, current.mp3_file); /* get file name and remove extension */ names[0] = rb->strrchr(temp_buf, '/')+1; if ((p = rb->strrchr(names[0], '.')) != NULL) *p = 0; if (current.id3->title && rb->strcmp(names[0], current.id3->title)) { rb->strlcpy(fname, current.id3->title, sizeof(fname)); fix_filename(fname); names[1] = fname; } dir = temp_buf; p = names[0]-1; do { int n; *p = 0; for (n = 0; ; n++) { if (n == 0) { len = rb->snprintf(current.lrc_file, MAX_PATH, "%s%s/", base_dir, dir); } else if (n == 1) { /* check file in subfolder named prefs.lrc_directory * in the directory of mp3 file. */ if (prefs.lrc_directory[0] == '/') { len = rb->snprintf(current.lrc_file, MAX_PATH, "%s%s/", dir, prefs.lrc_directory); } else continue; } else break; DEBUGF("check file in %s\n", current.lrc_file); if (!rb->dir_exists(current.lrc_file)) continue; for (current.type = 0; current.type < NUM_TYPES; current.type++) { for (i = 0; names[i] != NULL; i++) { rb->snprintf(&current.lrc_file[len], MAX_PATH-len, "%s%s", names[i], extentions[current.type]); if (rb->file_exists(current.lrc_file)) { DEBUGF("found: `%s'\n", current.lrc_file); return true; } } } } } while ((p = rb->strrchr(dir, '/')) != NULL); return false; } /* return true if a lrc file is found */ static bool find_lrc_file(void) { reset_current_data(); DEBUGF("find lrc file for `%s'\n", current.mp3_file); /* find .lrc file */ if (find_lrc_file_helper("")) return true; if (prefs.lrc_directory[0] == '/' && rb->dir_exists(prefs.lrc_directory)) { if (find_lrc_file_helper(prefs.lrc_directory)) return true; } current.lrc_file[0] = 0; return false; } /******************************* * Load file. *******************************/ /* check tag format and calculate value of the tag. * supported tag: ti, ar, offset * supported format of time tag: [mm:ss], [mm:ss.xx], [mm:ss.xxx] * returns value of timega if tag is time tag, -1 if tag is supported tag, * -10 otherwise. */ static char *parse_int(char *ptr, int *val) { *val = rb->atoi(ptr); while (isdigit(*ptr)) ptr++; return ptr; } static long get_time_value(char *tag, bool read_id_tags, off_t file_offset) { long time; char *ptr; int val; if (read_id_tags) { if (!rb->strncmp(tag, "ti:", 3)) { if (!current.id3->title || rb->strcmp(&tag[3], current.id3->title)) current.title = lrcbufadd(&tag[3], false); return -1; } if (!rb->strncmp(tag, "ar:", 3)) { if (!current.id3->artist || rb->strcmp(&tag[3], current.id3->artist)) current.artist = lrcbufadd(&tag[3], false); return -1; } if (!rb->strncmp(tag, "offset:", 7)) { current.offset = rb->atoi(&tag[7]); current.offset_file_offset = file_offset; return -1; } } /* minute */ ptr = parse_int(tag, &val); if (ptr-tag < 1 || ptr-tag > 2 || *ptr != ':') return -10; time = val * 60000; /* second */ tag = ptr+1; ptr = parse_int(tag, &val); if (ptr-tag != 2 || (*ptr != '.' && *ptr != ':' && *ptr != '\0')) return -10; time += val * 1000; if (*ptr != '\0') { /* milliseccond */ tag = ptr+1; ptr = parse_int(tag, &val); if (ptr-tag < 2 || ptr-tag > 3 || *ptr != '\0') return -10; time += ((ptr-tag)==3 ?val: val*10); } return time; } /* format: * [time tag]line * [time tag]...[time tag]line * [time tag]<word time tag>word<word time tag>...<word time tag> */ static bool parse_lrc_line(char *line, off_t file_offset) { struct lrc_line *lrc_line = NULL, *first_lrc_line = NULL; long time, time_start; char *str, *tagstart, *tagend; struct lrc_word *lrc_word; int nword = 0; /* parse [time tag]...[time tag] type tags */ str = line; while (1) { if (*str != '[') break; tagend = rb->strchr(str, ']'); if (tagend == NULL) break; *tagend = 0; time = get_time_value(str+1, !lrc_line, file_offset); *tagend++ = ']'; if (time < 0) break; lrc_line = alloc_buf(sizeof(struct lrc_line)); if (lrc_line == NULL) return false; if (!first_lrc_line) first_lrc_line = lrc_line; lrc_line->file_offset = file_offset; lrc_line->time_start = (time/10)*10; lrc_line->old_time_start = lrc_line->time_start; add_lrc_line(lrc_line, NULL); file_offset += (intptr_t)tagend - (intptr_t)str; str = tagend; } if (!first_lrc_line) return true; /* no time tag in line */ lrc_line = first_lrc_line; if (lrcbufadd("", false) == NULL) return false; /* parse <word time tag>...<word time tag> type tags */ /* [time tag]...[time tag]line type tags share lrc_line->words and can't * use lrc_line->words->timestart. use lrc_line->time_start instead. */ time_start = -1; tagstart = str; while (*tagstart) { tagstart = rb->strchr(tagstart, '<'); if (!tagstart) break; tagend = rb->strchr(tagstart, '>'); if (!tagend) break; *tagend = 0; time = get_time_value(tagstart+1, false, file_offset + ((intptr_t)tagstart - (intptr_t)str)); *tagend++ = '>'; if (time < 0) { tagstart++; continue; } *tagstart = 0; /* found word time tag. */ if (*str || time_start != -1) { if ((lrc_word = new_lrc_word(time_start, str, true)) == NULL) return false; nword++; } file_offset += (intptr_t)tagend - (intptr_t)str; tagstart = str = tagend; time_start = time; } if ((lrc_word = new_lrc_word(time_start, str, true)) == NULL) return false; nword++; /* duplicate lrc_lines */ while (lrc_line) { lrc_line->nword = nword; lrc_line->words = lrc_word; lrc_line = lrc_line->next; } return true; } /* format: * \xa2\xe2hhmmssxx\xa2\xd0 * line 1 * line 2 * \xa2\xe2hhmmssxx\xa2\xd0 * line 3 * ... */ static bool parse_snc_line(char *line, off_t file_offset) { #define SNC_TAG_START "\xa2\xe2" #define SNC_TAG_END "\xa2\xd0" /* SNC_TAG can be dencoded, so use * temp_buf which contains native data */ if (!rb->memcmp(temp_buf, SNC_TAG_START, 2) && !rb->memcmp(temp_buf+10, SNC_TAG_END, 2)) /* time tag */ { const char *pos = temp_buf+2; /* skip SNC_TAG_START */ int hh, mm, ss, xx; hh = (pos[0]-'0')*10+(pos[1]-'0'); pos += 2; mm = (pos[0]-'0')*10+(pos[1]-'0'); pos += 2; ss = (pos[0]-'0')*10+(pos[1]-'0'); pos += 2; xx = (pos[0]-'0')*10+(pos[1]-'0'); pos += 2; pos += 2; /* skip SNC_TAG_END */ /* initialize */ struct lrc_line *lrc_line = alloc_buf(sizeof(struct lrc_line)); if (lrc_line == NULL) return false; lrc_line->file_offset = file_offset+2; lrc_line->time_start = hh*3600000+mm*60000+ss*1000+xx*10; lrc_line->old_time_start = lrc_line->time_start; if (!add_lrc_line(lrc_line, "")) return false; if (pos[0]==0) return true; /* encode rest of line and add to buffer */ rb->iso_decode(pos, line, prefs.encoding, rb->strlen(pos)+1); } if (current.ll_head) { rb->strcat(line, "\n"); if (lrcbufadd(line, true) == NULL) return false; } return true; } static bool parse_txt_line(char *line, off_t file_offset) { /* initialize */ struct lrc_line *lrc_line = alloc_buf(sizeof(struct lrc_line)); if (lrc_line == NULL) return false; lrc_line->file_offset = file_offset; lrc_line->time_start = 0; lrc_line->old_time_start = -1; if (!add_lrc_line(lrc_line, line)) return false; return true; } static void load_lrc_file(void) { char utf8line[MAX_LINE_LEN*3]; int fd; int encoding = prefs.encoding; bool (*line_parser)(char *line, off_t) = NULL; off_t file_offset, readsize; switch(current.type) { case LRC8: encoding = UTF_8; /* .lrc8 is utf8 */ /* fall through */ case LRC: line_parser = parse_lrc_line; break; case SNC: line_parser = parse_snc_line; break; case TXT: line_parser = parse_txt_line; break; default: return; } fd = rb->open(current.lrc_file, O_RDONLY); if (fd < 0) return; { /* check encoding */ #define BOM "\xef\xbb\xbf" #define BOM_SIZE 3 unsigned char header[BOM_SIZE]; unsigned char* (*utf_decode)(const unsigned char *, unsigned char *, int) = NULL; rb->read(fd, header, BOM_SIZE); if (!rb->memcmp(header, BOM, BOM_SIZE)) /* UTF-8 */ { encoding = UTF_8; } else if (!rb->memcmp(header, "\xff\xfe", 2)) /* UTF-16LE */ { utf_decode = rb->utf16LEdecode; } else if (!rb->memcmp(header, "\xfe\xff", 2)) /* UTF-16BE */ { utf_decode = rb->utf16BEdecode; } else { rb->lseek(fd, 0, SEEK_SET); } if (utf_decode) { /* convert encoding of file from UTF-16 to UTF-8 */ char temp_file[MAX_PATH]; int fe; rb->lseek(fd, 2, SEEK_SET); rb->snprintf(temp_file, MAX_PATH, "%s~", current.lrc_file); fe = rb->creat(temp_file, 0666); if (fe < 0) { rb->close(fd); return; } rb->write(fe, BOM, BOM_SIZE); while ((readsize = rb->read(fd, temp_buf, MAX_LINE_LEN)) > 0) { char *end = utf_decode(temp_buf, utf8line, readsize/2); rb->write(fe, utf8line, end-utf8line); } rb->close(fe); rb->close(fd); rb->remove(current.lrc_file); rb->rename(temp_file, current.lrc_file); fd = rb->open(current.lrc_file, O_RDONLY); if (fd < 0) return; rb->lseek(fd, BOM_SIZE, SEEK_SET); /* skip bom */ encoding = UTF_8; } } file_offset = rb->lseek(fd, 0, SEEK_CUR); /* used in line_parser */ while ((readsize = rb->read_line(fd, temp_buf, MAX_LINE_LEN)) > 0) { /* note: parse_snc_line() reads temp_buf for native data. */ rb->iso_decode(temp_buf, utf8line, encoding, readsize+1); if (!line_parser(utf8line, file_offset)) break; file_offset += readsize; } rb->close(fd); current.loaded_lrc = true; calc_brpos(NULL, 0); init_time_tag(); return; } #ifdef LRC_SUPPORT_ID3 /******************************* * read lyrics from id3 *******************************/ static unsigned long unsync(unsigned long b0, unsigned long b1, unsigned long b2, unsigned long b3) { return (((long)(b0 & 0x7F) << (3*7)) | ((long)(b1 & 0x7F) << (2*7)) | ((long)(b2 & 0x7F) << (1*7)) | ((long)(b3 & 0x7F) << (0*7))); } static unsigned long bytes2int(unsigned long b0, unsigned long b1, unsigned long b2, unsigned long b3) { return (((long)(b0 & 0xFF) << (3*8)) | ((long)(b1 & 0xFF) << (2*8)) | ((long)(b2 & 0xFF) << (1*8)) | ((long)(b3 & 0xFF) << (0*8))); } static int unsynchronize(char* tag, int len, bool *ff_found) { int i; unsigned char c; unsigned char *rp, *wp; bool _ff_found = false; if(ff_found) _ff_found = *ff_found; wp = rp = (unsigned char *)tag; rp = (unsigned char *)tag; for(i = 0; i<len; i++) { /* Read the next byte and write it back, but don't increment the write pointer */ c = *rp++; *wp = c; if(_ff_found) { /* Increment the write pointer if it isn't an unsynch pattern */ if(c != 0) wp++; _ff_found = false; } else { if(c == 0xff) _ff_found = true; wp++; } } if(ff_found) *ff_found = _ff_found; return (intptr_t)wp - (intptr_t)tag; } static int read_unsynched(int fd, void *buf, int len, bool *ff_found) { int i; int rc; int remaining = len; char *wp; wp = buf; while(remaining) { rc = rb->read(fd, wp, remaining); if(rc <= 0) return rc; i = unsynchronize(wp, remaining, ff_found); remaining -= i; wp += i; } return len; } static unsigned char* utf8cpy(const unsigned char *src, unsigned char *dst, int count) { rb->strlcpy(dst, src, count+1); return dst+rb->strlen(dst); } static void parse_id3v2(int fd) { int minframesize; int size; long framelen; char header[10]; char tmp[8]; unsigned char version; int bytesread = 0; unsigned char global_flags; int flags; bool global_unsynch = false; bool global_ff_found = false; bool unsynch = false; int rc; enum {NOLT, SYLT, USLT} type = NOLT; /* Bail out if the tag is shorter than 10 bytes */ if(current.id3->id3v2len < 10) return; /* Read the ID3 tag version from the header */ if(10 != rb->read(fd, header, 10)) return; /* Get the total ID3 tag size */ size = current.id3->id3v2len - 10; version = current.id3->id3version; switch ( version ) { case ID3_VER_2_2: minframesize = 8; break; case ID3_VER_2_3: minframesize = 12; break; case ID3_VER_2_4: minframesize = 12; break; default: /* unsupported id3 version */ return; } global_flags = header[5]; /* Skip the extended header if it is present */ if(global_flags & 0x40) { if(version == ID3_VER_2_3) { if(10 != rb->read(fd, header, 10)) return; /* The 2.3 extended header size doesn't include the header size field itself. Also, it is not unsynched. */ framelen = bytes2int(header[0], header[1], header[2], header[3]) + 4; /* Skip the rest of the header */ rb->lseek(fd, framelen - 10, SEEK_CUR); } if(version >= ID3_VER_2_4) { if(4 != rb->read(fd, header, 4)) return; /* The 2.4 extended header size does include the entire header, so here we can just skip it. This header is unsynched. */ framelen = unsync(header[0], header[1], header[2], header[3]); rb->lseek(fd, framelen - 4, SEEK_CUR); } } /* Is unsynchronization applied? */ if(global_flags & 0x80) { global_unsynch = true; } /* We must have at least minframesize bytes left for the * remaining frames to be interesting */ while (size >= minframesize) { flags = 0; /* Read frame header and check length */ if(version >= ID3_VER_2_3) { if(global_unsynch && version <= ID3_VER_2_3) rc = read_unsynched(fd, header, 10, &global_ff_found); else rc = rb->read(fd, header, 10); if(rc != 10) return; /* Adjust for the 10 bytes we read */ size -= 10; flags = bytes2int(0, 0, header[8], header[9]); if (version >= ID3_VER_2_4) { framelen = unsync(header[4], header[5], header[6], header[7]); } else { /* version .3 files don't use synchsafe ints for * size */ framelen = bytes2int(header[4], header[5], header[6], header[7]); } } else { if(6 != rb->read(fd, header, 6)) return; /* Adjust for the 6 bytes we read */ size -= 6; framelen = bytes2int(0, header[3], header[4], header[5]); } if(framelen == 0){ if (header[0] == 0 && header[1] == 0 && header[2] == 0) return; else continue; } unsynch = false; if(flags) { if (version >= ID3_VER_2_4) { if(flags & 0x0040) { /* Grouping identity */ rb->lseek(fd, 1, SEEK_CUR); /* Skip 1 byte */ framelen--; } } else { if(flags & 0x0020) { /* Grouping identity */ rb->lseek(fd, 1, SEEK_CUR); /* Skip 1 byte */ framelen--; } } if(flags & 0x000c) /* Compression or encryption */ { /* Skip it */ size -= framelen; rb->lseek(fd, framelen, SEEK_CUR); continue; } if(flags & 0x0002) /* Unsynchronization */ unsynch = true; if (version >= ID3_VER_2_4) { if(flags & 0x0001) { /* Data length indicator */ if(4 != rb->read(fd, tmp, 4)) return; /* We don't need the data length */ framelen -= 4; } } } if (framelen == 0) continue; if (framelen < 0) return; if(!rb->memcmp( header, "SLT", 3 ) || !rb->memcmp( header, "SYLT", 4 )) { /* found a supported tag */ type = SYLT; break; } else if(!rb->memcmp( header, "ULT", 3 ) || !rb->memcmp( header, "USLT", 4 )) { /* found a supported tag */ type = USLT; break; } else { /* not a supported tag*/ if(global_unsynch && version <= ID3_VER_2_3) { size -= read_unsynched(fd, lrc_buffer, framelen, &global_ff_found); } else { size -= framelen; if( rb->lseek(fd, framelen, SEEK_CUR) == -1 ) return; } } } if(type == NOLT) return; int encoding = 0, chsiz; char *tag, *p, utf8line[MAX_LINE_LEN*3]; unsigned char* (*utf_decode)(const unsigned char *, unsigned char *, int) = NULL; /* use middle of lrc_buffer to store tag data. */ if(framelen >= LRC_BUFFER_SIZE/3) framelen = LRC_BUFFER_SIZE/3-1; tag = lrc_buffer+LRC_BUFFER_SIZE*2/3-framelen-1; if(global_unsynch && version <= ID3_VER_2_3) bytesread = read_unsynched(fd, tag, framelen, &global_ff_found); else bytesread = rb->read(fd, tag, framelen); if( bytesread != framelen ) return; if(unsynch || (global_unsynch && version >= ID3_VER_2_4)) bytesread = unsynchronize(tag, bytesread, NULL); tag[bytesread] = 0; encoding = tag[0]; p = tag; /* skip some data */ if(type == SYLT) { p += 6; } else { p += 4; } /* check encoding and skip content descriptor */ switch (encoding) { case 0x01: /* Unicode with or without BOM */ case 0x02: /* Now check if there is a BOM (zero-width non-breaking space, 0xfeff) and if it is in little or big endian format */ if(!rb->memcmp(p, "\xff\xfe", 2)) { /* Little endian? */ utf_decode = rb->utf16LEdecode; } else if(!rb->memcmp(p, "\xfe\xff", 2)) { /* Big endian? */ utf_decode = rb->utf16BEdecode; } else utf_decode = NULL; encoding = NUM_CODEPAGES; do { size = p[0] | p[1]; p += 2; } while(size); chsiz = 2; break; default: utf_decode = utf8cpy; if(encoding == 0x03) /* UTF-8 encoded string */ encoding = UTF_8; else encoding = prefs.encoding; p += rb->strlen(p)+1; chsiz = 1; break; } if(encoding == NUM_CODEPAGES) {