-
Notifications
You must be signed in to change notification settings - Fork 4
/
pmg.c
2254 lines (2038 loc) · 88.1 KB
/
pmg.c
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
/* PMG, a VOS clone for linux.
Copyright (C) 2006 rainycat <[email protected]>, loveruby <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
#include <glade/glade.h>
#include <asoundlib.h>
#include <popt.h>
#include <openssl/evp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#ifndef SHA_DIGEST_LENGTH
#define SHA_DIGEST_LENGTH 20
#endif
#define IDX_NONE ((unsigned) -1)
#define NKEY 7
/* A note to be played by the user */
typedef struct usernote_s {
double rt_start; /* Time of the Note-on event in seconds from the start of the song */
double tt_start; /* Time of the Note-on event in MIDI quarter-notes from the start of the song */
double rt_stop, tt_stop; /* For long notes, it is {rt,tt}_end; for short notes, it is {rt,tt}_start.
Used when displaying notes and scoring. */
double rt_end, tt_end; /* Time of the corresponding Note-off event. Used when playing short notes. */
unsigned char cmd, note_num, vol; /* Corresponding MIDI command */
unsigned key, color; /* Key is 0-6 for do,re,mi,fa,so,la,ti; Color is 0-15 */
gboolean is_long;
unsigned prev_idx, next_idx; /* The array index of the previous/next note on the same key;
IDX_NONE if there is none */
unsigned prev_idx_long, next_idx_long;
unsigned count, count_long; /* The number of (long) notes on this key, including this one */
} UserNote;
typedef struct inputevent_s {
double rt;
gboolean is_keypress;
unsigned key;
} InputEvent;
typedef struct tempochange_s {
double rt0, tt0; /* rt and tt at the time when the tempo change occurs */
double qn_time; /* The duration of a MIDI quarter-note after that */
} TempoChange;
typedef struct midievent_s {
double tt;
unsigned char cmd, a, b; /* cmd is the status byte */
} MidiEvent;
/* Stores the MIDI initialization events in an MIDI track */
typedef struct miditrack_s {
unsigned nevent;
MidiEvent *events;
} MidiTrack;
/* Both BGM notes and notes played by the user */
typedef struct note_s {
double tt_start, tt_end;
double rt_start, rt_end;
unsigned cmd, note_num, vol;
gboolean is_user, is_long;
} Note;
typedef struct notearray_s {
unsigned num_note;
Note *notes;
} NoteArray;
/* An iterator in the TempoChange array, used to accelerate the converstion between rt's and tt's. */
typedef struct tempoit_s {
unsigned idx; /* The index of the current TempoChange being used */
} TempoIt;
/* A scheduled event */
typedef enum schedeventtype_e {
SchedEventMidi, SchedEventNoteOn, SchedEventNoteOff, SchedEventUserNoteOff, SchedEventDemo,
SchedEventRefreshScore, SchedEventAutoOn, SchedEventAutoOff, SchedEventRefreshScreen
} SchedEventType;
typedef struct schedevent_s {
double rt;
SchedEventType type;
unsigned src, idx; /* src is the track number or the note array number;
idx is the index within the track or note array */
} SchedEvent;
typedef struct vossong_s {
unsigned ntempo;
TempoChange *tempos; /* The first TempoChange is the default one with qn_time=0.5 (120BPM) */
double midi_unit_tt; /* The number of quarter-notes in a MIDI delta-time unit */
unsigned ntrack;
MidiTrack *tracks;
unsigned num_note_array; /* Excluding the last one containing user notes */
NoteArray *note_arrays;
unsigned num_user_note;
UserNote *user_notes;
gboolean has_min_max_rt;
double min_rt, max_rt; /* For now, they only count the notes, not the tracks */
unsigned first_un_idxs[NKEY]; /* The first user note on each key */
unsigned first_un_idxs_long[NKEY]; /* The first long user note */
unsigned char hash[SHA_DIGEST_LENGTH];
} VosSong;
typedef struct comparerentry_s {
unsigned last_idx; /* The index of the last user note used for matching */
double score; /* Total score so far */
} ComparerEntry;
typedef struct comparer_s {
double score0; /* Score when none of the user notes within range are used for matching */
unsigned count0;
unsigned nent;
ComparerEntry *ents; /* Should be ordered so that both last_idx and score are strictly increasing */
} Comparer;
/* A marker is a circle showing the accuracy after a keypress */
typedef struct marker_s {
double rt;
double dt; /* dt = un->rt_start - cur_rt; dt > 0: too early; only the sign is used */
double score;
} Marker;
typedef struct keystate_s {
gboolean key_down; /* Whether the key on the keyboard is down or not */
double key_down_rt;
unsigned un_idx; /* For the actual note to play.
Only meaningful if key_down is true; IDX_NONE if the key_down had been ignored */
Comparer cmp_press, cmp_release; /* One comparer for keypress events, another for key release events */
double long_score, total_long_score;
double long_rt; /* The score before long_rt has been counted into long_score and total_long_score. */
gboolean long_okay, long_scored; /* The status at long_rt if key_down is true */
GQueue *markers;
} KeyState;
typedef enum vosgamemode_e { VosGameModeNormal, VosGameModeAuto, VosGameModePlayDemo } VosGameMode;
typedef struct gamescore_s {
double score, total_score;
} GameScore;
typedef struct gameoptions_s {
VosGameMode mode;
const char *vos_fname;
int allow_cheating;
int adaptive_time_factor;
double target_ratio; /* For use with adaptive_time_factor */
int half_volume_for_bgm;
int fast_mode; /* In fast mode, we mainly just calculate the scores */
int enable_ui, enable_sound;
double fps;
double igamma;
double init_speed; /* vy per second of actual time */
double seek;
gboolean use_seek;
double score_dt0; /* The amount of error, above which the lowest score is given; this is in actual time */
/* A key can be held in the duration of a user note and plus allowed_hold_time on both sides.
If it is held any longer, a penalty on long_score will be applied. */
double allowed_hold_time; /* in actual time */
int adjustable_mode; /* In adjustable mode, the time factor and the speed can be adjusted */
double tempo_factor, init_time_factor;
double pev_time_unit;
const char *pev_in_fname;
const char *pev_out_fname;
const char *midi_port_spec;
double score_refresh_period; /* In actual time */
unsigned recent_scores_nperiod;
} GameOptions;
/* Options specified on the command line and shared by all VosGame instances */
static GameOptions defopts = {
.mode = VosGameModeNormal,
.vos_fname = NULL,
.allow_cheating = FALSE,
.adaptive_time_factor = FALSE,
.target_ratio = 0.9,
.half_volume_for_bgm = FALSE,
.fast_mode = FALSE,
.enable_ui = TRUE, .enable_sound = TRUE,
.fps = 150.0, .igamma = 0.55,
.init_speed = 1.4, .seek = 0, .use_seek = FALSE,
.score_dt0 = 0.48, .allowed_hold_time = 0.20,
.adjustable_mode = FALSE, .tempo_factor = 1.0, .init_time_factor = 1.0,
.pev_time_unit = 0.001,
.pev_in_fname = NULL, .pev_out_fname = NULL, .midi_port_spec = "128:0",
.score_refresh_period = 0.25, .recent_scores_nperiod = 8
};
typedef struct vosgame_s {
GameOptions *opts;
GtkWidget *main_area;
GtkLabel *state_label, *time_label, *score_label, *rate_label, *time_factor_label;
VosSong *song;
const char *user_name;
snd_seq_t *seq;
int seq_client_id, seq_port_id;
int dest_client_id, dest_port_id;
guint event_timeout_id;
guint conn_key_press, conn_key_release, conn_expose, conn_delete;
gboolean is_paused, is_resync;
double start_rt; /* The rt at start_time */
GTimeVal start_time, pause_time;
double time_factor, speed_rt, tscale_rt; /* speed_rt does not change automatically during game */
double frame_time; /* 1.0 / fps */
double volume;
GArray *input_events_arr; /* Used when recording demos */
const InputEvent *in_evs; /* Used when playing demos */
unsigned in_nev;
double last_status_upd_rt;
GameScore *recent_scores;
GTree *sched; /* event scheduler */
GdkColor *colors;
TempoIt it;
unsigned cur_un_idxs[NKEY]; /* Used for speeding up the search in the user notes array;
Always points to a note on that key, unless there is no note on this key,
in which case the value is IDX_NONE */
unsigned cur_un_idxs_long[NKEY];
KeyState keys[NKEY];
} VosGame;
/* Information in the header of input events */
#define PEV_MAGIC 0xb10cde81U
/* Header types */
#define PEV_HEADER_END 0
#define PEV_HASH_SHA1 1
#define PEV_TEMPO_FACTOR 2 /* Skipped if this is 1 */
#define PEV_SPEED 3 /* NOTE: this might be bogus if speed can be changed in-game */
#define PEV_TIME_UNIT 4
#define PEV_DATE 5
#define PEV_USER_NAME 6
#define PEV_TIME_OFFSET 7
#define PEV_TIME_FACTOR 8
#define PEV_SEEK 9
#define PEV_CHEAT 10
#define PEV_ADAPTIVE_TIME_FACTOR 11
/* Event types */
#define PEV_EV_END 0
#define PEV_EV_PRESS 1
#define PEV_EV_RELEASE 8 /* The next event type should be 15 */
static const struct poptOption popt_table[] = {
{ "port", 'p', POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT, &defopts.midi_port_spec, 0,
"Set the MIDI sequencer port", "CLIENT:PORT" },
{ "speed", 's', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT, &defopts.init_speed, 0,
"Set the speed of the notes falling down", "SPEED" },
{ "seek", 'k', POPT_ARG_DOUBLE, &defopts.seek, 'k', "Seek to some time at startup", "RT" },
{ "cheat", 'c', POPT_ARG_NONE, &defopts.allow_cheating, 0, "Allow in-game changes to the time factor", NULL },
{ "dt0", 'd', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT, &defopts.score_dt0, 0,
"Set the maximum allowed error in seconds", "TIME" },
{ "tempo", 'T', POPT_ARG_DOUBLE, &defopts.tempo_factor, 0, "Multiply the tempo by FACTOR", "FACTOR" },
{ "time-factor", 't', POPT_ARG_DOUBLE, &defopts.init_time_factor, 0, "Make time pass FACTOR times as quickly", "FACTOR" },
{ "adaptive-tf", 'a', POPT_ARG_DOUBLE, &defopts.target_ratio, 'a', "Adaptively adjust the time factor", "TARGET_RATIO" },
{ "record", 'o', POPT_ARG_STRING, &defopts.pev_out_fname, 0, "Record into demo file FNAME.pev", "FNAME.pev" },
{ "playdemo", 'i', POPT_ARG_STRING, &defopts.pev_in_fname, 'i', "Play demo file FNAME.pev", "FNAME.pev" },
{ "fast", 'f', POPT_ARG_NONE, &defopts.fast_mode, 0, "Fast mode", NULL },
{ "sound-only", 'S', POPT_ARG_NONE, NULL, 'S', "Play sound only, no graphics", NULL },
{ "auto", 'A', POPT_ARG_NONE, NULL, 'A', "Automatic mode", NULL },
{ "verbose", 'v', POPT_ARG_NONE, NULL, 'v', "Verbose", NULL },
POPT_AUTOHELP
POPT_TABLEEND };
#define GET_WIDGET(gx, obj, name, type) \
do { \
(obj) = type(glade_xml_get_widget((gx), (name))); \
g_assert((obj) != NULL); \
} while (0)
#define COLOR_BLACK 0
#define COLOR_WHITE 1
#define COLOR_KEYPRESS_START 2
#define COLOR_KEYPRESS 10
#define COLOR_NOTE_START 11
#define COLOR_NOTE_END 42
#define COLOR_MARKER_START 43
#define COLOR_MARKER_BEST 43
#define COLOR_MARKER_WORST 59
#define COLOR_MARKER_END 74
#define COLOR_RATE_START 75
#define COLOR_RATE_END 106
#define NCOLOR 107
static const char *glade_fname = "pmg.glade";
static const double vx_min = -0.1, vx_max = 7.1, vx_mid = 3.5, vy_min = -1.0, vy_max = 0.2;
static const double note_vw = 0.1; /* width of long note borders */
static const double note_vt = 0.01;
/* Whether the length of short notes are automatically lengthened to the actual note length */
static const gboolean short_note_auto_len = TRUE;
gboolean verbose = FALSE;
/* Returns t-t0 in seconds */
static double timeval_diff(GTimeVal *t0, GTimeVal *t)
{
return (t->tv_sec - t0->tv_sec) + 1e-6 * (t->tv_usec - t0->tv_usec);
}
#define BUF_SIZE 4096
static void hash_file(FILE *file, unsigned char *hash, unsigned hash_len)
{
static char buf[BUF_SIZE];
unsigned cur_len;
EVP_MD_CTX mdctx;
const EVP_MD *md = EVP_sha1();
int result;
g_assert(EVP_MD_size(md) == (int) hash_len);
result = EVP_DigestInit(&mdctx, md); g_assert(result == 1);
result = fseek(file, 0, SEEK_SET); g_assert(result == 0);
while (1) {
result = fread(buf, 1, BUF_SIZE, file); g_assert(result >= 0); cur_len = result;
if (cur_len == 0) break;
result = EVP_DigestUpdate(&mdctx, buf, cur_len); g_assert(result == 1);
}
result = EVP_DigestFinal(&mdctx, hash, NULL); g_assert(result == 1);
}
#undef BUF_SIZE
static void tempoit_init(VosSong *song, TempoIt *it)
{
it->idx = 0;
}
static double tempoit_tt_to_rt(VosSong *song, TempoIt *it, double tt)
{
const TempoChange *tc;
while (it->idx > 0 && tt < song->tempos[it->idx].tt0) it->idx--;
while (it->idx + 1 < song->ntempo && tt >= song->tempos[it->idx+1].tt0) it->idx++;
tc = &song->tempos[it->idx];
return tc->rt0 + (tt - tc->tt0) * tc->qn_time;
}
static double tempoit_rt_to_tt(VosSong *song, TempoIt *it, double rt)
{
const TempoChange *tc;
while (it->idx > 0 && rt < song->tempos[it->idx].rt0) it->idx--;
while (it->idx + 1 < song->ntempo && rt >= song->tempos[it->idx+1].rt0) it->idx++;
tc = &song->tempos[it->idx];
return tc->tt0 + (rt - tc->rt0) / tc->qn_time;
}
static gint event_compare(gconstpointer pa, gconstpointer pb, gpointer user_data)
{
const SchedEvent *a = (SchedEvent *) pa, *b = (SchedEvent *) pb;
if (a->rt != b->rt) return (a->rt > b->rt) - (a->rt < b->rt);
else return (a > b) - (a < b);
}
static GTree *new_event_scheduler(void)
{
return g_tree_new_full(event_compare, NULL, NULL, g_free);
}
static void free_event_scheduler(GTree *sched)
{
g_tree_destroy(sched);
}
static void sched_event(GTree *sched, double rt, SchedEventType type, unsigned src, unsigned idx)
{
SchedEvent *ev = g_new0(SchedEvent, 1);
ev->rt = rt; ev->type = type; ev->src = src; ev->idx = idx;
g_tree_insert(sched, ev, ev);
}
static gboolean get_first_event_each(gpointer key, gpointer value, gpointer data)
{
SchedEvent **pev = (SchedEvent **) data;
*pev = (SchedEvent *) key;
return TRUE; /* stop traversal */
}
static SchedEvent *get_first_event(GTree *sched)
{
SchedEvent *ev = NULL;
g_tree_foreach(sched, get_first_event_each, &ev);
return ev;
}
static void remove_event(GTree *sched, SchedEvent *ev)
{
g_tree_remove(sched, ev);
}
static void free_vos_song(VosSong *song)
{
unsigned i;
g_free(song->tempos);
for (i = 0; i < song->ntrack; i++) g_free(song->tracks[i].events);
g_free(song->tracks);
for (i = 0; i < song->num_note_array; i++) g_free(song->note_arrays[i].notes);
g_free(song->note_arrays);
g_free(song->user_notes);
g_free(song);
}
static unsigned midi_read_u8(FILE *file)
{
int result = getc(file);
g_assert(result != EOF);
return (unsigned) result;
}
static unsigned midi_read_u16(FILE *file)
{
guint16 tmp;
int result;
result = fread(&tmp, 2, 1, file); g_assert(result == 1);
return GUINT16_FROM_BE(tmp);
}
static unsigned midi_read_u32(FILE *file)
{
guint32 tmp;
int result;
result = fread(&tmp, 4, 1, file); g_assert(result == 1);
return GUINT32_FROM_BE(tmp);
}
static unsigned midi_read_vl(FILE *file)
{
int result;
unsigned x = 0;
while (1) {
result = getc(file); g_assert(result != EOF);
x |= (result & 0x7f);
if (result & 0x80) x <<= 7;
else break;
}
return x;
}
static int tempo_change_compare(gconstpointer pa, gconstpointer pb)
{
const TempoChange *a = (const TempoChange *) pa, *b = (const TempoChange *) pb;
return (a->tt0 > b->tt0) - (a->tt0 < b->tt0);
}
static void vosfile_read_midi(VosSong *song, FILE *file, unsigned mid_ofs, unsigned mid_len, double tempo_factor)
{
int result;
char magic[4];
unsigned header_len, fmt, ppqn, i;
GArray *tempo_arr;
TempoChange tc;
result = fseek(file, mid_ofs, SEEK_SET); g_assert(result == 0);
result = fread(magic, 4, 1, file); g_assert(result == 1);
g_assert(memcmp(magic, "MThd", 4) == 0);
header_len = midi_read_u32(file); g_assert(header_len == 6);
fmt = midi_read_u16(file); g_assert(fmt == 1);
song->ntrack = midi_read_u16(file); g_assert(song->ntrack > 0);
ppqn = midi_read_u16(file); g_assert((ppqn & 0x8000) == 0); /* Actually a ppqn */
song->midi_unit_tt = 1.0 / ppqn;
song->tracks = g_new0(MidiTrack, song->ntrack);
tempo_arr = g_array_new(FALSE, FALSE, sizeof(TempoChange));
tc.rt0 = 0.0; tc.tt0 = 0.0; tc.qn_time = 0.5; g_array_append_val(tempo_arr, tc); /* 120 BPM, the default */
for (i = 0; i < song->ntrack; i++) {
MidiTrack *track = &song->tracks[i];
GArray *event_arr = g_array_new(FALSE, FALSE, sizeof(MidiEvent));
unsigned track_ofs, track_len;
unsigned char cmd = 0; /* The status byte */
unsigned char ch;
unsigned time = 0; /* In MIDI units */
gboolean is_eot = FALSE; /* Found "End of Track"? */
result = fread(magic, 4, 1, file); g_assert(result == 1);
g_assert(memcmp(magic, "MTrk", 4) == 0);
track_len = midi_read_u32(file);
track_ofs = ftell(file);
while ((unsigned) ftell(file) < track_ofs + track_len) {
MidiEvent ev;
double tt;
g_assert(! is_eot);
memset(&ev, 0, sizeof(ev));
time += midi_read_vl(file); tt = time * song->midi_unit_tt;
ch = midi_read_u8(file);
if (ch == 0xff) { /* Meta event */
unsigned meta_type = midi_read_u8(file);
unsigned meta_len = midi_read_vl(file);
switch (meta_type) {
default:
g_warning("Unknown meta event type 0x%02x", meta_type);
/* fall through */
case 0x03: /* Sequence/Track name */
case 0x21: /* MIDI port number */
case 0x58: /* Time signature */
case 0x59: /* Key signature */
result = fseek(file, meta_len, SEEK_CUR); g_assert(result == 0); /* skip over the data */
break;
case 0x2f: /* End of track */
g_assert(meta_len == 0); is_eot = TRUE; break;
case 0x51: /* Tempo */
{
unsigned char buf[3];
unsigned val;
/* NOTE: If tempo changes exist in multiple tracks (e.g. 2317.vos), the array will be out of order. Therefore,
we set rt0 only after sorting them. */
g_assert(meta_len == 3);
result = fread(buf, meta_len, 1, file); g_assert(result == 1);
val = ((unsigned) buf[0] << 16) | ((unsigned) buf[1] << 8) | buf[2];
tc.tt0 = tt; tc.rt0 = 0.0; tc.qn_time = val * 1e-6 / tempo_factor; g_array_append_val(tempo_arr, tc);
}
break;
}
continue;
} else if (ch == 0xf0) { /* SysEx event */
unsigned sysex_len = midi_read_vl(file);
/* Just ignore it */
result = fseek(file, sysex_len, SEEK_CUR); g_assert(result == 0);
} else {
unsigned cmd_type;
if (ch & 0x80) { cmd = ch; ch = midi_read_u8(file); }
cmd_type = (cmd & 0x7f) >> 4; g_assert(cmd_type != 7);
ev.cmd = cmd; ev.a = ch;
/* Program Change and Channel Pressure messages have one status bytes, all others have two */
if (! (cmd_type == 4 || cmd_type == 5)) ev.b = midi_read_u8(file);
}
ev.tt = tt;
g_array_append_val(event_arr, ev);
}
g_assert(is_eot);
g_assert((unsigned) ftell(file) == track_ofs + track_len);
track->nevent = event_arr->len;
track->events = (MidiEvent *) g_array_free(event_arr, FALSE);
}
g_array_sort(tempo_arr, tempo_change_compare);
song->ntempo = tempo_arr->len;
song->tempos = (TempoChange *) g_array_free(tempo_arr, FALSE);
for (i = 1; i < song->ntempo; i++) { /* song->tempos[0].rt0 has been set to zero */
const TempoChange *last_tc = &song->tempos[i-1];
TempoChange *tc = &song->tempos[i];
tc->rt0 = last_tc->rt0 + last_tc->qn_time * (tc->tt0 - last_tc->tt0);
}
if (verbose) {
for (i = 0; i < song->ntempo; i++) {
const TempoChange *tc = &song->tempos[i];
int rtt = (int) tc->rt0;
g_message("Tempo at %d:%02d: %d bpm", rtt / 60, rtt % 60, (int) floor(60.0 / tc->qn_time + 0.5));
}
}
}
static unsigned vosfile_read_u8(FILE *file)
{
int result = getc(file);
g_assert(result != EOF);
return (unsigned) result;
}
/* Little endian */
static unsigned vosfile_read_u16(FILE *file)
{
guint16 tmp;
int result;
result = fread(&tmp, 2, 1, file); g_assert(result == 1);
return GUINT16_FROM_LE(tmp);
}
static unsigned vosfile_read_u32(FILE *file)
{
guint32 tmp;
int result;
result = fread(&tmp, 4, 1, file); g_assert(result == 1);
return GUINT32_FROM_LE(tmp);
}
static char *vosfile_read_string(FILE *file)
{
unsigned len;
char *buf;
int result;
len = vosfile_read_u8(file); buf = g_new0(char, len + 1);
result = fread(buf, 1, len, file); g_assert(result == (int) len);
return buf;
}
static char *vosfile_read_string2(FILE *file)
{
unsigned len;
char *buf;
int result;
len = vosfile_read_u16(file); buf = g_new0(char, len + 1);
result = fread(buf, 1, len, file); g_assert(result == (int) len);
return buf;
}
static char *vosfile_read_string_fixed(FILE *file, unsigned len)
{
char *buf;
int result;
buf = g_new0(char, len + 1);
result = fread(buf, 1, len, file); g_assert(result == (int) len);
return buf;
}
static void print_vosfile_string(const char *name, const char *raw_str)
{
char *str = g_convert(raw_str, -1, "UTF-8", "GB2312", NULL, NULL, NULL);
if (str == NULL || *str != '\0') g_message("%s: %s", name, (str != NULL) ? str : "[conversion failed]");
if (str) g_free(str);
}
static void print_vosfile_string_v(const char *name, const char *raw_str)
{
if (verbose) print_vosfile_string(name, raw_str);
}
static void vosfile_read_info(VosSong *song, FILE *file, unsigned inf_ofs, unsigned inf_len)
{
int result;
unsigned inf_end_ofs = inf_ofs + inf_len, cur_ofs, next_ofs, key;
char *title, *artist, *comment, *vos_author;
unsigned song_type, ext_type, song_length, level;
char buf[4];
GArray *note_arrays_arr = g_array_new(FALSE, FALSE, sizeof(NoteArray));
GArray *user_notes_arr = g_array_new(FALSE, FALSE, sizeof(UserNote));
unsigned last_note_idx[NKEY], last_note_idx_long[NKEY], cur_un_idx;
unsigned count[NKEY], count_long[NKEY];
result = fseek(file, inf_ofs, SEEK_SET); g_assert(result == 0);
/* Skip the "VOS1" header in e.g. test3.vos and test4.vos, if any */
result = fread(buf, 4, 1, file);
if (result == 1 && memcmp(buf, "VOS1", 4) == 0) { /* Found "VOS1" header */
char *str1;
result = fseek(file, 66, SEEK_CUR); g_assert(result == 0);
str1 = vosfile_read_string(file); g_free(str1);
} else {
result = fseek(file, inf_ofs, SEEK_SET); g_assert(result == 0);
}
title = vosfile_read_string(file); print_vosfile_string_v("Title", title); g_free(title);
artist = vosfile_read_string(file); print_vosfile_string_v("Artist", artist); g_free(artist);
comment = vosfile_read_string(file); print_vosfile_string_v("Comment", comment); g_free(comment);
vos_author = vosfile_read_string(file); print_vosfile_string_v("VOS Author", vos_author); g_free(vos_author);
song_type = vosfile_read_u8(file); ext_type = vosfile_read_u8(file);
song_length = vosfile_read_u32(file);
level = vosfile_read_u8(file); if (verbose) g_message("Level: %u", level + 1);
result = fseek(file, 1023, SEEK_CUR); g_assert(result == 0);
result = ftell(file); g_assert(result != -1); cur_ofs = result;
for (key = 0; key < NKEY; key++) {
count[key] = 0; count_long[key] = 0;
last_note_idx[key] = IDX_NONE; last_note_idx_long[key] = IDX_NONE;
song->first_un_idxs[key] = IDX_NONE; song->first_un_idxs_long[key] = IDX_NONE;
}
cur_un_idx = 0;
while (1) {
unsigned type, nnote, i;
gboolean is_user_arr; /* Whether the current note array is the one to be played by the user. */
char dummy2[14];
NoteArray cur_note_arr;
TempoIt it;
result = ftell(file); g_assert(result != -1); cur_ofs = result;
if (cur_ofs == inf_end_ofs) break;
type = vosfile_read_u32(file); nnote = vosfile_read_u32(file);
next_ofs = cur_ofs + nnote * 13 + 22; is_user_arr = (next_ofs == inf_end_ofs);
result = fread(dummy2, 14, 1, file); g_assert(result == 1);
for (i = 0; i < 14; i++) g_assert(dummy2[i] == 0);
memset(&cur_note_arr, 0, sizeof(cur_note_arr));
tempoit_init(song, &it);
if (! is_user_arr) { cur_note_arr.num_note = nnote; cur_note_arr.notes = g_new0(Note, nnote); }
for (i = 0; i < nnote; i++) {
unsigned time, len;
unsigned char cmd, note_num, vol;
unsigned flags;
gboolean is_user_note, is_long;
double tt_start, tt_end, rt_start, rt_end;
time = vosfile_read_u32(file); len = vosfile_read_u32(file);
cmd = vosfile_read_u8(file); note_num = vosfile_read_u8(file); vol = vosfile_read_u8(file);
flags = vosfile_read_u16(file); is_user_note = ((flags & 0x80) != 0); is_long = ((flags & 0x8000) != 0);
tt_start = time / 768.0; tt_end = (time + len) / 768.0;
rt_start = tempoit_tt_to_rt(song, &it, tt_start); rt_end = tempoit_tt_to_rt(song, &it, tt_end);
if (song->has_min_max_rt) { song->min_rt = MIN(song->min_rt, rt_start); song->max_rt = MAX(song->max_rt, rt_end); }
else { song->min_rt = rt_start; song->max_rt = rt_end; song->has_min_max_rt = TRUE; }
if (! is_user_arr) {
Note *note = &cur_note_arr.notes[i];
note->tt_start = tt_start; note->tt_end = tt_end;
note->rt_start = rt_start; note->rt_end = rt_end;
note->cmd = cmd; note->note_num = note_num; note->vol = vol;
note->is_user = is_user_note; note->is_long = is_long;
} else {
UserNote un;
g_assert(is_user_note);
memset(&un, 0, sizeof(un));
un.tt_start = tt_start; un.rt_start = rt_start;
un.tt_end = tt_end; un.rt_end = rt_end;
un.cmd = cmd; un.note_num = note_num; un.vol = vol;
un.key = (flags & 0x70) >> 4; un.color = (flags & 0x0f); un.is_long = is_long;
un.tt_stop = (un.is_long) ? un.tt_end : un.tt_start;
un.rt_stop = (un.is_long) ? un.rt_end : un.rt_start;
g_assert(un.key < NKEY);
un.prev_idx = last_note_idx[un.key]; un.next_idx = IDX_NONE;
if (last_note_idx[un.key] != IDX_NONE) {
UserNote *last_un = &g_array_index(user_notes_arr, UserNote, last_note_idx[un.key]);
if (un.tt_start < last_un->tt_stop) { /* Notes on the same key should never overlap */
g_warning("User note %u ignored because of overlapping notes.", i);
goto skip_user_note;
}
last_un->next_idx = cur_un_idx;
} else song->first_un_idxs[un.key] = cur_un_idx; /* First note on this key */
last_note_idx[un.key] = cur_un_idx;
un.count = ++count[un.key];
if (un.is_long) {
un.prev_idx_long = last_note_idx_long[un.key]; un.next_idx_long = IDX_NONE;
if (last_note_idx_long[un.key] != IDX_NONE)
g_array_index(user_notes_arr, UserNote, last_note_idx_long[un.key]).next_idx_long = cur_un_idx;
else song->first_un_idxs_long[un.key] = cur_un_idx;
last_note_idx_long[un.key] = cur_un_idx;
un.count_long = ++count_long[un.key];
} else { un.prev_idx_long = IDX_NONE; un.next_idx_long = IDX_NONE; }
g_array_append_val(user_notes_arr, un); cur_un_idx++;
skip_user_note: ;
}
}
if (! is_user_arr) g_array_append_val(note_arrays_arr, cur_note_arr);
cur_ofs = next_ofs; g_assert((unsigned) ftell(file) == cur_ofs);
}
song->num_note_array = note_arrays_arr->len;
song->note_arrays = (NoteArray *) g_array_free(note_arrays_arr, FALSE);
song->num_user_note = user_notes_arr->len;
song->user_notes = (UserNote *) g_array_free(user_notes_arr, FALSE);
}
static void vosfile_read_info_022(VosSong *song, FILE *file, unsigned inf_ofs, unsigned inf_len)
{
int result;
char *title, *artist, *comment, *vos_author, *str;
unsigned version;
unsigned song_length, level, x;
unsigned i, j, k, key;
unsigned narr, nunote; /* NOTE: due to the deletion of buggy notes, song->num_user_note may be smaller than nunote */
char magic[6], unknown1[11];
GArray *user_notes_arr = g_array_new(FALSE, FALSE, sizeof(UserNote));
unsigned last_note_idx[NKEY], last_note_idx_long[NKEY], cur_un_idx;
unsigned count[NKEY], count_long[NKEY];
result = fseek(file, inf_ofs, SEEK_SET); g_assert(result == 0);
result = fread(magic, 6, 1, file); g_assert(result == 1);
if (memcmp(magic, "VOS022", 6) == 0) version = 22;
else if (memcmp(magic, "VOS006", 6) == 0) version = 6;
else g_assert_not_reached();
title = vosfile_read_string2(file); print_vosfile_string_v("Title", title); g_free(title);
artist = vosfile_read_string2(file); print_vosfile_string_v("Artist", artist); g_free(artist);
comment = vosfile_read_string2(file); print_vosfile_string_v("Comment", comment); g_free(comment);
vos_author = vosfile_read_string2(file); print_vosfile_string_v("VOS Author", vos_author); g_free(vos_author);
str = vosfile_read_string2(file); g_free(str);
result = fread(unknown1, 11, 1, file); g_assert(result == 1);
x = vosfile_read_u32(file); /* song_length_tt? */ song_length = vosfile_read_u32(file);
result = fseek(file, 1024, SEEK_CUR); g_assert(result == 0);
narr = vosfile_read_u32(file); x = vosfile_read_u32(file); g_assert(x == 1);
song->num_note_array = narr; song->note_arrays = g_new0(NoteArray, narr);
for (k = 0; k < narr; k++) {
x = vosfile_read_u8(file); g_assert(x == 4);
x = vosfile_read_u32(file); /* type */
}
x = vosfile_read_u8(file); g_assert(x == 0);
level = vosfile_read_u8(file); if (verbose) g_message("Level: %u", level + 1);
str = vosfile_read_string2(file); g_free(str);
x = vosfile_read_u32(file); g_assert(x == 0);
for (key = 0; key < NKEY; key++) {
count[key] = 0; count_long[key] = 0;
last_note_idx[key] = IDX_NONE; last_note_idx_long[key] = IDX_NONE;
song->first_un_idxs[key] = IDX_NONE; song->first_un_idxs_long[key] = IDX_NONE;
}
cur_un_idx = 0;
/* Notes */
for (k = 0; k < narr; k++) {
unsigned nnote;
TempoIt it;
NoteArray *cur_note_arr = &song->note_arrays[k];
nnote = vosfile_read_u32(file);
cur_note_arr->num_note = nnote; cur_note_arr->notes = g_new0(Note, nnote);
tempoit_init(song, &it);
for (i = 0; i < nnote; i++) {
unsigned time, len;
unsigned char cmd, note_num, vol;
unsigned track;
gboolean is_user_note, is_long;
double tt_start, tt_end, rt_start, rt_end;
Note *note = &cur_note_arr->notes[i];
x = vosfile_read_u8(file); g_assert(x == 0);
time = vosfile_read_u32(file); note_num = vosfile_read_u8(file);
track = vosfile_read_u8(file); cmd = track | 0x90;
vol = vosfile_read_u8(file); is_user_note = vosfile_read_u8(file);
x = vosfile_read_u8(file);
#if 0
if (x != 1) g_message("Special note: k=%u i=%u x=%u", k, i, x);
#endif
is_long = vosfile_read_u8(file); len = vosfile_read_u32(file);
x = vosfile_read_u8(file); g_assert(x == 0x00 || x == 0xff);
#if 0
/* This is true for most files, but 994.vos is an exception */
g_assert(x == (is_user_note ? 0x00 : 0xff));
#endif
tt_start = time / 768.0; tt_end = (time + len) / 768.0;
rt_start = tempoit_tt_to_rt(song, &it, tt_start); rt_end = tempoit_tt_to_rt(song, &it, tt_end);
if (song->has_min_max_rt) { song->min_rt = MIN(song->min_rt, rt_start); song->max_rt = MAX(song->max_rt, rt_end); }
else { song->min_rt = rt_start; song->max_rt = rt_end; song->has_min_max_rt = TRUE; }
note->tt_start = tt_start; note->tt_end = tt_end;
note->rt_start = rt_start; note->rt_end = rt_end;
note->cmd = cmd; note->note_num = note_num; note->vol = vol;
note->is_user = is_user_note; note->is_long = is_long;
}
}
/* User notes */
if (version == 22) { x = vosfile_read_u32(file); g_assert(x == 0); }
nunote = vosfile_read_u32(file);
for (j = 0; j < nunote; j++) {
NoteArray *cur_note_arr;
Note *note;
UserNote un;
k = vosfile_read_u8(file); g_assert(k < narr); cur_note_arr = &song->note_arrays[k];
i = vosfile_read_u32(file); g_assert(i < cur_note_arr->num_note); note = &cur_note_arr->notes[i];
key = vosfile_read_u8(file);
g_assert(note->is_user);
memset(&un, 0, sizeof(un));
un.tt_start = note->tt_start; un.rt_start = note->rt_start;
un.tt_end = note->tt_end; un.rt_end = note->rt_end;
un.cmd = note->cmd; un.note_num = note->note_num; un.vol = note->vol;
un.key = key; un.color = (k & 0x0f); un.is_long = note->is_long;
un.tt_stop = (un.is_long) ? un.tt_end : un.tt_start;
un.rt_stop = (un.is_long) ? un.rt_end : un.rt_start;
g_assert(un.key < NKEY);
un.prev_idx = last_note_idx[un.key]; un.next_idx = IDX_NONE;
if (last_note_idx[un.key] != IDX_NONE) {
UserNote *last_un = &g_array_index(user_notes_arr, UserNote, last_note_idx[un.key]);
if (un.tt_start < last_un->tt_stop) { /* Notes on the same key should never overlap */
g_warning("User note %u ignored because of overlapping notes.", i);
goto skip_user_note;
}
last_un->next_idx = cur_un_idx;
} else song->first_un_idxs[un.key] = cur_un_idx; /* First note on this key */
last_note_idx[un.key] = cur_un_idx;
un.count = ++count[un.key];
if (un.is_long) {
un.prev_idx_long = last_note_idx_long[un.key]; un.next_idx_long = IDX_NONE;
if (last_note_idx_long[un.key] != IDX_NONE)
g_array_index(user_notes_arr, UserNote, last_note_idx_long[un.key]).next_idx_long = cur_un_idx;
else song->first_un_idxs_long[un.key] = cur_un_idx;
last_note_idx_long[un.key] = cur_un_idx;
un.count_long = ++count_long[un.key];
} else { un.prev_idx_long = IDX_NONE; un.next_idx_long = IDX_NONE; }
g_array_append_val(user_notes_arr, un); cur_un_idx++;
skip_user_note: ;
}
song->num_user_note = user_notes_arr->len;
song->user_notes = (UserNote *) g_array_free(user_notes_arr, FALSE);
/* What follows is the lyric, which we ignore for now. */
}
static void vosfile_read_vos1(VosSong *song, FILE *file, unsigned file_size, double tempo_factor)
{
unsigned ofs, next_ofs;
unsigned inf_ofs = 0, inf_len = 0, mid_ofs = 0, mid_len = 0;
char *seg_name;
/* Read the segments */
ofs = vosfile_read_u32(file);
while (1) {
seg_name = vosfile_read_string_fixed(file, 16);
if (strcmp(seg_name, "EOF") == 0 || ofs == file_size) { g_free(seg_name); break; }
next_ofs = vosfile_read_u32(file);
if (strcmp(seg_name, "inf") == 0) { inf_ofs = ofs; inf_len = next_ofs - ofs; }
else if (strcmp(seg_name, "mid") == 0) { mid_ofs = ofs; mid_len = next_ofs - ofs; }
else g_assert_not_reached();
g_free(seg_name);
ofs = next_ofs;
}
g_assert(inf_len != 0); g_assert(mid_len != 0);
vosfile_read_midi(song, file, mid_ofs, mid_len, tempo_factor);
vosfile_read_info(song, file, inf_ofs, inf_len);
}
static void vosfile_read_vos022(VosSong *song, FILE *file, unsigned file_size, double tempo_factor)
{
int result;
unsigned inf_ofs = IDX_NONE, inf_len = 0, mid_ofs = IDX_NONE, mid_len = 0;
unsigned subfile_idx = 0, ofs = 4, data_ofs;
unsigned fname_len, len;
char *fname;
while (1) {
if (ofs == file_size) break;
result = fseek(file, ofs, SEEK_SET); g_assert(result == 0);
fname_len = vosfile_read_u32(file);
fname = vosfile_read_string_fixed(file, fname_len);
len = vosfile_read_u32(file); data_ofs = ofs + 4 + fname_len + 4;
if (subfile_idx == 0) { g_assert(strcmp(fname, "Vosctemp.trk") == 0); inf_ofs = data_ofs; inf_len = len; }
else if (subfile_idx == 1) {
g_assert(strcmp(fname, "VOSCTEMP.mid") == 0); mid_ofs = data_ofs, mid_len = len;
} else g_assert_not_reached();
g_free(fname);
ofs = data_ofs + len; subfile_idx++;
}
g_assert(inf_ofs != IDX_NONE); g_assert(mid_ofs != IDX_NONE);
vosfile_read_midi(song, file, mid_ofs, mid_len, tempo_factor);
vosfile_read_info_022(song, file, inf_ofs, inf_len);
}
static VosSong *read_vos_file(const char *fname, double tempo_factor)
{
VosSong *song;
FILE *file;
unsigned magic, file_size;
int result;
file = fopen(fname, "rb"); g_assert(file != NULL);
song = g_new0(VosSong, 1); song->has_min_max_rt = FALSE;
hash_file(file, song->hash, SHA_DIGEST_LENGTH);
result = fseek(file, 0, SEEK_END); g_assert(result == 0);
file_size = ftell(file);
result = fseek(file, 0, SEEK_SET); g_assert(result == 0);
magic = vosfile_read_u32(file);
if (magic == 3) vosfile_read_vos1(song, file, file_size, tempo_factor);
else if (magic == 2) vosfile_read_vos022(song, file, file_size, tempo_factor);
else g_assert_not_reached();
fclose(file);
return song;
}
#define SET_COLOR(idx, r, g, b) \
do { \
game->colors[(idx)].red = (guint16) ((double) (r) * 65535); \
game->colors[(idx)].green = (guint16) ((double) (g) * 65535); \
game->colors[(idx)].blue = (guint16) ((double) (b) * 65535); \
} while (0)
/* h is in 0..3 */
static void hsv2rgb(VosGame *game, double h, double s, double v, double *pr, double *pg, double *pb)
{
double igamma = game->opts->igamma;
double x0 = (1.0 - s) * v, dx = s * v;
double r, g, b;
if (h < 1.0) { r = x0 + (1.0 - h) * dx; g = x0 + h * dx; b = x0; }
else if (h < 2.0) { r = x0; g = x0 + (2.0 - h) * dx; b = x0 + (h - 1.0) * dx; }
else { r = x0 + (h - 2.0) * dx; g = x0; b = x0 + (3.0 - h) * dx; }
r = pow(r, igamma); g = pow(g, igamma); b = pow(b, igamma);
*pr = r; *pg = g; *pb = b;
}
static void init_colors(VosGame *game)
{