-
Notifications
You must be signed in to change notification settings - Fork 17
/
trs_cassette.c
1311 lines (1218 loc) · 36.8 KB
/
trs_cassette.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
/*
* Copyright (C) 1992 Clarendon Hill Software.
*
* Permission is granted to any individual or institution to use, copy,
* or redistribute this software, provided this copyright notice is retained.
*
* This software is provided "as is" without any expressed or implied
* warranty. If this software brings on any sort of damage -- physical,
* monetary, emotional, or brain -- too bad. You've got no one to blame
* but yourself.
*
* The software may be modified for your own purposes, but modified versions
* must retain this notice.
*/
/*
* Portions copyright (c) 1996-2020, Timothy P. Mann
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* This module implements cassette I/O, game sound, and Orchestra
* 85/90 sound. "Game sound" is defined as output to the cassette
* port when the cassette motor is off, or output to the Model III/4
* sound option card (a 1-bit DAC).
*
* Compile time option:
*
* HAVE_OSS - Set this if you have the Open Sound System (OSS) or an
* OSS compatibility layer that provides /dev/dsp. Older Linux
* systems use OSS as their primary sound API, and some other
* Unix-like systems have it as well. Newer Linux systems use ALSA
* instead, but generally have an OSS compatibility layer. On Linux
* systems that use the PulseAudio sound server, use the padsp wrapper
* program to run xtrs with /dev/dsp support.
*
* Regardless of whether HAVE_OSS is set, cassettes can be
* read/written from files in various formats, including WAV.
*
* When HAVE_OSS is set, cassettes can be also read/written directly
* through your sound input/output device, and both game sound and
* Orchestra 85/90 sound are sent to the sound output device.
*
* Game sound and Orchestra 85/90 sound are disabled if HAVE_OSS is
* not set.
*/
#define _POSIX_C_SOURCE 200112L /* signal.h: sigemptyset(), ...
stdio.h: fileno() */
#if __linux
#define HAVE_OSS 1
#endif
/*#define CASSDEBUG 1*/
/*#define CASSDEBUG2 1*/
/*#define CASSDEBUG3 1*/
/*#define CASSDEBUG4 1*/
#include "trs.h"
#include "z80.h"
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#if HAVE_OSS
#include <sys/ioctl.h>
#include <fcntl.h>
#include <sys/soundcard.h>
#endif
#define CLOSE 0
#define READ 1
#define WRITE 2
#define SOUND 3
#define ORCH90 4
#define FAILED 5
#define CAS_FORMAT 1 /* recovered bit/byte stream */
#define CPT_FORMAT 2 /* cassette pulse train w/ exact timing */
#define WAV_FORMAT 3 /* wave file */
#define DIRECT_FORMAT 4 /* direct to sound card */
#define DEBUG_FORMAT 5 /* like cpt but in ASCII */
static char *format_name[] = {
NULL, "cas", "cpt", "wav", "direct", "debug" };
#define DEFAULT_SAMPLE_RATE 11025 /* samples/sec for .wav and /dev/dsp output */
#define NOISE_FLOOR 64
#define CONTROL_FILENAME ".cassette.ctl"
#define DEFAULT_FILENAME "cassette.cas"
#define DSP_FILENAME "/dev/dsp" /* for sound output */
#define DEFAULT_FORMAT CAS_FORMAT
#define FLUSH -500 /* special fake signal value used when turning off motor */
static char cassette_filename[256];
static int cassette_position;
static int cassette_format;
static int cassette_state = CLOSE;
static int cassette_motor = 0;
static FILE *cassette_file;
static float cassette_avg;
static float cassette_env;
static int cassette_noisefloor;
static int cassette_sample_rate;
int cassette_default_sample_rate = DEFAULT_SAMPLE_RATE;
static int cassette_stereo = 0;
#if HAVE_OSS
static int cassette_afmt = AFMT_U8;
#endif
/* For bit-level emulation */
static tstate_t cassette_transition;
static tstate_t last_sound;
static tstate_t cassette_firstoutread;
static int cassette_value, cassette_next, cassette_flipflop;
static int cassette_lastnonzero;
static int cassette_transitionsout;
static unsigned long cassette_delta;
static float cassette_roundoff_error;
/* For bit/byte conversion (.cas file i/o) */
static int cassette_byte;
static int cassette_bitnumber;
static int cassette_pulsestate;
#define SPEED_500 0
#define SPEED_1500 1
#define SPEED_250 2
int cassette_speed = SPEED_500;
/* Pulse shapes for conversion from .cas on input */
#define CAS_MAXSTATES 8
struct {
int delta_us;
int next;
} pulse_shape[3][2][CAS_MAXSTATES] = {
{{
/* Low-speed zero: clock 1 data 0 */
{ 0, 1 },
{ 128, 2 },
{ 128, 0 },
{ 1871, 0 }, /* normally 1757; 1871 after 8th bit */
{ -1, -1 }
}, {
/* Low-speed one: clock 1 data 1 */
{ 0, 1 },
{ 128, 2 },
{ 128, 0 },
{ 748, 1 },
{ 128, 2 },
{ 128, 0 },
{ 860, 0 }, /* normally 748; 860 after 8th bit; 1894 after a5 sync */
{ -1, -1 }
}}, {{
/* High-speed zero: wide pulse */
{ 0, 1 },
{ 376, 2 },
{ 376, 1 },
{ -1, -1 }
}, {
/* High-speed one: narrow pulse */
{ 0, 1 },
{ 188, 2 },
{ 188, 1 },
{ -1, -1 }
}}, {{
/* Level I zero: clock 1 data 0 */
{ 0, 1 },
{ 125, 2 },
{ 125, 0 },
{ 3568, 0 },
{ -1, -1 }
}, {
/* Level I one: clock 1 data 1 */
{ 0, 1 },
{ 128, 2 },
{ 128, 0 },
{ 1673, 1 },
{ 128, 2 },
{ 128, 0 },
{ 1673, 0 },
{ -1, -1 }
}}
};
/* States and thresholds for conversion to .cas on output */
#define ST_INITIAL 0
#define ST_500GOTCLK 1
#define ST_500GOTDAT 2
#define ST_1500 3
#define ST_250 4
#define ST_250GOTCLK 5
#define ST_250GOTDAT 6
#define ST_500THRESH 1250.0 /* us threshold between 0 and 1 */
#define ST_1500THRESH 282.0 /* us threshold between 1 and 0 */
#define ST_250THRESH 2500.0 /* us threshold between 0 and 1 */
#define DETECT_250 1200.0 /* detect level 1 input routine */
/* Values for conversion to .wav on output */
/* Values in comments are from Model I technical manual. Model III/4 are
close though not quite the same, as one resistor in the network was
changed; we ignore the difference. Actually, we ignore more than
that; we convert the values as if 0 were really halfway between
high and low. */
Uchar value_to_sample[] = { 127, /* 0.46 V */
254, /* 0.85 V */
0, /* 0.00 V */
127, /* unused, but close to 0.46 V */
};
/* .wav file definitions */
#define WAVE_FORMAT_PCM (0x0001)
#define WAVE_FORMAT_MONO 1
#define WAVE_FORMAT_STEREO 2
#define WAVE_FORMAT_8BIT 8
#define WAVE_FORMAT_16BIT 16
#define WAVE_RIFFSIZE_OFFSET 0x04
#define WAVE_RIFF_OFFSET 0x08
#define WAVE_DATAID_OFFSET 0x24
#define WAVE_DATASIZE_OFFSET 0x28
#define WAVE_DATA_OFFSET 0x2c
static long wave_dataid_offset = WAVE_DATAID_OFFSET;
static long wave_datasize_offset = WAVE_DATASIZE_OFFSET;
static long wave_data_offset = WAVE_DATA_OFFSET;
#if HAVE_OSS
/* Orchestra 80/85/90 stuff */
static int orch90_left = 128, orch90_right = 128;
#endif
#if !HAVE_OSS
static void
no_sound(void)
{
static int warned = 0;
if (!warned) {
error("sound support is not compiled in");
warned = 1;
}
}
#endif
/* Output an 8-byte unsigned sample, if necessary converting to a
* different sample format. */
static void
put_sample(Uchar sample, int convert, FILE* f)
{
if (convert) {
#if HAVE_OSS
switch (cassette_afmt) {
case AFMT_U8:
putc(sample, f);
break;
case AFMT_S16_LE:
put_twobyte((sample << 8) - 0x8000, f);
break;
default:
error("sample format 0x%x not supported", cassette_afmt);
break;
}
return;
#endif
}
putc(sample, f);
}
/* Get an 8-byte unsigned sample, if necessary converting from a
* different sample format and/or reducing stereo to mono. */
static int
get_sample(int convert, FILE* f)
{
#if HAVE_OSS
if (convert) {
int ret = 0;
short s = 0;
switch (cassette_afmt) {
case AFMT_U8:
ret = getc(f);
break;
case AFMT_S16_LE:
ret = get_twobyte((Ushort *)&s, cassette_file);
if (ret == EOF) break;
ret = ((s + 0x8000) >> 8) & 0xff;
break;
default:
error("sample format 0x%x not supported", cassette_afmt);
break;
}
return ret;
}
#endif
return getc(f);
}
/* Write a new .wav file header to a file. Return -1 on error. */
static int
create_wav_header(FILE *f)
{
Uint field;
/* Chunk sizes don't count the 4-byte chunk type name nor the 4-byte
size field itself. The RIFF chunk is the whole file, so its size
is the actual length of the file minus WAVE_RIFF_OFFSET (=8).
The data chunk is the actual sample data, so its size is the size
of the file minus wave_data_offset. */
wave_dataid_offset = WAVE_DATAID_OFFSET;
wave_datasize_offset = WAVE_DATASIZE_OFFSET;
wave_data_offset = WAVE_DATA_OFFSET;
if (cassette_position < wave_data_offset) {
cassette_position = wave_data_offset;
}
if (fputs("RIFF", f) < 0) return -1;
if (put_fourbyte(0, f) < 0) return -1; /* RIFF chunk size */
if (fputs("WAVEfmt ", f) < 0) return -1;
if (put_fourbyte(16, f) < 0) return -1; /* fmt chunk size */
if (put_twobyte(WAVE_FORMAT_PCM, f) < 0) return -1;
if (put_twobyte(WAVE_FORMAT_MONO, f) < 0) return -1;
if (put_fourbyte(cassette_sample_rate, f) < 0) return -1;
field = (WAVE_FORMAT_MONO * cassette_sample_rate * WAVE_FORMAT_8BIT/8);
if (put_fourbyte(field, f) < 0) return -1;
field = (WAVE_FORMAT_MONO * WAVE_FORMAT_8BIT/8);
if (put_twobyte(field, f) < 0) return -1;
if (put_twobyte(WAVE_FORMAT_8BIT, f) < 0) return -1; /* end of fmt chunk */
if (fputs("data", f) < 0) return -1;
if (put_fourbyte(0, f) < 0) return -1; /* size of data chunk payload */
/* payload starts here */
return 0;
}
/* Error message generator */
static int
check_chunk_id(char *expected, FILE* f)
{
char c4[5];
c4[4] = '\0';
if (fread(c4, 4, 1, f) != 1) return -1;
if (strcmp(c4, expected) != 0) {
error("unusable wav file: expected chunk id '%s', got '%s'", expected, c4);
return -1;
}
return 0;
}
/* Parse a .wav file's RIFF header. We don't understand much about
the RIFF format, so we might fail on valid .WAV files. For now,
that's just tough. Try running the file through sox to convert it
to something more vanilla. */
static int
parse_wav_header(FILE *f)
{
Uint n4;
Uint fmt_size;
Ushort n2, expect2;
if (check_chunk_id("RIFF", f) < 0) return -1;
if (get_fourbyte(&n4, f) < 0) return -1; /* ignore this field */
if (check_chunk_id("WAVE", f) < 0) return -1;
if (check_chunk_id("fmt ", f) < 0) return -1;
if (get_fourbyte(&fmt_size, f) < 0) return -1;
if (get_twobyte(&n2, f) < 0) return -1;
if (n2 != WAVE_FORMAT_PCM) {
error("unusable wav file: must be pcm");
return -1;
}
if (get_twobyte(&n2, f) < 0) return -1;
if (n2 != WAVE_FORMAT_MONO) {
error("unusable wav file: must be mono");
return -1;
}
if (get_fourbyte(&n4, f) < 0) return -1;
cassette_sample_rate = n4;
if (get_fourbyte(&n4, f) < 0) return -1; /* ignore this field */
expect2 = WAVE_FORMAT_MONO * WAVE_FORMAT_8BIT/8;
if (get_twobyte(&n2, f) < 0) return -1;
if (n2 != expect2) {
error("unusable wav file: must be %d bytes/sample", expect2);
return -1;
}
expect2 = WAVE_FORMAT_8BIT;
if (get_twobyte(&n2, f) < 0) return -1;
if (n2 != expect2) {
error("unusable wav file: must be %d bits/sample", expect2);
return -1;
}
fmt_size -= 16; /* size read so far */
while (fmt_size-- > 0) getc(f); /* ignore additional */
wave_dataid_offset = ftell(f);
if (check_chunk_id("data", f) < 0) return -1;
wave_datasize_offset = ftell(f);
if (get_fourbyte(&n4, f) < 0) return -1; /* ignore this field */
wave_data_offset = ftell(f);
if (cassette_position < wave_data_offset) {
cassette_position = wave_data_offset;
}
return 0;
}
static int
set_audio_format(FILE *f, int state)
{
#if HAVE_OSS
int audio_fd = fileno(f);
int format, stereo, speed, req;
req = format = AFMT_U8; /* unsigned 8-bit */
if (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &format)==-1) return -1;
if (format != req) {
req = format = AFMT_S16_LE; /* signed 16-bit little-endian */
if (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &format)==-1) return -1;
if (format != req) {
error("requested audio format 0x%x, got 0x%x", req, format);
errno = EINVAL;
return -1;
}
}
cassette_afmt = format;
req = stereo = (state == ORCH90);
if (ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo)==-1) return -1;
if (req && !stereo) {
error("requested stereo, got mono");
errno = EINVAL;
return -1;
}
cassette_stereo = stereo;
req = speed = cassette_sample_rate;
if (ioctl(audio_fd, SNDCTL_DSP_SPEED, &speed)==-1) return -1;
if (abs(speed - req) > req/20) {
error("requested sample rate %d Hz, got %d Hz", req, speed);
errno = EINVAL;
return -1;
}
#endif
return 0;
}
static void get_control(void)
{
FILE *f;
f = fopen(CONTROL_FILENAME, "r");
cassette_format = DEFAULT_FORMAT;
if ((!f) ||
(fscanf(f, "%s %d %d", cassette_filename,
&cassette_position, &cassette_format) < 2)) {
error("can't read %s (%s);\n cassette file will be: %s, format %s",
CONTROL_FILENAME, strerror(errno),
DEFAULT_FILENAME, format_name[DEFAULT_FORMAT]);
strcpy(cassette_filename, DEFAULT_FILENAME);
cassette_position = 0;
}
if (f) {
fclose(f);
}
}
static void put_control(void)
{
FILE *f;
f = fopen(CONTROL_FILENAME, "w");
if (f) {
trs_paused = 1; /* disable speed measurement for this round */
fprintf(f, "%s %d %d\n", cassette_filename, cassette_position,
cassette_format);
fclose(f);
}
}
/* Return value: 1 = already that state; 0 = state changed; -1 = failed */
static int assert_state(int state)
{
if (cassette_state == state) {
return 1;
}
if (cassette_state == FAILED && state != CLOSE) {
return -1;
}
#if CASSDEBUG
debug("state %d -> %d\n", cassette_state, state);
#endif
if (cassette_state == ORCH90) {
trs_orch90_out(0, FLUSH);
}
if (cassette_state != CLOSE && cassette_state != FAILED) {
if (cassette_format == DIRECT_FORMAT) {
sigset_t set, oldset;
sigemptyset(&set);
sigaddset(&set, SIGALRM);
sigprocmask(SIG_BLOCK, &set, &oldset);
trs_paused = 1; /* disable speed measurement for this round */
fclose(cassette_file);
sigprocmask(SIG_SETMASK, &oldset, NULL);
cassette_position = 0;
} else {
cassette_position = ftell(cassette_file);
if (cassette_format == WAV_FORMAT && cassette_state == WRITE) {
fseek(cassette_file, WAVE_RIFFSIZE_OFFSET, 0);
put_fourbyte(cassette_position - WAVE_RIFF_OFFSET, cassette_file);
fseek(cassette_file, wave_datasize_offset, 0);
put_fourbyte(cassette_position - wave_data_offset, cassette_file);
}
fclose(cassette_file);
}
if (cassette_state != SOUND && cassette_state != ORCH90) {
put_control();
}
#if HAVE_OSS
cassette_stereo = 0;
cassette_afmt = AFMT_U8;
#endif
}
switch (state) {
case READ:
get_control();
if (cassette_format == DIRECT_FORMAT) {
cassette_file = fopen(cassette_filename, "r");
if (cassette_file == NULL) {
error("couldn't read %s: %s", cassette_filename, strerror(errno));
cassette_state = FAILED;
return -1;
}
/*setbuf(cassette_file, NULL);*/ /* seems no need for this */
cassette_sample_rate = cassette_default_sample_rate;
if (set_audio_format(cassette_file, state) < 0) {
error("couldn't set audio format on %s: %s",
cassette_filename, strerror(errno));
cassette_file = NULL;
cassette_state = FAILED;
return -1;
}
} else {
cassette_file = fopen(cassette_filename, "r");
if (cassette_format == WAV_FORMAT &&
cassette_file != NULL && parse_wav_header(cassette_file) < 0) {
cassette_file = NULL;
}
if (cassette_file == NULL) {
error("couldn't read %s: %s", cassette_filename, strerror(errno));
cassette_state = FAILED;
return -1;
}
fseek(cassette_file, cassette_position, 0);
}
break;
case SOUND:
case ORCH90:
case WRITE:
if (state == SOUND || state == ORCH90) {
cassette_format = DIRECT_FORMAT;
strcpy(cassette_filename, DSP_FILENAME);
} else {
get_control();
}
if (cassette_format == DIRECT_FORMAT) {
#if !HAVE_OSS
no_sound();
return -1;
#endif
cassette_sample_rate = cassette_default_sample_rate;
cassette_file = fopen(cassette_filename, "w");
if (cassette_file == NULL) {
error("couldn't write %s: %s", cassette_filename, strerror(errno));
cassette_state = FAILED;
return -1;
}
setbuf(cassette_file, NULL); /* ??hangs on some OSS drivers */
#if HAVE_OSS
if (state == SOUND || state == ORCH90) {
/*int arg = 0x7fff0008;*/ /* unlimited fragments of size (1 << 8) */
int arg = 0x00200008; /* 32 fragments of size (1 << 8) */
if (ioctl(fileno(cassette_file), SNDCTL_DSP_SETFRAGMENT, &arg) < 0) {
error("warning: couldn't set sound fragment size: %s",
strerror(errno));
}
}
#endif
if (set_audio_format(cassette_file, state) < 0) {
error("couldn't set audio format on %s: %s",
cassette_filename, strerror(errno));
cassette_file = NULL;
cassette_state = FAILED;
return -1;
}
} else if (cassette_format == WAV_FORMAT) {
cassette_file = fopen(cassette_filename, "r+");
if (cassette_file == NULL) {
cassette_sample_rate = cassette_default_sample_rate;
cassette_file = fopen(cassette_filename, "w");
if (cassette_file && create_wav_header(cassette_file) < 0) {
cassette_file = NULL;
}
} else {
if (parse_wav_header(cassette_file) < 0) {
fclose(cassette_file);
cassette_file = NULL;
}
}
if (cassette_file != NULL) {
fseek(cassette_file, cassette_position, 0);
}
} else {
cassette_file = fopen(cassette_filename, "r+");
if (cassette_file == NULL) {
cassette_file = fopen(cassette_filename, "w");
}
if (cassette_file != NULL) {
fseek(cassette_file, cassette_position, 0);
}
}
if (cassette_file == NULL) {
error("couldn't write %s: %s", cassette_filename, strerror(errno));
cassette_state = FAILED;
return -1;
}
break;
}
cassette_state = state;
return 0;
}
/* Call assert_state and ignore return value */
static void
assert_state_void(int state)
{
assert_state(state);
}
/* Record an output transition.
value is either the new port value or FLUSH.
*/
static void
transition_out(int value)
{
Uchar sample;
long nsamples, delta_us;
Ushort code;
float ddelta_us;
sigset_t set, oldset;
cassette_transitionsout++;
if (value != FLUSH && value == cassette_value) return;
sigemptyset(&set);
sigaddset(&set, SIGALRM);
sigprocmask(SIG_BLOCK, &set, &oldset);
ddelta_us = (z80_state.t_count - cassette_transition) / z80_state.clockMHz
- cassette_roundoff_error;
switch (cassette_format) {
case DEBUG_FORMAT:
/* Print value and delta_us in ASCII for easier examination */
if (value == FLUSH) value = cassette_value;
delta_us = (unsigned long) (ddelta_us + 0.5);
cassette_roundoff_error = delta_us - ddelta_us;
fprintf(cassette_file, "%d %lu\n", value, delta_us);
break;
case CPT_FORMAT:
/* Encode value and delta_us in two bytes if delta_us is small enough.
Pack bits as ddddddddddddddvv and store this value in little-
endian order. */
if (value == FLUSH) value = cassette_value;
delta_us = (unsigned long) (ddelta_us + 0.5);
cassette_roundoff_error = delta_us - ddelta_us;
if (delta_us < 0x3fff) {
code = value | (delta_us << 2);
put_twobyte(code, cassette_file);
} else {
/* Else write 0xffff escape code and encode in five bytes:
1-byte value, then 4-byte delta_us in little-endian order */
put_twobyte(0xffff, cassette_file);
putc(value, cassette_file);
put_fourbyte(delta_us, cassette_file);
}
break;
case WAV_FORMAT:
case DIRECT_FORMAT:
#if HAVE_OSS
if (cassette_state == SOUND) {
if (ddelta_us > 20000.0) {
/* Truncate silent periods */
ddelta_us = 20000.0;
cassette_roundoff_error = 0.0;
}
if (trs_event_scheduled() == transition_out ||
trs_event_scheduled() == assert_state_void) {
trs_cancel_event();
}
if (value == FLUSH) {
trs_schedule_event(assert_state_void, CLOSE, 5000000);
} else {
trs_schedule_event(transition_out, FLUSH,
(int)(25000 * z80_state.clockMHz));
}
}
#endif
sample = value_to_sample[cassette_value];
nsamples = (unsigned long)
(ddelta_us / (1000000.0/cassette_sample_rate) + 0.5);
if (nsamples == 0) nsamples = 1; /* always at least one sample */
cassette_roundoff_error =
nsamples * (1000000.0/cassette_sample_rate) - ddelta_us;
#if CASSDEBUG
debug("%d %4lu %d -> %3lu\n", cassette_value,
z80_state.t_count - cassette_transition, value, nsamples);
#endif
if (cassette_format == DIRECT_FORMAT && cassette_stereo) nsamples *= 2;
while (nsamples-- > 0) {
put_sample(sample, cassette_format == DIRECT_FORMAT, cassette_file);
}
if (value == FLUSH) {
value = cassette_value;
#if HAVE_OSS
if (cassette_format == DIRECT_FORMAT) {
ioctl(fileno(cassette_file), SNDCTL_DSP_POST, 0);
}
trs_restore_delay();
#endif
}
break;
case CAS_FORMAT:
if (value == FLUSH && cassette_bitnumber != 0) {
putc(cassette_byte, cassette_file);
cassette_byte = 0;
break;
}
sample = 2; /* i.e., no bit */
switch (cassette_pulsestate) {
case ST_INITIAL:
if (cassette_value == 2 && value == 0) {
/* Low speed, end of first pulse. Assume clock */
cassette_pulsestate = ST_500GOTCLK;
} else if (cassette_value == 2 && value == 1) {
/* High speed, nothing interesting yet. */
cassette_pulsestate = ST_1500;
}
break;
case ST_500GOTCLK:
if (cassette_value == 0 && value == 1) {
/* Low speed, start of next pulse. */
if (ddelta_us > ST_250THRESH) {
/* Oops, really ultra-low speed */
/* It's the next clock; bit was 0 */
sample = 0;
/* Watch for end of this clock */
cassette_pulsestate = ST_250;
} else if (ddelta_us > ST_500THRESH) {
/* It's the next clock; bit was 0 */
sample = 0;
/* Watch for end of this clock */
cassette_pulsestate = ST_INITIAL;
} else {
/* It's a data pulse; bit was 1 */
sample = 1;
/* Ignore the data pulse falling edge */
cassette_pulsestate = ST_500GOTDAT;
}
}
break;
case ST_500GOTDAT:
if (cassette_value == 2 && value == 0) {
/* End of data pulse; watch for end of next clock */
cassette_pulsestate = ST_INITIAL;
}
break;
case ST_1500:
if (cassette_value == 1 && value == 2) {
sample = (ddelta_us < ST_1500THRESH);
}
break;
case ST_250:
if (cassette_value == 2 && value == 0) {
/* Ultra-low speed, end of first pulse. Assume clock */
cassette_pulsestate = ST_250GOTCLK;
}
break;
case ST_250GOTCLK:
if (cassette_value == 0 && value == 1) {
/* Low speed, start of next pulse. */
if (ddelta_us > ST_250THRESH) {
/* It's the next clock; bit was 0 */
sample = 0;
/* Watch for end of this clock */
cassette_pulsestate = ST_250;
} else {
/* It's a data pulse; bit was 1 */
sample = 1;
/* Ignore the data pulse falling edge */
cassette_pulsestate = ST_250GOTDAT;
}
}
break;
case ST_250GOTDAT:
if (cassette_value == 2 && value == 0) {
/* End of data pulse; watch for end of next clock */
cassette_pulsestate = ST_250;
}
break;
}
if (sample == 2) break;
cassette_bitnumber--;
if (cassette_bitnumber < 0) cassette_bitnumber = 7;
cassette_byte |= (sample << cassette_bitnumber);
if (cassette_bitnumber == 0) {
putc(cassette_byte, cassette_file);
cassette_byte = 0;
}
break;
default:
error("output format %s not implemented",
cassette_format < (int)(sizeof(format_name)/sizeof(char *)) ?
format_name[cassette_format] : "out of range;");
break;
}
sigprocmask(SIG_SETMASK, &oldset, NULL);
if (cassette_value != value) last_sound = z80_state.t_count;
cassette_transition = z80_state.t_count;
cassette_value = value;
}
/* Read a new transition, updating cassette_next and cassette_delta.
If file read fails (perhaps due to eof), return 0, else 1.
Set cassette_delta to (unsigned long) -1 on failure. */
static int
transition_in(void)
{
unsigned long delta_us, nsamples, maxsamples;
Ushort code;
Uint d;
int next, ret = 0;
int c, cabs;
float delta_ts;
sigset_t set, oldset;
sigemptyset(&set);
sigaddset(&set, SIGALRM);
sigprocmask(SIG_BLOCK, &set, &oldset);
switch (cassette_format) {
case DEBUG_FORMAT:
if (fscanf(cassette_file, "%d %lu\n", &next, &delta_us) == 2) {
delta_ts = delta_us * z80_state.clockMHz - cassette_roundoff_error;
cassette_delta = (unsigned long)(delta_ts + 0.5);
cassette_roundoff_error = cassette_delta - delta_ts;
cassette_next = next;
#if CASSDEBUG
debug("%d %4lu %d\n", cassette_value, cassette_delta, cassette_next);
#endif
ret = 1;
}
break;
case CPT_FORMAT:
c = get_twobyte(&code, cassette_file);
if (c == -1) break;
if (code == 0xffff) {
c = getc(cassette_file);
if (c == EOF) break;
cassette_next = c;
c = get_fourbyte(&d, cassette_file);
if (c == -1) break;
delta_us = d;
} else {
cassette_next = code & 3;
delta_us = code >> 2;
}
delta_ts = delta_us * z80_state.clockMHz - cassette_roundoff_error;
cassette_delta = (unsigned long)(delta_ts + 0.5);
cassette_roundoff_error = cassette_delta - delta_ts;
#if CASSDEBUG
debug("%d %4lu %d\n", cassette_value, cassette_delta, cassette_next);
#endif
ret = 1;
break;
case DIRECT_FORMAT:
case WAV_FORMAT:
nsamples = 0;
maxsamples = cassette_sample_rate / 100;
do {
int direct = (cassette_format == DIRECT_FORMAT);
c = get_sample(direct, cassette_file);
if (direct && cassette_stereo) {
/* Discard right channel */
(void) get_sample(direct, cassette_file);
}
if (c == EOF) goto fail;
if (c > 127 + cassette_noisefloor) {
next = 1;
} else if (c <= 127 - cassette_noisefloor) {
next = 2;
} else {
next = 0;
}
if (cassette_speed == SPEED_1500) {
cassette_noisefloor = 2;
} else {
/* Attempt to learn the correct noise cutoff adaptively.
* This code is just a hack; it would be nice to know a
* real signal-processing algorithm for this application
*/
cabs = abs(c - 127);
#if CASSDEBUG2
debug("%f %f %d %d -> %d\n", cassette_avg, cassette_env,
cassette_noisefloor, cabs, next);
#endif
if (cabs > 1) {
cassette_avg = (99*cassette_avg + cabs)/100;
}
if (cabs > cassette_env) {
cassette_env = (cassette_env + 9*cabs)/10;
} else if (cabs > 10) {
cassette_env = (99*cassette_env + cabs)/100;
}
cassette_noisefloor = (cassette_avg + cassette_env)/2;
}
nsamples++;
/* Allow reset button */
trs_get_event(FALSE);
if (z80_state.nmi) break;
} while (next == cassette_value && maxsamples-- > 0);
cassette_next = next;
delta_ts = nsamples * (1000000.0/cassette_sample_rate)
* z80_state.clockMHz - cassette_roundoff_error;
cassette_delta = (unsigned long) delta_ts + 0.5;
cassette_roundoff_error = cassette_delta - delta_ts;
#if CASSDEBUG
debug("%3lu -> %d %4lu %d\n",
nsamples, cassette_value, cassette_delta, cassette_next);
#endif
ret = 1;
break;
case CAS_FORMAT:
if (cassette_pulsestate == 0) {
cassette_bitnumber--;
}
if (cassette_bitnumber < 0) {
c = getc(cassette_file);
if (c == EOF) {
/* Add one extra zero byte to work around an apparent bug
in the Vavasour Model I emulator's .CAS files */
if (cassette_byte == 0x100) goto fail;
c = 0x100;
}
cassette_byte = c;
cassette_bitnumber = 7;
}
c = (cassette_byte >> cassette_bitnumber) & 1;
delta_us =
pulse_shape[cassette_speed][c][cassette_pulsestate].delta_us;
cassette_next =
pulse_shape[cassette_speed][c][cassette_pulsestate].next;
cassette_pulsestate++;
if (pulse_shape[cassette_speed][c][cassette_pulsestate].next == -1) {
cassette_pulsestate = 0;
/* Kludge to emulate extra delay that's needed after the initial
0xA5 sync byte to let Basic execute the CLEAR routine.