-
Notifications
You must be signed in to change notification settings - Fork 1
/
sbagen.c
3256 lines (2842 loc) · 85.2 KB
/
sbagen.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
//
// SBaGen - Sequenced Binaural Beat Generator
//
// (c) 1999-2007 Jim Peters <[email protected]>. All Rights Reserved.
// For latest version see http://sbagen.sf.net/ or
// http://uazu.net/sbagen/. Released under the GNU GPL version 2.
// Use at your own risk.
//
// " 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, version 2.
//
// 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. "
//
// See the file COPYING for details of this license.
//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// Some code fragments in the Win32 audio handling are based on
// code from PLIB (c) 2001 by Steve Baker, originally released
// under the LGPL (slDSP.cxx and sl.h). For the original source,
// see the PLIB project: http://plib.sf.net
//
// The code for the Mac audio output was based on code from the
// FINK project's patches to ESounD, by Shawn Hsiao and Masanori
// Sekino. See: http://fink.sf.net
#define VERSION "1.4.4"
// This should be built with one of the following target macros
// defined, which selects options for that platform, or else with some
// of the individual named flags #defined as listed later.
//
// T_LINUX To build the LINUX version with /dev/dsp support
// T_MINGW To build for Windows using MinGW and Win32 calls
// T_MSVC To build for Windows using MSVC and Win32 calls
// T_MACOSX To build for MacOSX using CoreAudio
// T_POSIX To build for simple file output on any Posix-compliant OS
//
// Ogg and MP3 support is handled separately from the T_* macros.
// Define OSS_AUDIO to use /dev/dsp for audio output
// Define WIN_AUDIO to use Win32 calls
// Define MAC_AUDIO to use Mac CoreAudio calls
// Define NO_AUDIO if no audio output device is usable
// Define UNIX_TIME to use UNIX calls for getting time
// Define WIN_TIME to use Win32 calls for getting time
// Define ANSI_TTY to use ANSI sequences to clear/redraw lines
// Define UNIX_MISC to use UNIX calls for various miscellaneous things
// Define WIN_MISC to use Windows calls for various miscellaneous things
// Define EXIT_KEY to require the user to hit RETURN before exiting after error
// Define OGG_DECODE to include OGG support code
// Define MP3_DECODE to include MP3 support code
#ifdef T_LINUX
#define OSS_AUDIO
#define UNIX_TIME
#define UNIX_MISC
#define ANSI_TTY
#endif
#ifdef T_MINGW
#define WIN_AUDIO
#define WIN_TIME
#define WIN_MISC
#define EXIT_KEY
#endif
#ifdef T_MSVC
#define WIN_AUDIO
#define WIN_TIME
#define WIN_MISC
#define EXIT_KEY
#endif
#ifdef T_MACOSX
#define MAC_AUDIO
#define UNIX_TIME
#define UNIX_MISC
#define ANSI_TTY
#endif
#ifdef T_POSIX
#define NO_AUDIO
#define UNIX_TIME
#define UNIX_MISC
#endif
// Make sure NO_AUDIO is set if necessary
#ifndef OSS_AUDIO
#ifndef MAC_AUDIO
#ifndef WIN_AUDIO
#define NO_AUDIO
#endif
#endif
#endif
// Make sure one of the _TIME macros is set
#ifndef UNIX_TIME
#ifndef WIN_TIME
#error UNIX_TIME or WIN_TIME not defined. Maybe you did not define one of T_LINUX/T_MINGW/T_MACOSX/etc ?
#endif
#endif
// Make sure one of the _MISC macros is set
#ifndef UNIX_MISC
#ifndef WIN_MISC
#error UNIX_MISC or WIN_MISC not defined. Maybe you did not define one of T_LINUX/T_MINGW/T_MACOSX/etc ?
#endif
#endif
#include <stdio.h>
#include <math.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#ifdef T_MSVC
#include <io.h>
#define write _write
#define vsnprintf _vsnprintf
typedef long long S64; // I have no idea if this is correct for MSVC
#else
#include <unistd.h>
#include <sys/time.h>
typedef long long S64;
#endif
#ifdef T_MINGW
#define vsnprintf _vsnprintf
#endif
#ifdef OSS_AUDIO
#include <linux/soundcard.h>
//WAS: #include <sys/soundcard.h>
#endif
#ifdef WIN_AUDIO
#include <windows.h>
#include <mmsystem.h>
#endif
#ifdef MAC_AUDIO
#include <Carbon.h>
#include <CoreAudio/CoreAudio.h>
#endif
#ifdef UNIX_TIME
#include <sys/ioctl.h>
#include <sys/times.h>
#endif
#ifdef UNIX_MISC
#include <pthread.h>
#endif
typedef struct Channel Channel;
typedef struct Voice Voice;
typedef struct Period Period;
typedef struct NameDef NameDef;
typedef struct BlockDef BlockDef;
typedef unsigned char uchar;
int inbuf_loop(void *vp) ;
int inbuf_read(int *dst, int dlen) ;
void inbuf_start(int(*rout)(int*,int), int len) ;
inline int t_per24(int t0, int t1) ;
inline int t_per0(int t0, int t1) ;
inline int t_mid(int t0, int t1) ;
int main(int argc, char **argv) ;
void status(char *) ;
void dispCurrPer( FILE* ) ;
void init_sin_table() ;
void debug(char *fmt, ...) ;
void warn(char *fmt, ...) ;
void * Alloc(size_t len) ;
char * StrDup(char *str) ;
inline int calcNow() ;
void loop() ;
void outChunk() ;
void corrVal(int ) ;
int readLine() ;
char * getWord() ;
void badSeq() ;
void readSeqImm(int ac, char **av) ;
void readSeq(int ac, char **av) ;
void readPreProg(int ac, char **av) ;
void correctPeriods();
void setup_device(void) ;
void readNameDef();
void readTimeLine();
int voicesEq(Voice *, Voice *);
void error(char *fmt, ...) ;
int sprintTime(char *, int);
int sprintVoice(char *, Voice *, Voice *);
int readTime(char *, int *);
void writeWAV();
void writeOut(char *, int);
void sinc_interpolate(double *, int, int *);
inline int userTime();
void find_wav_data_start(FILE *in);
int raw_mix_in(int *dst, int dlen);
int scanOptions(int *acp, char ***avp);
void handleOptions(char *p);
void setupOptC(char *spec) ;
extern int out_rate, out_rate_def;
void create_drop(int ac, char **av);
void create_slide(int ac, char **av);
#define ALLOC_ARR(cnt, type) ((type*)Alloc((cnt) * sizeof(type)))
#define uint unsigned int
#ifdef OGG_DECODE
#include "oggdec.c"
#endif
#ifdef MP3_DECODE
#include "mp3dec.c"
#endif
#ifdef WIN_AUDIO
void CALLBACK win32_audio_callback(HWAVEOUT, UINT, DWORD, DWORD, DWORD);
#endif
#ifdef MAC_AUDIO
OSStatus mac_callback(AudioDeviceID, const AudioTimeStamp *, const AudioBufferList *,
const AudioTimeStamp *, AudioBufferList *, const AudioTimeStamp *,
void *inClientData);
#endif
#define NL "\n"
void
help() {
printf("SBaGen - Sequenced Binaural Beat Generator, version " VERSION
NL "Copyright (c) 1999-2007 Jim Peters, http://uazu.net/, all rights "
NL " reserved, released under the GNU GPL v2. See file COPYING."
NL
NL "Usage: sbagen [options] seq-file ..."
NL " sbagen [options] -i tone-specs ..."
NL " sbagen [options] -p pre-programmed-sequence-specs ..."
NL
NL "Options: -h Display this help-text"
NL " -Q Quiet - don't display running status"
NL " -D Display the full interpreted sequence instead of playing it"
NL " -i Immediate. Take the remainder of the command line to be"
NL " tone-specifications, and play them continuously"
NL " -p Pre-programmed sequence. Take the remainder of the command"
NL " line to be a type and arguments, e.g. \"drop 00ds+\""
NL " -q mult Quick. Run through quickly (real time x 'mult') from the"
NL " start time, rather than wait for real time to pass"
NL
NL " -r rate Select the output rate (default is 44100 Hz, or from -m)"
#ifndef MAC_AUDIO
NL " -b bits Select the number bits for output (8 or 16, default 16)"
#endif
NL " -L time Select the length of time (hh:mm or hh:mm:ss) to output"
NL " for. Default is to output forever."
NL " -S Output from the first tone-set in the sequence (Start),"
NL " instead of working in real-time. Equivalent to '-q 1'."
NL " -E Output until the last tone-set in the sequence (End),"
NL " instead of outputting forever."
NL " -T time Start at the given clock-time (hh:mm)"
NL
NL " -o file Output raw data to the given file instead of /dev/dsp"
NL " -O Output raw data to the standard output"
NL " -W Output a WAV-format file instead of raw data"
NL " -m file Read audio data from the given file and mix it with the"
NL " generated binaural beats; may be "
#ifdef OGG_DECODE
"ogg/"
#endif
#ifdef MP3_DECODE
"mp3/"
#endif
"wav/raw format"
NL " -M Read raw audio data from the standard input and mix it"
NL " with the generated binaural beats (raw only)"
NL
NL " -R rate Select rate in Hz that frequency changes are recalculated"
NL " (for file/pipe output only, default is 10Hz)"
NL " -F fms Fade in/out time in ms (default 60000ms, or 1min)"
#ifdef OSS_AUDIO
NL " -d dev Select a different output device instead of /dev/dsp"
#endif
NL " -c spec Compensate for low-frequency headphone roll-off; see docs"
NL
);
exit(0);
}
void
usage() {
error("SBaGen - Sequenced Binaural Beat Generator, version " VERSION
NL "Copyright (c) 1999-2007 Jim Peters, http://uazu.net/, all rights "
NL " reserved, released under the GNU GPL v2. See file COPYING."
NL
NL "Usage: sbagen [options] seq-file ..."
NL " sbagen [options] -i tone-specs ..."
NL " sbagen [options] -p pre-programmed-sequence-specs ..."
NL
NL "For full usage help, type 'sbagen -h'. For latest version see"
NL "http://uazu.net/sbagen/ or http://sbagen.sf.net/"
#ifdef EXIT_KEY
NL
NL "Windows users please note that this utility is designed to be run as the"
NL "associated application for SBG files. This should have been set up for you by"
NL "the installer. You can run all the SBG files directly from the desktop by"
NL "double-clicking on them, and edit them using NotePad from the right-click menu."
NL "Alternatively, SBaGen may be run from the MS-DOS prompt (CMD on WinXP), or from"
NL "BAT files. SBaGen is powerful software -- it is worth the effort of figuring"
NL "all this out. See SBAGEN.TXT for the full documentation."
NL
NL "Editing the SBG files gives you access to the full tweakable power of SBaGen, "
NL "but if you want a simple GUI interface to the most basic features, you could "
NL "look at a user-contributed tool called SBaGUI:"
NL
NL " http://sbagen.opensrc.org/wiki.php?page=SBaGUI"
#endif
NL);
}
#define DEBUG_CHK_UTIME 0 // Check how much user time is being consumed
#define DEBUG_DUMP_WAVES 0 // Dump out wave tables (to plot with gnuplot)
#define DEBUG_DUMP_AMP 0 // Dump output amplitude to stdout per chunk
#define N_CH 16 // Number of channels
struct Voice {
int typ; // Voice type: 0 off, 1 binaural, 2 pink noise, 3 bell, 4 spin,
// 5 mix, 6 mixspin, 7 mixbeat, -1 to -100 wave00 to wave99
double amp; // Amplitude level (0-4096 for 0-100%)
double carr; // Carrier freq (for binaural/bell), width (for spin)
double res; // Resonance freq (-ve or +ve) (for binaural/spin)
};
struct Channel {
Voice v; // Current voice setting (updated from current period)
int typ; // Current type: 0 off, 1 binaural, 2 pink noise, 3 bell, 4 spin,
// 5 mix, 6 mixspin, 7 mixbeat, -1 to -100 wave00 to wave99
int amp, amp2; // Current state, according to current type
int inc1, off1; // :: (for binaural tones, offset + increment into sine
int inc2, off2; // :: table * 65536)
};
struct Period {
Period *nxt, *prv; // Next/prev in chain
int tim; // Start time (end time is ->nxt->tim)
Voice v0[N_CH], v1[N_CH]; // Start and end voices
int fi, fo; // Temporary: Fade-in, fade-out modes
};
struct NameDef {
NameDef *nxt;
char *name; // Name of definition
BlockDef *blk; // Non-zero for block definition
Voice vv[N_CH]; // Voice-set for it (unless a block definition)
};
struct BlockDef {
BlockDef *nxt; // Next in chain
char *lin; // StrDup'd line
};
#define ST_AMP 0x7FFFF // Amplitude of wave in sine-table
#define NS_ADJ 12 // Noise is generated internally with amplitude ST_AMP<<NS_ADJ
#define NS_DITHER 16 // How many bits right to shift the noise for dithering
#define NS_AMP (ST_AMP<<NS_ADJ)
#define ST_SIZ 16384 // Number of elements in sine-table (power of 2)
int *sin_table;
#define AMP_DA(pc) (40.96 * (pc)) // Display value (%age) to ->amp value
#define AMP_AD(amp) ((amp) / 40.96) // Amplitude value to display %age
int *waves[100]; // Pointers are either 0 or point to a sin_table[]-style array of int
Channel chan[N_CH]; // Current channel states
int now; // Current time (milliseconds from midnight)
Period *per= 0; // Current period
NameDef *nlist; // Full list of name definitions
int *tmp_buf; // Temporary buffer for 20-bit mix values
short *out_buf; // Output buffer
int out_bsiz; // Output buffer size (bytes)
int out_blen; // Output buffer length (samples) (1.0* or 0.5* out_bsiz)
int out_bps; // Output bytes per sample (2 or 4)
int out_buf_ms; // Time to output a buffer-ful in ms
int out_buf_lo; // Time to output a buffer-ful, fine-tuning in ms/0x10000
int out_fd; // Output file descriptor
int out_rate= 44100; // Sample rate
int out_rate_def= 1; // Sample rate is default value, not set by user
int out_mode= 1; // Output mode: 0 unsigned char[2], 1 short[2], 2 swapped short[2]
int out_prate= 10; // Rate of parameter change (for file and pipe output only)
int fade_int= 60000; // Fade interval (ms)
FILE *in; // Input sequence file
int in_lin; // Current input line
char buf[4096]; // Buffer for current line
char buf_copy[4096]; // Used to keep unmodified copy of line
char *lin; // Input line (uses buf[])
char *lin_copy; // Copy of input line
double spin_carr_max; // Maximum 'carrier' value for spin (really max width in us)
#define NS_BIT 10
int ns_tbl[1<<NS_BIT];
int ns_off= 0;
int fast_tim0= -1; // First time mentioned in the sequence file (for -q and -S option)
int fast_tim1= -1; // Last time mentioned in the sequence file (for -E option)
int fast_mult= 0; // 0 to sync to clock (adjusting as necessary), or else sync to
// output rate, with the multiplier indicated
S64 byte_count= -1; // Number of bytes left to output, or -1 if unlimited
int tty_erase; // Chars to erase from current line (for ESC[K emulation)
int opt_D;
int opt_M;
int opt_Q;
int opt_S;
int opt_E;
int opt_W;
int opt_O;
int opt_L= -1; // Length in ms, or -1
int opt_T= -1; // Start time in ms, or -1
char *opt_o; // File name to output to, or 0
char *opt_m; // File name to read mix data from, or 0
char *opt_d= "/dev/dsp"; // Output device
FILE *mix_in; // Input stream for mix sound data, or 0
int mix_cnt; // Version number from mix filename (#<digits>), or -1
int bigendian; // Is this platform Big-endian?
int mix_flag= 0; // Has 'mix/*' been used in the sequence?
int opt_c; // Number of -c option points provided (max 16)
struct AmpAdj {
double freq, adj;
} ampadj[16]; // List of maximum 16 (freq,adj) pairs, freq-increasing order
char *pdir; // Program directory (used as second place to look for -m files)
#ifdef WIN_AUDIO
#define BUFFER_COUNT 8
#define BUFFER_SIZE 8192*4
HWAVEOUT aud_handle;
WAVEHDR *aud_head[BUFFER_COUNT];
int aud_current; // Current header
int aud_cnt; // Number of headers in use
#endif
#ifdef MAC_AUDIO
#define BUFFER_COUNT 8
#define BUFFER_SIZE 4096*4
char aud_buf[BUFFER_COUNT][BUFFER_SIZE];
int aud_rd; // Next buffer to read out of list (to send to device)
int aud_wr; // Next buffer to write. aud_rd==aud_wr means empty buffer list
static AudioDeviceID aud_dev;
#endif
//
// Delay for a short period of time (in ms)
//
#ifdef UNIX_MISC
void
delay(int ms) {
struct timespec ts;
ts.tv_sec= ms / 1000;
ts.tv_nsec= (ms % 1000) * 1000000;
nanosleep(&ts, 0);
}
#endif
#ifdef WIN_MISC
void
delay(int ms) {
Sleep(ms);
}
#endif
//
// WAV/OGG/MP3 input data buffering
//
int *inbuf; // Buffer for input data (as 20-bit samples)
int ib_len; // Length of input buffer (in ints)
volatile int ib_rd; // Read-offset in inbuf
volatile int ib_wr; // Write-offset in inbuf
volatile int ib_eof; // End of file flag
int ib_cycle= 100; // Time in ms for a complete loop through the buffer
int (*ib_read)(int*,int); // Routine to refill buffer
int
inbuf_loop(void *vp) {
int now= -1;
int waited= 0; // Used to bail out if the main thread dies for some reason
int a;
while (1) {
int rv;
int rd= ib_rd;
int wr= ib_wr;
int cnt= (rd-1-wr) & (ib_len-1);
if (cnt > ib_len-wr) cnt= ib_len-wr;
if (cnt > ib_len/8) cnt= ib_len/8;
// Choose to only work in ib_len/8 units, although this is not
// 100% necessary
if (cnt < ib_len/8) {
// Wait a little while for the buffer to empty (minimum 1ms)
if (waited > 10000 + ib_cycle)
error("Mix stream halted for more than 10 seconds; aborting");
delay(a= 1+ib_cycle/4);
waited += a;
continue;
}
waited= 0;
rv= ib_read(inbuf+wr, cnt);
//debug("ib_read %d-%d (%d) -> %d", wr, wr+cnt-1, cnt, rv);
if (rv != cnt) {
ib_eof= 1;
return 0;
}
ib_wr= (wr + rv) & (ib_len-1);
// Whenever we roll over, recalculate 'ib_cycle'
if (ib_wr < wr) {
int prev= now;
now= calcNow();
if (prev >= 0 && now > prev)
ib_cycle= now - prev;
//debug("Input buffer cycle duration is now %dms", ib_cycle);
}
}
return 0;
}
//
// Read a chunk of int data from the input buffer. This will
// always return enough data unless we have hit the end of the
// file, in which case it returns a lower number or 0. If not
// enough data has been read by the input thread, then this
// thread pauses until data is ready -- but this should hopefully
// never happen.
//
int
inbuf_read(int *dst, int dlen) {
int rv= 0;
int waited= 0; // As a precaution, bail out if other thread hangs for some reason
int a;
while (dlen > 0) {
int rd= ib_rd;
int wr= ib_wr;
int avail= (wr-rd) & (ib_len-1);
int toend= ib_len-rd;
if (avail > toend) avail= toend;
if (avail > dlen) avail= dlen;
if (avail == 0) {
if (ib_eof) return rv;
// Necessary to wait for incoming mix data. This should
// never happen in normal running, though, unless we are
// outputting to a file
if (waited > 10000)
error("Mix stream problem; waited more than 10 seconds for data; aborting");
//debug("Waiting for input thread (%d)", ib_eof);
delay(a= ib_cycle/4 > 100 ? 100 : 1+ib_cycle/4);
waited += a;
continue;
}
waited= 0;
memcpy(dst, inbuf+rd, avail * sizeof(int));
dst += avail;
dlen -= avail;
rv += avail;
ib_rd= (rd + avail) & (ib_len-1);
}
return rv;
}
//
// Start off the thread that fills the buffer
//
void
inbuf_start(int(*rout)(int*,int), int len) {
if (0 != (len & (len-1)))
error("inbuf_start() called with length not a power of two");
ib_read= rout;
ib_len= len;
inbuf= ALLOC_ARR(ib_len, int);
ib_rd= 0;
ib_wr= 0;
ib_eof= 0;
if (!opt_Q) warn("Initialising %d-sample buffer for mix stream", ib_len/2);
// Preload 75% of the buffer -- or at least attempt to do so;
// errors/eof/etc will be picked up in the inbuf_loop() routine
ib_wr= ib_read(inbuf, ib_len*3/4);
// Start the thread off
#ifdef UNIX_MISC
{
pthread_t thread;
if (0 != pthread_create(&thread, NULL, (void*)&inbuf_loop, NULL))
error("Failed to start input buffering thread");
}
#endif
#ifdef WIN_MISC
{
DWORD tmp;
if (0 == CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&inbuf_loop, 0, 0, &tmp))
error("Failed to start input buffering thread");
}
#endif
}
//
// Time-keeping functions
//
#define H24 (86400000) // 24 hours
#define H12 (43200000) // 12 hours
inline int t_per24(int t0, int t1) { // Length of period starting at t0, ending at t1.
int td= t1 - t0; // NB for t0==t1 this gives 24 hours, *NOT 0*
return td > 0 ? td : td + H24;
}
inline int t_per0(int t0, int t1) { // Length of period starting at t0, ending at t1.
int td= t1 - t0; // NB for t0==t1 this gives 0 hours
return td >= 0 ? td : td + H24;
}
inline int t_mid(int t0, int t1) { // Midpoint of period from t0 to t1
return ((t1 < t0) ? (H24 + t0 + t1) / 2 : (t0 + t1) / 2) % H24;
}
//
// M A I N
//
int
main(int argc, char **argv) {
short test= 0x1100;
int rv;
char *p;
pdir= StrDup(argv[0]);
p= strchr(pdir, 0);
while (p > pdir && p[-1] != '/' && p[-1] != '\\') *--p= 0;
argc--; argv++;
init_sin_table();
bigendian= ((char*)&test)[0] != 0;
// Process all the options
rv= scanOptions(&argc, &argv);
if (argc < 1) usage();
if (rv == 'i') {
// Immediate mode
readSeqImm(argc, argv);
} else if (rv == 'p') {
// Pre-programmed sequence
readPreProg(argc, argv);
} else {
// Sequenced mode -- sequence may include options, so options
// are not settled until below this point
if (argc < 1) usage();
readSeq(argc, argv);
}
if (opt_W && !opt_o && !opt_O)
error("Use -o or -O with the -W option");
if (opt_W && opt_L < 0 && !opt_E) {
fprintf(stderr, "*** The length has not been specified for the -W option; assuming 1 hour ***\n");
fprintf(stderr, "(Use -L or -E with the -W option to control the length of the WAV file)\n\n");
opt_L= 60*60*1000;
}
mix_in= 0;
if (opt_M || opt_m) {
char *p;
char tmp[4];
int raw= 1;
if (opt_M) {
mix_in= stdin;
tmp[0]= 0;
}
if (opt_m) {
// Pick up #<digits> on end of filename
p= strchr(opt_m, 0);
mix_cnt= -1;
if (p > opt_m && isdigit(p[-1])) {
mix_cnt= 0;
while (p > opt_m && isdigit(p[-1]))
mix_cnt= mix_cnt * 10 + *--p - '0';
if (p > opt_m && p[-1] == '#')
*--p= 0;
else {
p= strchr(opt_m, 0);
mix_cnt= -1;
}
}
// p points to end of filename (NUL)
// Open file
mix_in= fopen(opt_m, "rb");
if (!mix_in && opt_m[0] != '/') {
int len= strlen(opt_m) + strlen(pdir) + 1;
char *tmp= ALLOC_ARR(len, char);
strcpy(tmp, pdir);
strcat(tmp, opt_m);
mix_in= fopen(tmp, "rb");
free(tmp);
}
if (!mix_in)
error("Can't open -m option mix input file: %s", opt_m);
// Pick up extension
if (p-opt_m >= 4 && p[-4] == '.') {
tmp[0]= tolower(p[-3]);
tmp[1]= tolower(p[-2]);
tmp[2]= tolower(p[-1]);
tmp[3]= 0;
}
}
if (0 == strcmp(tmp, "wav")) // Skip header on WAV files
find_wav_data_start(mix_in);
if (0 == strcmp(tmp, "ogg")) {
#ifdef OGG_DECODE
ogg_init(); raw= 0;
#else
error("Sorry: Ogg support wasn't compiled into this executable");
#endif
}
if (0 == strcmp(tmp, "mp3")) {
#ifdef MP3_DECODE
mp3_init(); raw= 0;
#else
error("Sorry: MP3 support wasn't compiled into this executable");
#endif
}
// If this is a raw/wav data stream, setup a 256*1024-int
// buffer ([email protected])
if (raw) inbuf_start(raw_mix_in, 256*1024);
}
loop();
return 0;
}
//
// Scan options. Returns a flag indicating what is expected to
// interpret the rest of the arguments: 0 normal, 'i' immediate
// (-i option), 'p' -p option.
//
int
scanOptions(int *acp, char ***avp) {
int argc= *acp;
char **argv= *avp;
int val;
char dmy;
int rv= 0;
// Scan options
while (argc > 0 && argv[0][0] == '-' && argv[0][1]) {
char opt, *p= 1 + *argv++; argc--;
while ((opt= *p++)) {
// Check options that are available on both
switch (opt) {
case 'Q': opt_Q= 1; break;
case 'E': opt_E= 1; break;
case 'm':
if (argc-- < 1) error("-m option expects filename");
// Earliest takes precedence, so command-line overrides sequence file
if (!opt_m) opt_m= *argv++;
break;
case 'S': opt_S= 1;
if (!fast_mult) fast_mult= 1; // Don't try to sync with real time
break;
case 'L':
if (argc-- < 1 || 0 == (val= readTime(*argv, &opt_L)) ||
1 == sscanf(*argv++ + val, " %c", &dmy))
error("-L expects hh:mm or hh:mm:ss time");
break;
case 'T':
if (argc-- < 1 || 0 == (val= readTime(*argv, &opt_T)) ||
1 == sscanf(*argv++ + val, " %c", &dmy))
error("-T expects hh:mm or hh:mm:ss time");
if (!fast_mult) fast_mult= 1; // Don't try to sync with real time
break;
case 'F':
if (argc-- < 1 || 1 != sscanf(*argv++, "%d %c", &fade_int, &dmy))
error("-F expects fade-time in ms");
break;
case 'c':
if (argc-- < 1) error("-c expects argument");
setupOptC(*argv++);
break;
case 'i': rv= 'i'; break;
case 'p': rv= 'p'; break;
case 'h': help(); break;
case 'D': opt_D= 1; break;
case 'M': opt_M= 1; break;
case 'O': opt_O= 1;
if (!fast_mult) fast_mult= 1; // Don't try to sync with real time
break;
case 'W': opt_W= 1;
if (!fast_mult) fast_mult= 1; // Don't try to sync with real time
break;
case 'q':
opt_S= 1;
if (argc-- < 1 || 1 != sscanf(*argv++, "%d %c", &fast_mult, &dmy))
error("Expecting an integer after -q");
if (fast_mult < 1) fast_mult= 1;
break;
case 'r':
if (argc-- < 1 || 1 != sscanf(*argv++, "%d %c", &out_rate, &dmy))
error("Expecting an integer after -r");
out_rate_def= 0;
break;
#ifndef MAC_AUDIO
case 'b':
if (argc-- < 1 ||
1 != sscanf(*argv++, "%d %c", &val, &dmy) ||
!(val == 8 || val == 16))
error("Expecting -b 8 or -b 16");
out_mode= (val == 8) ? 0 : 1;
break;
#endif
case 'o':
if (argc-- < 1) error("Expecting filename after -o");
opt_o= *argv++;
if (!fast_mult) fast_mult= 1; // Don't try to sync with real time
break;
#ifdef OSS_AUDIO
case 'd':
if (argc-- < 1) error("Expecting device filename after -d");
opt_d= *argv++;
break;
#endif
case 'R':
if (argc-- < 1 || 1 != sscanf(*argv++, "%d %c", &out_prate, &dmy))
error("Expecting integer after -R");
break;
default:
error("Option -%c not known; run 'sbagen -h' for help", opt);
}
}
}
*acp= argc;
*avp= argv;
return rv;
}
//
// Handle an option string, breaking it into an (argc/argv) list
// for scanOptions.
//
void
handleOptions(char *str0) {
// Always StrDup() string and don't bother to free(), as normal
// argv[] strings stick around for the life of the program
char *str= StrDup(str0);
int const max_argc= 32;
char *argv[max_argc+1];
int argc= 0;
while (*str) {
if (argc >= max_argc)
error("Too many options at line: %d\n %s", in_lin, lin_copy);
argv[argc++]= str;
while (*str && !isspace(*str)) str++;
if (!*str) continue;
*str++= 0; // NUL-term this word
while (isspace(*str)) str++;
}
argv[argc]= 0; // Terminate argv list with a NULL
// Process the options
{
char **av= argv;
int ac= argc;
int rv;
rv= scanOptions(&ac, &av);
if (rv == 'i') {
// Immediate mode
readSeqImm(ac, av);
} else if (rv == 'p') {
// Pre-programmed sequence
readPreProg(ac, av);
} else if (ac)
error("Trailing garbage after options at line: %d\n %s", in_lin, lin_copy);
}
}
//
// Setup the ampadj[] array from the given -c spec-string
//
void
setupOptC(char *spec) {
char *p= spec, *q;
int a, b;
while (1) {
while (isspace(*p) || *p == ',') p++;
if (!*p) break;
if (opt_c >= sizeof(ampadj) / sizeof(ampadj[0]))
error("Too many -c option frequencies; maxmimum is %d",
sizeof(ampadj) / sizeof(ampadj[0]));
ampadj[opt_c].freq= strtod(p, &q);
if (p == q) goto bad;
if (*q++ != '=') goto bad;
ampadj[opt_c].adj= strtod(q, &p);
if (p == q) goto bad;
opt_c++;
}
// Sort the list
for (a= 0; a<opt_c; a++)
for (b= a+1; b<opt_c; b++)
if (ampadj[a].freq > ampadj[b].freq) {
double tmp;
tmp= ampadj[a].freq; ampadj[a].freq= ampadj[b].freq; ampadj[b].freq= tmp;
tmp= ampadj[a].adj; ampadj[a].adj= ampadj[b].adj; ampadj[b].adj= tmp;
}
return;
bad:
error("Bad -c option spec; expecting <freq>=<amp>[,<freq>=<amp>]...:\n %s", spec);
}
//
// If this is a WAV file we've been given, skip forward to the
// 'data' section. Don't bother checking any of the 'fmt '
// stuff. If they didn't give us a valid 16-bit stereo file at
// the right rate, then tough!
//
void
find_wav_data_start(FILE *in) {
unsigned char buf[16];
if (1 != fread(buf, 12, 1, in)) goto bad;
if (0 != memcmp(buf, "RIFF", 4)) goto bad;
if (0 != memcmp(buf+8, "WAVE", 4)) goto bad;
while (1) {
int len;
if (1 != fread(buf, 8, 1, in)) goto bad;
if (0 == memcmp(buf, "data", 4)) return; // We're in the right place!
len= buf[4] + (buf[5]<<8) + (buf[6]<<16) + (buf[7]<<24);
if (len & 1) len++;
if (out_rate_def && 0 == memcmp(buf, "fmt ", 4)) {
// Grab the sample rate to use as the default if available
if (1 != fread(buf, 8, 1, in)) goto bad;
len -= 8;
out_rate= buf[4] + (buf[5]<<8) + (buf[6]<<16) + (buf[7]<<24);
out_rate_def= 0;
}
if (0 != fseek(in, len, SEEK_CUR)) goto bad;
}
bad:
warn("WARNING: Not a valid WAV file, treating as RAW");
rewind(in);
}
//
// Input raw audio data from the 'mix_in' stream, and convert to
// 32-bit values (max 'dlen')
//
int
raw_mix_in(int *dst, int dlen) {
short *tmp= (short*)(dst + dlen/2);
int a, rv;
rv= fread(tmp, 2, dlen, mix_in);
if (rv == 0) {
if (feof(mix_in))
return 0;
error("Read error on mix input:\n %s", strerror(errno));