aboutsummaryrefslogtreecommitdiff
path: root/cyclone/hammer/seq.c
blob: 030a7ab54e399f21cdf522993dbc6ee9992693ce (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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
/* Copyright (c) 2002-2005 krzYszcz and others.
 * For information on usage and redistribution, and for a DISCLAIMER OF ALL
 * WARRANTIES, see the file, "LICENSE.txt," in this distribution.  */

/* CHECKED no sharing of data among seq objects having the same creation arg */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "m_pd.h"
#include "shared.h"
#include "common/loud.h"
#include "common/grow.h"
#include "common/fitter.h"
#include "common/mifi.h"
#include "unstable/forky.h"
#include "hammer/file.h"

#ifdef KRZYSZCZ
#define SEQ_DEBUG
#endif

#define SEQ_INISEQSIZE       256   /* LATER rethink */
#define SEQ_INITEMPOMAPSIZE  128   /* LATER rethink */
#define SEQ_EOM              255   /* end of message marker, LATER rethink */
#define SEQ_TICKSPERSEC       48
#define SEQ_MINTICKDELAY       1.  /* LATER rethink */
#define SEQ_TICKEPSILON  ((double).0001)

enum { SEQ_IDLEMODE, SEQ_RECMODE, SEQ_PLAYMODE, SEQ_SLAVEMODE };

typedef struct _seqevent
{
    double         e_delta;
    unsigned char  e_bytes[4];
} t_seqevent;

typedef struct _seqtempo
{
    double  t_scoretime;  /* score ticks from start */
    double  t_sr;         /* score ticks per second */
} t_seqtempo;

typedef struct _seq
{
    t_object       x_ob;
    t_canvas      *x_canvas;
    t_symbol      *x_defname;
    t_hammerfile  *x_filehandle;
    int            x_mode;
    int            x_playhead;
    double         x_nextscoretime;
    float          x_timescale;
    float          x_newtimescale;
    double         x_prevtime;
    double         x_slaveprevtime;
    double         x_clockdelay;
    unsigned char  x_status;
    int            x_evelength;
    int            x_expectedlength;
    int            x_eventreadhead;
    int            x_seqsize;  /* as allocated */
    int            x_nevents;  /* as used */
    t_seqevent    *x_sequence;
    t_seqevent     x_seqini[SEQ_INISEQSIZE];
    int            x_temporeadhead;
    int            x_tempomapsize;  /* as allocated */
    int            x_ntempi;        /* as used */
    t_seqtempo    *x_tempomap;
    t_seqtempo     x_tempomapini[SEQ_INITEMPOMAPSIZE];
    t_clock       *x_clock;
    t_clock       *x_slaveclock;
    t_outlet      *x_bangout;
} t_seq;

static t_class *seq_class;

static void seq_doclear(t_seq *x, int dofree)
{
    if (dofree)
    {
	if (x->x_sequence != x->x_seqini)
	{
	    freebytes(x->x_sequence, x->x_seqsize * sizeof(*x->x_sequence));
	    x->x_sequence = x->x_seqini;
	    x->x_seqsize = SEQ_INISEQSIZE;
	}
	if (x->x_tempomap != x->x_tempomapini)
	{
	    freebytes(x->x_tempomap,
		      x->x_tempomapsize * sizeof(*x->x_tempomap));
	    x->x_tempomap = x->x_tempomapini;
	    x->x_tempomapsize = SEQ_INITEMPOMAPSIZE;
	}
    }
    x->x_nevents = 0;
    x->x_ntempi = 0;
}

static int seq_dogrowing(t_seq *x, int nevents, int ntempi)
{
    if (nevents > x->x_seqsize)
    {
	int nrequested = nevents;
#ifdef SEQ_DEBUG
	loudbug_post("growing for %d events...", nevents);
#endif
	x->x_sequence =
	    grow_nodata(&nrequested, &x->x_seqsize, x->x_sequence,
			SEQ_INISEQSIZE, x->x_seqini, sizeof(*x->x_sequence));
	if (nrequested < nevents)
	{
	    x->x_nevents = 0;
	    x->x_ntempi = 0;
	    return (0);
	}
    }
    if (ntempi > x->x_tempomapsize)
    {
	int nrequested = ntempi;
#ifdef SEQ_DEBUG
	loudbug_post("growing for %d tempi...", ntempi);
#endif
	x->x_tempomap =
	    grow_nodata(&nrequested, &x->x_tempomapsize, x->x_tempomap,
			SEQ_INITEMPOMAPSIZE, x->x_tempomapini,
			sizeof(*x->x_tempomap));
	if (nrequested < ntempi)
	{
	    x->x_ntempi = 0;
	    return (0);
	}
    }
    x->x_nevents = nevents;
    x->x_ntempi = ntempi;
    return (1);
}

static void seq_complete(t_seq *x)
{
    if (x->x_evelength < x->x_expectedlength)
    {
	/* CHECKED no warning if no data after status byte requiring data */
	if (x->x_evelength > 1)
	    post("seq: truncated midi message");  /* CHECKED */
	/* CHECKED nothing stored */
    }
    else
    {
	t_seqevent *ep = &x->x_sequence[x->x_nevents];
	ep->e_delta = clock_gettimesince(x->x_prevtime);
	x->x_prevtime = clock_getlogicaltime();
	if (x->x_evelength < 4)
	    ep->e_bytes[x->x_evelength] = SEQ_EOM;
	x->x_nevents++;
	if (x->x_nevents >= x->x_seqsize)
	{
	    int nexisting = x->x_seqsize;
	    /* store-ahead scheme, LATER consider using x_currevent */
	    int nrequested = x->x_nevents + 1;
#ifdef SEQ_DEBUG
	    loudbug_post("growing...");
#endif
	    x->x_sequence =
		grow_withdata(&nrequested, &nexisting,
			      &x->x_seqsize, x->x_sequence,
			      SEQ_INISEQSIZE, x->x_seqini,
			      sizeof(*x->x_sequence));
	    if (nrequested <= x->x_nevents)
		x->x_nevents = 0;
	}
    }
    x->x_evelength = 0;
}

static void seq_checkstatus(t_seq *x, unsigned char c)
{
    if (x->x_status && x->x_evelength > 1)  /* LATER rethink */
	seq_complete(x);
    if (c < 192)
	x->x_expectedlength = 3;
    else if (c < 224)
	x->x_expectedlength = 2;
    else if (c < 240)
	x->x_expectedlength = 3;
    else if (c < 248)
    {
	/* FIXME */
	x->x_expectedlength = -1;
    }
    else
    {
	x->x_sequence[x->x_nevents].e_bytes[0] = c;
	x->x_evelength = x->x_expectedlength = 1;
	seq_complete(x);
	return;
    }
    x->x_status = x->x_sequence[x->x_nevents].e_bytes[0] = c;
    x->x_evelength = 1;
}

static void seq_addbyte(t_seq *x, unsigned char c, int docomplete)
{
    x->x_sequence[x->x_nevents].e_bytes[x->x_evelength++] = c;
    if (x->x_evelength == x->x_expectedlength)
    {
	seq_complete(x);
	if (x->x_status)
	{
	    x->x_sequence[x->x_nevents].e_bytes[0] = x->x_status;
	    x->x_evelength = 1;
	}
    }
    else if (x->x_evelength == 4)
    {
	if (x->x_status != 240)
	    loudbug_bug("seq_addbyte");
	/* CHECKED sysex is broken into 4-byte packets marked with
	   the actual delta time of last byte received in a packet */
	seq_complete(x);
    }
    else if (docomplete) seq_complete(x);
}

static void seq_endofsysex(t_seq *x)
{
    seq_addbyte(x, 247, 1);
    x->x_status = 0;
}

static void seq_stoprecording(t_seq *x)
{
    if (x->x_status == 240)
    {
	post("seq: incomplete sysex");  /* CHECKED */
	seq_endofsysex(x);  /* CHECKED 247 added implicitly */
    }
    else if (x->x_status)
	seq_complete(x);
    /* CHECKED running status used in recording, but not across recordings */
    x->x_status = 0;
}

static void seq_stopplayback(t_seq *x)
{
    /* FIXME */
    /* CHECKED "seq: incomplete sysex" at playback stop, 247 added implicitly */
    /* CHECKME resetting controllers, etc. */
    /* CHECKED bang not sent if playback stopped early */
    clock_unset(x->x_clock);
    x->x_playhead = 0;
    x->x_nextscoretime = 0.;
}

static void seq_stopslavery(t_seq *x)
{
    /* FIXME */
    clock_unset(x->x_clock);
    clock_unset(x->x_slaveclock);
    x->x_playhead = 0;
    x->x_nextscoretime = 0.;
}

static void seq_startrecording(t_seq *x, int modechanged)
{
    x->x_prevtime = clock_getlogicaltime();
    x->x_status = 0;
    x->x_evelength = 0;
    x->x_expectedlength = -1;  /* LATER rethink */
}

/* CHECKED running status not used in playback */
static void seq_startplayback(t_seq *x, int modechanged)
{
    /* CHECKED bang not sent if sequence is empty */
    if (x->x_nevents)
    {
	if (modechanged)
	{
	    x->x_playhead = 0;
	    x->x_nextscoretime = x->x_sequence->e_delta;
	    /* playback data never sent within the scheduler event of
	       a start message (even for the first delta <= 0), LATER rethink */
	    x->x_clockdelay = x->x_sequence->e_delta * x->x_newtimescale;
	}
	else
	{  /* CHECKED timescale change */
	    if (x->x_prevtime > 0.)  /* running state */
		x->x_clockdelay -= clock_gettimesince(x->x_prevtime);
	    x->x_clockdelay *= x->x_newtimescale / x->x_timescale;
	}
	if (x->x_clockdelay < 0.)
	    x->x_clockdelay = 0.;
	x->x_timescale = x->x_newtimescale;
	clock_delay(x->x_clock, x->x_clockdelay);
	x->x_prevtime = clock_getlogicaltime();
    }
    else x->x_mode = SEQ_IDLEMODE;
}

static void seq_startslavery(t_seq *x, int modechanged)
{
    if (x->x_nevents)
    {
	x->x_playhead = 0;
	x->x_nextscoretime = 0.;
	x->x_prevtime = 0.;
	x->x_slaveprevtime = 0.;
    }
    else x->x_mode = SEQ_IDLEMODE;
}

static void seq_setmode(t_seq *x, int newmode)
{
    int changed = (x->x_mode != newmode);
    if (changed)
    {
	switch (x->x_mode)
	{
	case SEQ_IDLEMODE:
	    break;
	case SEQ_RECMODE:
	    seq_stoprecording(x);
	    break;
	case SEQ_PLAYMODE:
	    seq_stopplayback(x);
	    break;
	case SEQ_SLAVEMODE:
	    seq_stopslavery(x);
	    break;
	default:
	    loudbug_bug("seq_setmode (old)");
	    return;
	}
	x->x_mode = newmode;
    }
    switch (newmode)
    {
    case SEQ_IDLEMODE:
	break;
    case SEQ_RECMODE:
	seq_startrecording(x, changed);
	break;
    case SEQ_PLAYMODE:
	seq_startplayback(x, changed);
	break;
    case SEQ_SLAVEMODE:
	seq_startslavery(x, changed);
	break;
    default:
	loudbug_bug("seq_setmode (new)");
    }
}

static void seq_settimescale(t_seq *x, float newtimescale)
{
    if (newtimescale < 1e-20)
	x->x_newtimescale = 1e-20;
    else if (newtimescale > 1e20)
	x->x_newtimescale = 1e20;
    else
	x->x_newtimescale = newtimescale;
}

static void seq_clocktick(t_seq *x)
{
    if (x->x_mode == SEQ_PLAYMODE || x->x_mode == SEQ_SLAVEMODE)
    {
	t_seqevent *ep = &x->x_sequence[x->x_playhead++];
	unsigned char *bp = ep->e_bytes;
nextevent:
	outlet_float(((t_object *)x)->ob_outlet, *bp++);
	if (*bp != SEQ_EOM)
	{
	    outlet_float(((t_object *)x)->ob_outlet, *bp++);
	    if (*bp != SEQ_EOM)
	    {
		outlet_float(((t_object *)x)->ob_outlet, *bp++);
		if (*bp != SEQ_EOM)
		    outlet_float(((t_object *)x)->ob_outlet, *bp++);
	    }
	}
	if (x->x_mode != SEQ_PLAYMODE && x->x_mode != SEQ_SLAVEMODE)
	    return;  /* protecting against outlet -> 'stop' etc. */
	if (x->x_playhead < x->x_nevents)
	{
	    ep++;
	    x->x_nextscoretime += ep->e_delta;
	    if (ep->e_delta < SEQ_TICKEPSILON)
		/* continue output in the same scheduler event, LATER rethink */
	    {
		x->x_playhead++;
		bp = ep->e_bytes;
		goto nextevent;
	    }
	    else
	    {
		x->x_clockdelay = ep->e_delta * x->x_timescale;
		if (x->x_clockdelay < 0.)
		    x->x_clockdelay = 0.;
		clock_delay(x->x_clock, x->x_clockdelay);
		x->x_prevtime = clock_getlogicaltime();
	    }
	}
	else
	{
	    seq_setmode(x, SEQ_IDLEMODE);
	    /* CHECKED bang sent immediately _after_ last byte */
	    outlet_bang(x->x_bangout);  /* LATER think about reentrancy */
	}
    }
}

/* timeout handler ('tick' is late) */
static void seq_slaveclocktick(t_seq *x)
{
    if (x->x_mode == SEQ_SLAVEMODE) clock_unset(x->x_clock);
}

/* LATER dealing with self-invokation (outlet -> 'tick') */
static void seq_tick(t_seq *x)
{
    if (x->x_mode == SEQ_SLAVEMODE)
    {
	if (x->x_slaveprevtime > 0)
	{
	    double elapsed = clock_gettimesince(x->x_slaveprevtime);
	    if (elapsed < SEQ_MINTICKDELAY)
		return;
	    clock_delay(x->x_slaveclock, elapsed);
	    seq_settimescale(x, (float)(elapsed * (SEQ_TICKSPERSEC / 1000.)));
	    if (x->x_prevtime > 0.)
	    {
		x->x_clockdelay -= clock_gettimesince(x->x_prevtime);
		x->x_clockdelay *= x->x_newtimescale / x->x_timescale;
	    }
	    else x->x_clockdelay =
		x->x_sequence[x->x_playhead].e_delta * x->x_newtimescale;
	    if (x->x_clockdelay < 0.)
		x->x_clockdelay = 0.;
	    clock_delay(x->x_clock, x->x_clockdelay);
	    x->x_prevtime = clock_getlogicaltime();
	    x->x_slaveprevtime = x->x_prevtime;
	    x->x_timescale = x->x_newtimescale;
	}
	else
	{
	    x->x_clockdelay = 0.;  /* redundant */
	    x->x_prevtime = 0.;    /* redundant */
	    x->x_slaveprevtime = clock_getlogicaltime();
	    x->x_timescale = 1.;       /* redundant */
	}
    }
}

/* CHECKED bang does the same as 'start 1024', not 'start <current-timescale>'
   (also if already in SEQ_PLAYMODE) */
static void seq_bang(t_seq *x)
{
    seq_settimescale(x, 1.);
    seq_setmode(x, SEQ_PLAYMODE);  /* CHECKED 'bang' stops recording */
}

static void seq_float(t_seq *x, t_float f)
{
    if (x->x_mode == SEQ_RECMODE)
    {
	/* CHECKED noninteger and out of range silently truncated */
	unsigned char c = (unsigned char)f;
	if (c < 128)
	{
	    if (x->x_status) seq_addbyte(x, c, 0);
	}
	else if (c != 254)  /* CHECKED active sensing ignored */
	{
	    if (x->x_status == 240)
	    {
		if (c == 247) seq_endofsysex(x);
		else
		{
		    /* CHECKED rt bytes alike */
		    post("seq: unterminated sysex");  /* CHECKED */
		    seq_endofsysex(x);  /* CHECKED 247 added implicitly */
		    seq_checkstatus(x, c);
		}
	    }
	    else if (c != 247) seq_checkstatus(x, c);
	}
    }
}

static void seq_symbol(t_seq *x, t_symbol *s)
{
    loud_nomethod((t_pd *)x, &s_symbol);  /* CHECKED */
}

static void seq_list(t_seq *x, t_symbol *s, int ac, t_atom *av)
{
    if (ac && av->a_type == A_FLOAT) seq_float(x, av->a_w.w_float);
    /* CHECKED anything else/more silently ignored */
}

static void seq_record(t_seq *x)
{
    /* CHECKED 'record' stops playback, resets recording */
    seq_doclear(x, 0);
    seq_setmode(x, SEQ_RECMODE);
}

static void seq_append(t_seq *x)
{
    /* CHECKED 'append' stops playback */
    /* CHECKED if in SEQ_RECMODE, 'append' resets the timer */
    seq_setmode(x, SEQ_RECMODE);
}

static void seq_start(t_seq *x, t_floatarg f)
{
    if (f < 0)
    {
	/* FIXME */
	seq_setmode(x, SEQ_SLAVEMODE);
    }
    else
    {
	seq_settimescale(x, (f == 0 ? 1. : 1024. / f));
	seq_setmode(x, SEQ_PLAYMODE);  /* CHECKED 'start' stops recording */
    }
}

static void seq_stop(t_seq *x)
{
    seq_setmode(x, SEQ_IDLEMODE);
}

/* CHECKED first delta time is set permanently (it is stored in a file) */
static void seq_delay(t_seq *x, t_floatarg f)
{
    if (x->x_nevents)
	/* CHECKED signed/unsigned bug (not emulated) */
	x->x_sequence->e_delta = (f > SEQ_TICKEPSILON ? f : 0.);
}

/* CHECKED all delta times are set permanently (they are stored in a file) */
static void seq_hook(t_seq *x, t_floatarg f)
{
    int nevents;
    if (nevents = x->x_nevents)
    {
	t_seqevent *ev = x->x_sequence;
	if (f < 0)
	    f = 0;  /* CHECKED signed/unsigned bug (not emulated) */
	while (nevents--) ev++->e_delta *= f;
    }
}

static void seq_pause(t_seq *x)
{
    static int warned = 0;
    if (fittermax_get() && !warned)
    {
	fittermax_warning(*(t_pd *)x, "'pause' not supported in Max");
	warned = 1;
    }
    if (x->x_mode == SEQ_PLAYMODE &&
	x->x_prevtime > 0.)  /* running state */
    {
	x->x_clockdelay -= clock_gettimesince(x->x_prevtime);
	if (x->x_clockdelay < 0.)
	    x->x_clockdelay = 0.;
	clock_unset(x->x_clock);
	x->x_prevtime = 0.;
    }
}

static void seq_continue(t_seq *x)
{
    static int warned = 0;
    if (fittermax_get() && !warned)
    {
	fittermax_warning(*(t_pd *)x, "'continue' not supported in Max");
	warned = 1;
    }
    if (x->x_mode == SEQ_PLAYMODE &&
	x->x_prevtime <= 0.)  /* pause state */
    {
	if (x->x_clockdelay < 0.)
	    x->x_clockdelay = 0.;
	clock_delay(x->x_clock, x->x_clockdelay);
	x->x_prevtime = clock_getlogicaltime();
    }
}

static void seq_goto(t_seq *x, t_floatarg f1, t_floatarg f2)
{
    static int warned = 0;
    if (fittermax_get() && !warned)
    {
	fittermax_warning(*(t_pd *)x, "'goto' not supported in Max");
	warned = 1;
    }
    if (x->x_nevents)
    {
	t_seqevent *ev;
	int ndx, nevents = x->x_nevents;
	double ms = f1 * 1000. + f2, sum;
	if (ms < SEQ_TICKEPSILON)
	    ms = 0.;
	if (x->x_mode != SEQ_PLAYMODE)
	{
	    seq_settimescale(x, x->x_timescale);
	    seq_setmode(x, SEQ_PLAYMODE);
	    /* clock_delay() has been called in setmode, LATER avoid */
	    clock_unset(x->x_clock);
	    x->x_prevtime = 0.;
	}
	for (ndx = 0, ev = x->x_sequence, sum = SEQ_TICKEPSILON; ndx < nevents;
	     ndx++, ev++)
	{
	    if ((sum += ev->e_delta) >= ms)
	    {
		x->x_playhead = ndx;
		x->x_nextscoretime = sum;
		x->x_clockdelay = sum - SEQ_TICKEPSILON - ms;
		if (x->x_clockdelay < 0.)
		    x->x_clockdelay = 0.;
		if (x->x_prevtime > 0.)  /* running state */
		{
		    clock_delay(x->x_clock, x->x_clockdelay);
		    x->x_prevtime = clock_getlogicaltime();
		}
		break;
	    }
	}
    }
}

static void seq_scoretime(t_seq *x, t_symbol *s)
{
    static int warned = 0;
    if (fittermax_get() && !warned)
    {
	fittermax_warning(*(t_pd *)x, "'scoretime' not supported in Max");
	warned = 1;
    }
    if (s && s->s_thing &&
	x->x_mode == SEQ_PLAYMODE)  /* LATER other modes */
    {
	t_atom aout[2];
	double ms, clockdelay = x->x_clockdelay;
	t_float f1, f2;
	if (x->x_prevtime > 0.)  /* running state */
	    clockdelay -= clock_gettimesince(x->x_prevtime);
	ms = x->x_nextscoretime - clockdelay / x->x_timescale;
	f1 = ms / 1000.;
	f2 = ms - f1;
	SETFLOAT(&aout[0], f1);
	SETFLOAT(&aout[1], f2);
	pd_list(s->s_thing, &s_list, 2, aout);
    }
}

static void seq_cd(t_seq *x, t_symbol *s)
{
    static int warned = 0;
    if (fittermax_get() && !warned)
    {
	fittermax_warning(*(t_pd *)x, "'cd' not supported in Max");
	warned = 1;
    }
    hammerpanel_setopendir(x->x_filehandle, s);
}

static void seq_pwd(t_seq *x, t_symbol *s)
{
    t_symbol *dir;
    static int warned = 0;
    if (fittermax_get() && !warned)
    {
	fittermax_warning(*(t_pd *)x, "'pwd' not supported in Max");
	warned = 1;
    }
    if (s && s->s_thing && (dir = hammerpanel_getopendir(x->x_filehandle)))
	pd_symbol(s->s_thing, dir);
}

static int seq_eventcomparehook(const void *e1, const void *e2)
{
    return (((t_seqevent *)e1)->e_delta > ((t_seqevent *)e2)->e_delta ? 1 : -1);
}

static int seq_tempocomparehook(const void *t1, const void *t2)
{
    return (((t_seqtempo *)t1)->t_scoretime >
	    ((t_seqtempo *)t2)->t_scoretime ? 1 : -1);
}

static int seq_mrhook(t_mifiread *mr, void *hookdata, int evtype)
{
    t_seq *x = (t_seq *)hookdata;
    double scoretime = mifiread_getscoretime(mr);
    if (evtype >= 0xf0)
    {
    }
    else if (evtype >= 0x80)
    {
	if (x->x_eventreadhead < x->x_nevents)
	{
	    t_seqevent *sev = &x->x_sequence[x->x_eventreadhead++];
	    int status = mifiread_getstatus(mr);
	    sev->e_delta = scoretime;
	    sev->e_bytes[0] = status | mifiread_getchannel(mr);
	    sev->e_bytes[1] = mifiread_getdata1(mr);
	    if (MIFI_ONEDATABYTE(status))
		sev->e_bytes[2] = SEQ_EOM;
	    else
	    {
		sev->e_bytes[2] = mifiread_getdata2(mr);
		sev->e_bytes[3] = SEQ_EOM;
	    }
	}
	else if (x->x_eventreadhead == x->x_nevents)
	{
	    loudbug_bug("seq_mrhook 1");
	    x->x_eventreadhead++;
	}
    }
    else if (evtype == MIFIMETA_TEMPO)
    {
	if (x->x_temporeadhead < x->x_ntempi)
	{
	    t_seqtempo *stm = &x->x_tempomap[x->x_temporeadhead++];
	    stm->t_scoretime = scoretime;
	    stm->t_sr = mifiread_gettempo(mr);
#ifdef SEQ_DEBUG
	    loudbug_post("tempo %g at %g", stm->t_sr, scoretime);
#endif
	}
	else if (x->x_temporeadhead == x->x_ntempi)
	{
	    loudbug_bug("seq_mrhook 2");
	    x->x_temporeadhead++;
	}
    }
    return (1);
}

/* apply tempo and fold */
static void seq_foldtime(t_seq *x, double deftempo)
{
    t_seqevent *sev;
    t_seqtempo *stm = x->x_tempomap;
    double coef = 1000. / deftempo;
    int ex, tx = 0;
    double prevscoretime = 0.;
    while (tx < x->x_ntempi && stm->t_scoretime < SEQ_TICKEPSILON)
	tx++, coef = 1000. / stm++->t_sr;
    for (ex = 0, sev = x->x_sequence; ex < x->x_nevents; ex++, sev++)
    {
	double clockdelta = 0.;
	while (tx < x->x_ntempi && stm->t_scoretime <= sev->e_delta)
	{
	    clockdelta += (stm->t_scoretime - prevscoretime) * coef;
	    prevscoretime = stm->t_scoretime;
	    tx++;
	    coef = 1000. / stm++->t_sr;
	}
	clockdelta += (sev->e_delta - prevscoretime) * coef;
	prevscoretime = sev->e_delta;
	sev->e_delta = clockdelta;
    }
}

static int seq_mfread(t_seq *x, char *path)
{
    int result = 0;
    t_mifiread *mr = mifiread_new((t_pd *)x);
    if (!mifiread_open(mr, path, "", 0))
	goto mfreadfailed;
#ifdef SEQ_DEBUG
    loudbug_startpost("midifile (format %d): %d tracks, %d ticks",
		      mifiread_getformat(mr), mifiread_gethdtracks(mr),
		      mifiread_getbeatticks(mr));
    if (mifiread_getnframes(mr))
	loudbug_post(" (%d smpte frames)", mifiread_getnframes(mr));
    else
	loudbug_post(" per beat");
#endif
    if (!seq_dogrowing(x, mifiread_getnevents(mr), mifiread_getntempi(mr)))
	goto mfreadfailed;
    x->x_eventreadhead = 0;
    x->x_temporeadhead = 0;
    if (mifiread_doit(mr, seq_mrhook, x) != MIFIREAD_EOF)
	goto mfreadfailed;
    if (x->x_eventreadhead < x->x_nevents)
    {
	loudbug_bug("seq_mfread 1");
	loudbug_post("declared %d events, got %d",
		     x->x_nevents, x->x_eventreadhead);
	x->x_nevents = x->x_eventreadhead;
    }
    if (x->x_nevents)
	qsort(x->x_sequence, x->x_nevents, sizeof(*x->x_sequence),
	      seq_eventcomparehook);
    if (x->x_temporeadhead < x->x_ntempi)
    {
	loudbug_bug("seq_mfread 2");
	loudbug_post("declared %d tempi, got %d",
		     x->x_ntempi, x->x_temporeadhead);
	x->x_ntempi = x->x_temporeadhead;
    }
    if (x->x_ntempi)
	qsort(x->x_tempomap, x->x_ntempi, sizeof(*x->x_tempomap),
	      seq_tempocomparehook);
    seq_foldtime(x, mifiread_getdeftempo(mr));
#ifdef SEQ_DEBUG
    loudbug_post("seq: got %d events from midi file", x->x_nevents);
#endif
    result = 1;
mfreadfailed:
    mifiread_free(mr);
    return (result);
}

static int seq_mfwrite(t_seq *x, char *path)
{
    int result = 0;
    t_seqevent *sev = x->x_sequence;
    int nevents = x->x_nevents;
    t_mifiwrite *mw = mifiwrite_new((t_pd *)x);
    if (!mifiwrite_open(mw, path, "", 1, 1))
	goto mfwritefailed;
    if (!mifiwrite_opentrack(mw, "seq-track", 1))
	goto mfwritefailed;
    while (nevents--)
    {
	unsigned char *bp = sev->e_bytes;
	unsigned status = *bp & 0xf0;
	if (status > 127 && status < 240)
	{
	    if (!mifiwrite_channelevent(mw, sev->e_delta, status, *bp & 0x0f,
					bp[1], bp[2]))  /* SEQ_EOM ignored */
	    {
		loud_error((t_pd *)x, "cannot write channel event %d", status);
		goto mfwritefailed;
	    }
	}
	/* FIXME system, sysex (first, and continuation) */
	sev++;
    }
    if (!mifiwrite_closetrack(mw, 0., 1))
	goto mfwritefailed;
    mifiwrite_close(mw);
    result = 1;
mfwritefailed:
    if (!result)
	loud_errand((t_pd *)x,
		    "while saving sequence into midi file \"%s\"", path);
    mifiwrite_free(mw);
    return (result);
}

/* FIXME */
/* CHECKED absolute timestamps, semi-terminated, verified */
static int seq_frombinbuf(t_seq *x, t_binbuf *bb)
{
    int nevents = 0;
    int ac = binbuf_getnatom(bb);
    t_atom *av = binbuf_getvec(bb);
    while (ac--)
	if (av++->a_type == A_SEMI)  /* FIXME parsing */
	    nevents++;
    if (nevents)
    {
	t_seqevent *ep;
	float prevtime = 0;
	int i = -1;
	if (!seq_dogrowing(x, nevents, 0))
	    return (0);
	nevents = 0;
	ac = binbuf_getnatom(bb);
	av = binbuf_getvec(bb);
	ep = x->x_sequence;
	while (ac--)
	{
	    if (av->a_type == A_FLOAT)
	    {
		if (i < 0)
		{
		    ep->e_delta = av->a_w.w_float - prevtime;
		    prevtime = av->a_w.w_float;
		    i = 0;
		}
		else if (i < 4)
		    ep->e_bytes[i++] = av->a_w.w_float;
		/* CHECKME else */
	    }
	    else if (av->a_type == A_SEMI && i > 0)
	    {
		if (i < 4)
		    ep->e_bytes[i] = SEQ_EOM;
		nevents++;
		ep++;
		i = -1;
	    }
	    /* CHECKME else */
	    av++;
	}
	x->x_nevents = nevents;
    }
    return (nevents);
}

static void seq_tobinbuf(t_seq *x, t_binbuf *bb)
{
    int nevents = x->x_nevents;
    t_seqevent *ep = x->x_sequence;
    t_atom at[5];
    float timestamp = 0;
    while (nevents--)
    {
	unsigned char *bp = ep->e_bytes;
	int i;
	t_atom *ap = at;
	timestamp += ep->e_delta;
	SETFLOAT(ap, timestamp);  /* CHECKED same for sysex continuation */
	ap++;
	SETFLOAT(ap, *bp);
	for (i = 0, ap++, bp++; i < 3 && *bp != SEQ_EOM; i++, ap++, bp++)
	    SETFLOAT(ap, *bp);
	binbuf_add(bb, i + 2, at);
	binbuf_addsemi(bb);
	ep++;
    }
}

static void seq_textread(t_seq *x, char *path)
{
    t_binbuf *bb;
    bb = binbuf_new();
    if (binbuf_read(bb, path, "", 0))
    {
	/* CHECKED no complaint, open dialog presented */
	hammerpanel_open(x->x_filehandle, 0);  /* LATER rethink */
    }
    else
    {
	int nlines = seq_frombinbuf(x, bb);
	if (nlines < 0)
	    /* CHECKED "bad MIDI file (truncated)" alert, even if a text file */
	    loud_error((t_pd *)x, "bad text file (truncated)");
	else if (nlines == 0)
	{
	    /* CHECKED no complaint, sequence erased, LATER rethink */
	}
    }
    binbuf_free(bb);
}

static void seq_textwrite(t_seq *x, char *path)
{
    t_binbuf *bb;
    bb = binbuf_new();
    seq_tobinbuf(x, bb);
    /* CHECKED empty sequence stored as an empty file */
    if (binbuf_write(bb, path, "", 0))
    {
	/* CHECKME complaint and FIXME */
	loud_error((t_pd *)x, "error writing text file");
    }
    binbuf_free(bb);
}

static void seq_doread(t_seq *x, t_symbol *fn, int creation)
{
    char buf[MAXPDSTRING];
    /* FIXME use open_via_path() */
    if (x->x_canvas)
	canvas_makefilename(x->x_canvas, fn->s_name, buf, MAXPDSTRING);
    else
    {
    	strncpy(buf, fn->s_name, MAXPDSTRING);
    	buf[MAXPDSTRING-1] = 0;
    }
    if (creation)
    {
	/* loading during object creation -- CHECKED no warning if a file
	   specified with an arg does not exist, LATER rethink */
	FILE *fp;
	char path[MAXPDSTRING];
	sys_bashfilename(buf, path);
	if (!(fp = fopen(path, "r")))
	    return;
	fclose(fp);
    }
    /* CHECKED all cases: arg or not, message and creation */
    post("seq: reading %s", fn->s_name);
    if (!seq_mfread(x, buf))
	seq_textread(x, buf);
}

static void seq_dowrite(t_seq *x, t_symbol *fn)
{
    char buf[MAXPDSTRING], *dotp;
    if (x->x_canvas)
	canvas_makefilename(x->x_canvas, fn->s_name, buf, MAXPDSTRING);
    else
    {
    	strncpy(buf, fn->s_name, MAXPDSTRING);
    	buf[MAXPDSTRING-1] = 0;
    }
    post("seq: writing %s", fn->s_name);  /* CHECKED arg or not */
    /* save as text for any extension other then ".mid" */
    if ((dotp = strrchr(fn->s_name, '.')) && strcmp(dotp + 1, "mid"))
	seq_textwrite(x, buf);
    else  /* save as mf for ".mid" (FIXME ignore case?) or no extension at all,
	     LATER rethink */
	seq_mfwrite(x, buf);
}

static void seq_readhook(t_pd *z, t_symbol *fn, int ac, t_atom *av)
{
    seq_doread((t_seq *)z, fn, 0);
}

static void seq_writehook(t_pd *z, t_symbol *fn, int ac, t_atom *av)
{
    seq_dowrite((t_seq *)z, fn);
}

static void seq_read(t_seq *x, t_symbol *s)
{
    if (s && s != &s_)
	seq_doread(x, s, 0);
    else  /* CHECKED no default file name */
	/* start in a dir last read from, if any, otherwise in a canvas dir */
	hammerpanel_open(x->x_filehandle, 0);
}

static void seq_write(t_seq *x, t_symbol *s)
{
    if (s && s != &s_)
	seq_dowrite(x, s);
    else  /* CHECKED creation arg is a default file name */
	hammerpanel_save(x->x_filehandle,
			 /* always start in canvas dir */
			 canvas_getdir(x->x_canvas), x->x_defname);
}

static void seq_eventstring(t_seq *x, char *buf, t_seqevent *ep)
{
    unsigned char *bp = ep->e_bytes;
    int i;
    if (*bp < 128 || *bp == 247)
	sprintf(buf, "(%g)->", ep->e_delta);
    else
	sprintf(buf, "(%g)", ep->e_delta);
    buf += strlen(buf);
    sprintf(buf, " %g", (float)*bp);
    for (i = 0, bp++; i < 3 && *bp != SEQ_EOM; i++, bp++)
    {
	buf += strlen(buf);
	sprintf(buf, " %g", (float)*bp);
    }
}

static void seq_print(t_seq *x)
{
    int nevents = x->x_nevents;
    startpost("midiseq:");  /* CHECKED */
    if (nevents)
    {
	t_seqevent *ep = x->x_sequence;
	char buf[MAXPDSTRING+2];
	int truncated;
	if (nevents > 16)
	    nevents = 16, truncated = 1;
	else
	    truncated = 0;
	endpost();
	while (nevents--)
	{
	    /* CHECKED bytes are space-separated, no semi */
	    seq_eventstring(x, buf, ep);
	    post(buf);
	    ep++;
	}
	if (truncated) post("...");  /* CHECKED */
    }
    else post(" no sequence");  /* CHECKED */
}

static void seq_properties(t_gobj *z, t_glist *glist)
{
    t_seq *x = (t_seq *)z;
    t_seqevent *ep = x->x_sequence;
    int nevents = x->x_nevents;
    char buf[MAXPDSTRING+2];
    sprintf(buf, "seq: %s", (x->x_defname && x->x_defname != &s_ ?
			     x->x_defname->s_name : "<anonymous>"));
    hammereditor_open(x->x_filehandle, buf);
    while (nevents--)
    {
	seq_eventstring(x, buf, ep);
	strcat(buf, "\n");
	hammereditor_append(x->x_filehandle, buf);
	ep++;
    }
}

static void seq_free(t_seq *x)
{
    if (x->x_clock) clock_free(x->x_clock);
    if (x->x_slaveclock) clock_free(x->x_slaveclock);
    if (x->x_filehandle) hammerfile_free(x->x_filehandle);
    if (x->x_sequence != x->x_seqini)
	freebytes(x->x_sequence, x->x_seqsize * sizeof(*x->x_sequence));
    if (x->x_tempomap != x->x_tempomapini)
	freebytes(x->x_tempomap, x->x_tempomapsize * sizeof(*x->x_tempomap));
}

static void *seq_new(t_symbol *s)
{
    t_seq *x = (t_seq *)pd_new(seq_class);
    static int warned = 0;
    if (fittermax_get() && !warned)
    {
	loud_warning((t_pd *)x, 0, "seq is not ready yet");
	warned = 1;
    }
    x->x_canvas = canvas_getcurrent();
    x->x_filehandle = hammerfile_new((t_pd *)x, 0,
				     seq_readhook, seq_writehook, 0);
    x->x_timescale = 1.;
    x->x_newtimescale = 1.;
    x->x_prevtime = 0.;
    x->x_slaveprevtime = 0.;
    x->x_seqsize = SEQ_INISEQSIZE;
    x->x_nevents = 0;
    x->x_sequence = x->x_seqini;
    x->x_tempomapsize = SEQ_INITEMPOMAPSIZE;
    x->x_ntempi = 0;
    x->x_tempomap = x->x_tempomapini;
    outlet_new((t_object *)x, &s_anything);
    x->x_bangout = outlet_new((t_object *)x, &s_bang);
    if (s && s != &s_)
    {
	x->x_defname = s;  /* CHECKME if 'read' changes this */
	seq_doread(x, s, 1);
    }
    else x->x_defname = &s_;
    x->x_clock = clock_new(x, (t_method)seq_clocktick);
    x->x_slaveclock = clock_new(x, (t_method)seq_slaveclocktick);
    return (x);
}

void seq_setup(void)
{
    seq_class = class_new(gensym("seq"),
			  (t_newmethod)seq_new,
			  (t_method)seq_free,
			  sizeof(t_seq), 0,
			  A_DEFSYM, 0);
    class_addbang(seq_class, seq_bang);
    class_addfloat(seq_class, seq_float);
    /* CHECKED symbol rejected */
    class_addsymbol(seq_class, seq_symbol);
    /* CHECKED 1st atom of a list accepted if a float, ignored if a symbol */
    class_addlist(seq_class, seq_list);
    class_addmethod(seq_class, (t_method)seq_record,
		    gensym("record"), 0);
    class_addmethod(seq_class, (t_method)seq_append,
		    gensym("append"), 0);
    class_addmethod(seq_class, (t_method)seq_start,
		    gensym("start"), A_DEFFLOAT, 0);
    class_addmethod(seq_class, (t_method)seq_stop,
		    gensym("stop"), 0);
    class_addmethod(seq_class, (t_method)seq_tick,
		    gensym("tick"), 0);
    class_addmethod(seq_class, (t_method)seq_delay,
		    gensym("delay"), A_FLOAT, 0);  /* CHECKED arg obligatory */
    class_addmethod(seq_class, (t_method)seq_hook,
		    gensym("hook"), A_FLOAT, 0);   /* CHECKED arg obligatory */
    class_addmethod(seq_class, (t_method)seq_read,
		    gensym("read"), A_DEFSYM, 0);
    class_addmethod(seq_class, (t_method)seq_write,
		    gensym("write"), A_DEFSYM, 0);
    class_addmethod(seq_class, (t_method)seq_print,
		    gensym("print"), 0);

    class_addmethod(seq_class, (t_method)seq_pause,
		    gensym("pause"), 0);
    class_addmethod(seq_class, (t_method)seq_continue,
		    gensym("continue"), 0);
    class_addmethod(seq_class, (t_method)seq_goto,
		    gensym("goto"), A_DEFFLOAT, A_DEFFLOAT, 0);
    class_addmethod(seq_class, (t_method)seq_scoretime,
		    gensym("scoretime"), A_SYMBOL, 0);
    class_addmethod(seq_class, (t_method)seq_cd,
		    gensym("cd"), A_DEFSYM, 0);
    class_addmethod(seq_class, (t_method)seq_pwd,
		    gensym("pwd"), A_SYMBOL, 0);

    forky_setpropertiesfn(seq_class, seq_properties);
    hammerfile_setup(seq_class, 0);
    fitter_setup(seq_class, 0);
}