forked from wb2osz/direwolf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
audio_win.c
1171 lines (905 loc) · 31.4 KB
/
audio_win.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
//
// This file is part of Dire Wolf, an amateur radio packet TNC.
//
// Copyright (C) 2011, 2012, 2013, 2014, 2015 John Langner, WB2OSZ
//
// 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. If not, see <http://www.gnu.org/licenses/>.
//
/*------------------------------------------------------------------
*
* Module: audio_win.c
*
* Purpose: Interface to audio device commonly called a "sound card" for
* historical reasons.
*
* This version uses the native Windows sound interface.
*
* Credits: Fabrice FAURE contributed Linux code for the SDR UDP interface.
*
* Discussion here: http://gqrx.dk/doc/streaming-audio-over-udp
*
* Major revisions:
*
* 1.2 - Add ability to use more than one audio device.
*
*---------------------------------------------------------------*/
#include "direwolf.h" // Sets _WIN32_WINNT for XP API level needed by ws2tcpip.h
// Also includes windows.h.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
#include <io.h>
#include <fcntl.h>
#include <mmsystem.h>
#ifndef WAVE_FORMAT_96M16
#define WAVE_FORMAT_96M16 0x40000
#define WAVE_FORMAT_96S16 0x80000
#endif
#include <winsock2.h>
#include <ws2tcpip.h> // _WIN32_WINNT must be set to 0x0501 before including this
#include "audio.h"
#include "audio_stats.h"
#include "textcolor.h"
#include "ptt.h"
#include "demod.h" /* for alevel_t & demod_get_audio_level() */
/* Audio configuration. */
static struct audio_s *save_audio_config_p;
/*
* Allocate enough buffers for 1 second each direction.
* Each buffer size is a trade off between being responsive
* to activity on the channel vs. overhead of having too
* many little transfers.
*/
/*
* Originally, we had an abitrary buf time of 40 mS.
*
* For mono, the buffer size was rounded up from 3528 to 4k so
* it was really about 50 mS per buffer or about 20 per second.
* For stereo, the buffer size was rounded up from 7056 to 7k so
* it was really about 43.7 mS per buffer or about 23 per second.
*
* In version 1.2, let's try changing it to 10 to reduce the latency.
* For mono, the buffer size was rounded up from 882 to 1k so it
* was really about 12.5 mS per buffer or about 80 per second.
*/
#define TOTAL_BUF_TIME 1000
#define ONE_BUF_TIME 10
#define NUM_IN_BUF ((TOTAL_BUF_TIME)/(ONE_BUF_TIME))
#define NUM_OUT_BUF ((TOTAL_BUF_TIME)/(ONE_BUF_TIME))
#define roundup1k(n) (((n) + 0x3ff) & ~0x3ff)
static int calcbufsize(int rate, int chans, int bits)
{
int size1 = (rate * chans * bits / 8 * ONE_BUF_TIME) / 1000;
int size2 = roundup1k(size1);
#if DEBUG
text_color_set(DW_COLOR_DEBUG);
dw_printf ("audio_open: calcbufsize (rate=%d, chans=%d, bits=%d) calc size=%d, round up to %d\n",
rate, chans, bits, size1, size2);
#endif
/* Version 1.3 - add a sanity check. */
if (size2 < 256 || size2 > 32768) {
text_color_set(DW_COLOR_ERROR);
dw_printf ("Audio buffer has unexpected extreme size of %d bytes.\n", size2);
dw_printf ("Detected at %s, line %d.\n", __FILE__, __LINE__);
dw_printf ("This might be caused by unusual audio device configuration values.\n");
size2 = 2048;
dw_printf ("Using %d to attempt recovery.\n", size2);
}
return (size2);
}
/* Information for each audio stream (soundcard, stdin, or UDP) */
static struct adev_s {
enum audio_in_type_e g_audio_in_type;
/*
* UDP socket for receiving audio stream.
* Buffer, length, and pointer for UDP or stdin.
*/
SOCKET udp_sock;
char stream_data[SDR_UDP_BUF_MAXLEN];
int stream_len;
int stream_next;
/* For sound output. */
/* out_wavehdr.dwUser is used to keep track of output buffer state. */
#define DWU_FILLING 1 /* Ready to use or in process of being filled. */
#define DWU_PLAYING 2 /* Was given to sound system for playing. */
#define DWU_DONE 3 /* Sound system is done with it. */
HWAVEOUT audio_out_handle;
volatile WAVEHDR out_wavehdr[NUM_OUT_BUF];
int out_current; /* index to above. */
int outbuf_size;
/* For sound input. */
/* In this case dwUser is index of next available byte to remove. */
HWAVEIN audio_in_handle;
WAVEHDR in_wavehdr[NUM_IN_BUF];
volatile WAVEHDR *in_headp; /* head of queue to process. */
CRITICAL_SECTION in_cs;
} adev[MAX_ADEVS];
/*------------------------------------------------------------------
*
* Name: audio_open
*
* Purpose: Open the digital audio device.
*
* New in version 1.0, we recognize "udp:" optionally
* followed by a port number.
*
* Inputs: pa - Address of structure of type audio_s.
*
* Using a structure, rather than separate arguments
* seemed to make sense because we often pass around
* the same set of parameters various places.
*
* The fields that we care about are:
* num_channels
* samples_per_sec
* bits_per_sample
* If zero, reasonable defaults will be provided.
*
* Outputs: pa - The ACTUAL values are returned here.
*
* The Linux version adjusts strange values to the
* nearest valid value. Don't know, yet, if Windows
* does the same or just fails. Or performs some
* expensive resampling from a rate supported by
* hardware.
*
* These might not be exactly the same as what was requested.
*
* Example: ask for stereo, 16 bits, 22050 per second.
* An ordinary desktop/laptop PC should be able to handle this.
* However, some other sort of smaller device might be
* more restrictive in its capabilities.
* It might say, the best I can do is mono, 8 bit, 8000/sec.
*
* The sofware modem must use this ACTUAL information
* that the device is supplying, that could be different
* than what the user specified.
*
* Returns: 0 for success, -1 for failure.
*
* References: Multimedia Reference
*
* http://msdn.microsoft.com/en-us/library/windows/desktop/dd743606%28v=vs.85%29.aspx
*
*----------------------------------------------------------------*/
static void CALLBACK in_callback (HWAVEIN handle, UINT msg, DWORD instance, DWORD param1, DWORD param2);
static void CALLBACK out_callback (HWAVEOUT handle, UINT msg, DWORD instance, DWORD param1, DWORD param2);
int audio_open (struct audio_s *pa)
{
int a;
int err;
int chan;
int n;
int in_dev_no[MAX_ADEVS];
int out_dev_no[MAX_ADEVS];
int num_devices;
WAVEINCAPS wic;
WAVEOUTCAPS woc;
save_audio_config_p = pa;
for (a=0; a<MAX_ADEVS; a++) {
if (pa->adev[a].defined) {
struct adev_s *A = &(adev[a]);
assert (A->audio_in_handle == 0);
assert (A->audio_out_handle == 0);
//text_color_set(DW_COLOR_DEBUG);
//dw_printf ("pa->adev[a].adevice_in = '%s'\n", pa->adev[a].adevice_in);
//dw_printf ("pa->adev[a].adevice_out = '%s'\n", pa->adev[a].adevice_out);
/*
* Fill in defaults for any missing values.
*/
if (pa -> adev[a].num_channels == 0)
pa -> adev[a].num_channels = DEFAULT_NUM_CHANNELS;
if (pa -> adev[a].samples_per_sec == 0)
pa -> adev[a].samples_per_sec = DEFAULT_SAMPLES_PER_SEC;
if (pa -> adev[a].bits_per_sample == 0)
pa -> adev[a].bits_per_sample = DEFAULT_BITS_PER_SAMPLE;
A->g_audio_in_type = AUDIO_IN_TYPE_SOUNDCARD;
for (chan=0; chan<MAX_CHANS; chan++) {
if (pa -> achan[chan].mark_freq == 0)
pa -> achan[chan].mark_freq = DEFAULT_MARK_FREQ;
if (pa -> achan[chan].space_freq == 0)
pa -> achan[chan].space_freq = DEFAULT_SPACE_FREQ;
if (pa -> achan[chan].baud == 0)
pa -> achan[chan].baud = DEFAULT_BAUD;
if (pa->achan[chan].num_subchan == 0)
pa->achan[chan].num_subchan = 1;
}
A->udp_sock = INVALID_SOCKET;
in_dev_no[a] = WAVE_MAPPER; /* = ((UINT)-1) in mmsystem.h */
out_dev_no[a] = WAVE_MAPPER;
/*
* Determine the type of audio input and select device.
* This can be soundcard, UDP stream, or stdin.
*/
if (strcasecmp(pa->adev[a].adevice_in, "stdin") == 0 || strcmp(pa->adev[a].adevice_in, "-") == 0) {
A->g_audio_in_type = AUDIO_IN_TYPE_STDIN;
/* Change - to stdin for readability. */
strlcpy (pa->adev[a].adevice_in, "stdin", sizeof(pa->adev[a].adevice_in));
}
else if (strncasecmp(pa->adev[a].adevice_in, "udp:", 4) == 0) {
A->g_audio_in_type = AUDIO_IN_TYPE_SDR_UDP;
/* Supply default port if none specified. */
if (strcasecmp(pa->adev[a].adevice_in,"udp") == 0 ||
strcasecmp(pa->adev[a].adevice_in,"udp:") == 0) {
snprintf (pa->adev[a].adevice_in, sizeof(pa->adev[a].adevice_in), "udp:%d", DEFAULT_UDP_AUDIO_PORT);
}
}
else {
A->g_audio_in_type = AUDIO_IN_TYPE_SOUNDCARD;
/* Does config file have a number? */
/* If so, it is an index into list of devices. */
/* Originally only a single digit was recognized. */
/* v 1.5 also recognizes two digits. (Issue 116) */
if (strlen(pa->adev[a].adevice_in) == 1 && isdigit(pa->adev[a].adevice_in[0])) {
in_dev_no[a] = atoi(pa->adev[a].adevice_in);
}
else if (strlen(pa->adev[a].adevice_in) == 2 && isdigit(pa->adev[a].adevice_in[0]) && isdigit(pa->adev[a].adevice_in[1])) {
in_dev_no[a] = atoi(pa->adev[a].adevice_in);
}
/* Otherwise, does it have search string? */
if ((UINT)(in_dev_no[a]) == WAVE_MAPPER && strlen(pa->adev[a].adevice_in) >= 1) {
num_devices = waveInGetNumDevs();
for (n=0 ; n<num_devices && (UINT)(in_dev_no[a]) == WAVE_MAPPER ; n++) {
if ( ! waveInGetDevCaps(n, &wic, sizeof(WAVEINCAPS))) {
if (strstr(wic.szPname, pa->adev[a].adevice_in) != NULL) {
in_dev_no[a] = n;
}
}
}
if ((UINT)(in_dev_no[a]) == WAVE_MAPPER) {
text_color_set(DW_COLOR_ERROR);
dw_printf ("\"%s\" doesn't match any of the input devices.\n", pa->adev[a].adevice_in);
}
}
}
/*
* Select output device.
* Only soundcard at this point.
* Purhaps we'd like to add UDP for an SDR transmitter.
*/
if (strlen(pa->adev[a].adevice_out) == 1 && isdigit(pa->adev[a].adevice_out[0])) {
out_dev_no[a] = atoi(pa->adev[a].adevice_out);
}
else if (strlen(pa->adev[a].adevice_out) == 2 && isdigit(pa->adev[a].adevice_out[0]) && isdigit(pa->adev[a].adevice_out[1])) {
out_dev_no[a] = atoi(pa->adev[a].adevice_out);
}
if ((UINT)(out_dev_no[a]) == WAVE_MAPPER && strlen(pa->adev[a].adevice_out) >= 1) {
num_devices = waveOutGetNumDevs();
for (n=0 ; n<num_devices && (UINT)(out_dev_no[a]) == WAVE_MAPPER ; n++) {
if ( ! waveOutGetDevCaps(n, &woc, sizeof(WAVEOUTCAPS))) {
if (strstr(woc.szPname, pa->adev[a].adevice_out) != NULL) {
out_dev_no[a] = n;
}
}
}
if ((UINT)(out_dev_no[a]) == WAVE_MAPPER) {
text_color_set(DW_COLOR_ERROR);
dw_printf ("\"%s\" doesn't match any of the output devices.\n", pa->adev[a].adevice_out);
}
}
} /* if defined */
} /* for each device */
/*
* Display the input devices (soundcards) available and what is selected.
*/
text_color_set(DW_COLOR_INFO);
dw_printf ("Available audio input devices for receive (*=selected):\n");
num_devices = waveInGetNumDevs();
for (a=0; a<MAX_ADEVS; a++) {
if (pa->adev[a].defined) {
if (in_dev_no[a] < -1 || in_dev_no[a] >= num_devices) {
text_color_set(DW_COLOR_ERROR);
dw_printf ("Invalid input (receive) audio device number %d.\n", in_dev_no[a]);
in_dev_no[a] = WAVE_MAPPER;
}
}
}
text_color_set(DW_COLOR_INFO);
for (n=0; n<num_devices; n++) {
if ( ! waveInGetDevCaps(n, &wic, sizeof(WAVEINCAPS))) {
for (a=0; a<MAX_ADEVS; a++) {
if (pa->adev[a].defined) {
dw_printf (" %c", n==in_dev_no[a] ? '*' : ' ');
}
}
dw_printf (" %d: %s", n, wic.szPname);
for (a=0; a<MAX_ADEVS; a++) {
if (pa->adev[a].defined && n==in_dev_no[a]) {
if (pa->adev[a].num_channels == 2) {
dw_printf (" (channels %d & %d)", ADEVFIRSTCHAN(a), ADEVFIRSTCHAN(a)+1);
}
else {
dw_printf (" (channel %d)", ADEVFIRSTCHAN(a));
}
}
}
dw_printf ("\n");
}
}
// Add UDP or stdin to end of device list if used.
for (a=0; a<MAX_ADEVS; a++) {
if (pa->adev[a].defined) {
struct adev_s *A = &(adev[a]);
/* Display stdin or udp:port if appropriate. */
if (A->g_audio_in_type != AUDIO_IN_TYPE_SOUNDCARD) {
int aaa;
for (aaa=0; aaa<MAX_ADEVS; aaa++) {
if (pa->adev[aaa].defined) {
dw_printf (" %c", a == aaa ? '*' : ' ');
}
}
dw_printf (" %s ", pa->adev[a].adevice_in); /* should be UDP:nnnn or stdin */
if (pa->adev[a].num_channels == 2) {
dw_printf (" (channels %d & %d)", ADEVFIRSTCHAN(a), ADEVFIRSTCHAN(a)+1);
}
else {
dw_printf (" (channel %d)", ADEVFIRSTCHAN(a));
}
dw_printf ("\n");
}
}
}
/*
* Display the output devices (soundcards) available and what is selected.
*/
dw_printf ("Available audio output devices for transmit (*=selected):\n");
/* TODO? */
/* No "*" is currently displayed when using the default device. */
/* Should we put "*" next to the default device when using it? */
/* Which is the default? The first one? */
num_devices = waveOutGetNumDevs();
for (a=0; a<MAX_ADEVS; a++) {
if (pa->adev[a].defined) {
if (out_dev_no[a] < -1 || out_dev_no[a] >= num_devices) {
text_color_set(DW_COLOR_ERROR);
dw_printf ("Invalid output (transmit) audio device number %d.\n", out_dev_no[a]);
out_dev_no[a] = WAVE_MAPPER;
}
}
}
text_color_set(DW_COLOR_INFO);
for (n=0; n<num_devices; n++) {
if ( ! waveOutGetDevCaps(n, &woc, sizeof(WAVEOUTCAPS))) {
for (a=0; a<MAX_ADEVS; a++) {
if (pa->adev[a].defined) {
dw_printf (" %c", n==out_dev_no[a] ? '*' : ' ');
}
}
dw_printf (" %d: %s", n, woc.szPname);
for (a=0; a<MAX_ADEVS; a++) {
if (pa->adev[a].defined && n==out_dev_no[a]) {
if (pa->adev[a].num_channels == 2) {
dw_printf (" (channels %d & %d)", ADEVFIRSTCHAN(a), ADEVFIRSTCHAN(a)+1);
}
else {
dw_printf (" (channel %d)", ADEVFIRSTCHAN(a));
}
}
}
dw_printf ("\n");
}
}
/*
* Open for each audio device input/output pair.
*/
for (a=0; a<MAX_ADEVS; a++) {
if (pa->adev[a].defined) {
struct adev_s *A = &(adev[a]);
WAVEFORMATEX wf;
wf.wFormatTag = WAVE_FORMAT_PCM;
wf.nChannels = pa -> adev[a].num_channels;
wf.nSamplesPerSec = pa -> adev[a].samples_per_sec;
wf.wBitsPerSample = pa -> adev[a].bits_per_sample;
wf.nBlockAlign = (wf.wBitsPerSample / 8) * wf.nChannels;
wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec;
wf.cbSize = 0;
A->outbuf_size = calcbufsize(wf.nSamplesPerSec,wf.nChannels,wf.wBitsPerSample);
/*
* Open the audio output device.
* Soundcard is only possibility at this time.
*/
err = waveOutOpen (&(A->audio_out_handle), out_dev_no[a], &wf, (DWORD_PTR)out_callback, a, CALLBACK_FUNCTION);
if (err != MMSYSERR_NOERROR) {
text_color_set(DW_COLOR_ERROR);
dw_printf ("Could not open audio device for output.\n");
return (-1);
}
/*
* Set up the output buffers.
* We use dwUser to indicate it is available for filling.
*/
memset ((void*)(A->out_wavehdr), 0, sizeof(A->out_wavehdr));
for (n = 0; n < NUM_OUT_BUF; n++) {
A->out_wavehdr[n].lpData = malloc(A->outbuf_size);
A->out_wavehdr[n].dwUser = DWU_FILLING;
A->out_wavehdr[n].dwBufferLength = 0;
}
A->out_current = 0;
/*
* Open audio input device.
* More possibilities here: soundcard, UDP port, stdin.
*/
switch (A->g_audio_in_type) {
/*
* Soundcard.
*/
case AUDIO_IN_TYPE_SOUNDCARD:
InitializeCriticalSection (&(A->in_cs));
err = waveInOpen (&(A->audio_in_handle), in_dev_no[a], &wf, (DWORD_PTR)in_callback, a, CALLBACK_FUNCTION);
if (err != MMSYSERR_NOERROR) {
text_color_set(DW_COLOR_ERROR);
dw_printf ("Could not open audio device for input.\n");
return (-1);
}
/*
* Set up the input buffers.
*/
memset ((void*)(A->in_wavehdr), 0, sizeof(A->in_wavehdr));
for (n = 0; n < NUM_OUT_BUF; n++) {
A->in_wavehdr[n].dwBufferLength = A->outbuf_size; /* all the same size */
A->in_wavehdr[n].lpData = malloc(A->outbuf_size);
}
A->in_headp = NULL;
/*
* Give them to the sound input system.
*/
for (n = 0; n < NUM_OUT_BUF; n++) {
waveInPrepareHeader(A->audio_in_handle, &(A->in_wavehdr[n]), sizeof(WAVEHDR));
waveInAddBuffer(A->audio_in_handle, &(A->in_wavehdr[n]), sizeof(WAVEHDR));
}
/*
* Start it up.
* The callback function is called when one is filled.
*/
waveInStart (A->audio_in_handle);
break;
/*
* UDP.
*/
case AUDIO_IN_TYPE_SDR_UDP:
{
WSADATA wsadata;
struct sockaddr_in si_me;
//int slen=sizeof(si_me);
//int data_size = 0;
int err;
err = WSAStartup (MAKEWORD(2,2), &wsadata);
if (err != 0) {
text_color_set(DW_COLOR_ERROR);
dw_printf("WSAStartup failed: %d\n", err);
return (-1);
}
if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 2) {
text_color_set(DW_COLOR_ERROR);
dw_printf("Could not find a usable version of Winsock.dll\n");
WSACleanup();
return (-1);
}
// Create UDP Socket
A->udp_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (A->udp_sock == INVALID_SOCKET) {
text_color_set(DW_COLOR_ERROR);
dw_printf ("Couldn't create socket, errno %d\n", WSAGetLastError());
return -1;
}
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons((short)atoi(pa->adev[a].adevice_in + 4));
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
// Bind to the socket
if (bind(A->udp_sock, (SOCKADDR *) &si_me, sizeof(si_me)) != 0) {
text_color_set(DW_COLOR_ERROR);
dw_printf ("Couldn't bind socket, errno %d\n", WSAGetLastError());
return -1;
}
A->stream_next= 0;
A->stream_len = 0;
}
break;
/*
* stdin.
*/
case AUDIO_IN_TYPE_STDIN:
setmode (STDIN_FILENO, _O_BINARY);
A->stream_next= 0;
A->stream_len = 0;
break;
default:
text_color_set(DW_COLOR_ERROR);
dw_printf ("Internal error, invalid audio_in_type\n");
return (-1);
}
}
}
return (0);
} /* end audio_open */
/*
* Called when input audio block is ready.
*/
static void CALLBACK in_callback (HWAVEIN handle, UINT msg, DWORD instance, DWORD param1, DWORD param2)
{
int a = instance;
//dw_printf ("in_callback, handle = %d, a = %d\n", (int)handle, a);
assert (a >= 0 && a < MAX_ADEVS);
struct adev_s *A = &(adev[a]);
if (msg == WIM_DATA) {
WAVEHDR *p = (WAVEHDR*)param1;
p->dwUser = -1; /* needs to be unprepared. */
p->lpNext = NULL;
EnterCriticalSection (&(A->in_cs));
if (A->in_headp == NULL) {
A->in_headp = p; /* first one in list */
}
else {
WAVEHDR *last = (WAVEHDR*)(A->in_headp);
while (last->lpNext != NULL) {
last = last->lpNext;
}
last->lpNext = p; /* append to last one */
}
LeaveCriticalSection (&(A->in_cs));
}
}
/*
* Called when output system is done with a block and it
* is again available for us to fill.
*/
static void CALLBACK out_callback (HWAVEOUT handle, UINT msg, DWORD instance, DWORD param1, DWORD param2)
{
if (msg == WOM_DONE) {
WAVEHDR *p = (WAVEHDR*)param1;
p->dwBufferLength = 0;
p->dwUser = DWU_DONE;
}
}
/*------------------------------------------------------------------
*
* Name: audio_get
*
* Purpose: Get one byte from the audio device.
*
*
* Inputs: a - Audio soundcard number.
*
* Returns: 0 - 255 for a valid sample.
* -1 for any type of error.
*
* Description: The caller must deal with the details of mono/stereo
* and number of bytes per sample.
*
* This will wait if no data is currently available.
*
*----------------------------------------------------------------*/
// Use hot attribute for all functions called for every audio sample.
__attribute__((hot))
int audio_get (int a)
{
struct adev_s *A;
WAVEHDR *p;
int n;
int sample;
A = &(adev[a]);
switch (A->g_audio_in_type) {
/*
* Soundcard.
*/
case AUDIO_IN_TYPE_SOUNDCARD:
while (1) {
/*
* Wait if nothing available.
* Could use an event to wake up but this is adequate.
*/
int timeout = 25;
while (A->in_headp == NULL) {
//SLEEP_MS (ONE_BUF_TIME / 5);
SLEEP_MS (ONE_BUF_TIME);
timeout--;
if (timeout <= 0) {
text_color_set(DW_COLOR_ERROR);
// TODO1.2: Need more details. Can we keep going?
dw_printf ("Timeout waiting for input from audio device %d.\n", a);
audio_stats (a,
save_audio_config_p->adev[a].num_channels,
0,
save_audio_config_p->statistics_interval);
return (-1);
}
}
p = (WAVEHDR*)(A->in_headp); /* no need to be volatile at this point */
if (p->dwUser == (DWORD)(-1)) {
waveInUnprepareHeader(A->audio_in_handle, p, sizeof(WAVEHDR));
p->dwUser = 0; /* Index for next byte. */
audio_stats (a,
save_audio_config_p->adev[a].num_channels,
p->dwBytesRecorded / (save_audio_config_p->adev[a].num_channels * save_audio_config_p->adev[a].bits_per_sample / 8),
save_audio_config_p->statistics_interval);
}
if (p->dwUser < p->dwBytesRecorded) {
n = ((unsigned char*)(p->lpData))[p->dwUser++];
#if DEBUGx
text_color_set(DW_COLOR_DEBUG);
dw_printf ("audio_get(): returns %d\n", n);
#endif
return (n);
}
/*
* Buffer is all used up. Give it back to sound input system.
*/
EnterCriticalSection (&(A->in_cs));
A->in_headp = p->lpNext;
LeaveCriticalSection (&(A->in_cs));
p->dwFlags = 0;
waveInPrepareHeader(A->audio_in_handle, p, sizeof(WAVEHDR));
waveInAddBuffer(A->audio_in_handle, p, sizeof(WAVEHDR));
}
break;
/*
* UDP.
*/
case AUDIO_IN_TYPE_SDR_UDP:
while (A->stream_next >= A->stream_len) {
int res;
assert (A->udp_sock > 0);
res = SOCK_RECV (A->udp_sock, A->stream_data, SDR_UDP_BUF_MAXLEN);
if (res <= 0) {
text_color_set(DW_COLOR_ERROR);
dw_printf ("Can't read from udp socket, errno %d", WSAGetLastError());
A->stream_len = 0;
A->stream_next = 0;
audio_stats (a,
save_audio_config_p->adev[a].num_channels,
0,
save_audio_config_p->statistics_interval);
return (-1);
}
audio_stats (a,
save_audio_config_p->adev[a].num_channels,
res / (save_audio_config_p->adev[a].num_channels * save_audio_config_p->adev[a].bits_per_sample / 8),
save_audio_config_p->statistics_interval);
A->stream_len = res;
A->stream_next = 0;
}
sample = A->stream_data[A->stream_next] & 0xff;
A->stream_next++;
return (sample);
break;
/*
* stdin.
*/
case AUDIO_IN_TYPE_STDIN:
while (A->stream_next >= A->stream_len) {
int res;
res = read(STDIN_FILENO, A->stream_data, 1024);
if (res <= 0) {
text_color_set(DW_COLOR_INFO);
dw_printf ("\nEnd of file on stdin. Exiting.\n");
exit (0);
}
audio_stats (a,
save_audio_config_p->adev[a].num_channels,
res / (save_audio_config_p->adev[a].num_channels * save_audio_config_p->adev[a].bits_per_sample / 8),
save_audio_config_p->statistics_interval);
A->stream_len = res;
A->stream_next = 0;
}
return (A->stream_data[A->stream_next++] & 0xff);
break;
}
return (-1);
} /* end audio_get */
/*------------------------------------------------------------------
*
* Name: audio_put
*
* Purpose: Send one byte to the audio device.
*
* Inputs: a - Index for audio device.
*
* c - One byte in range of 0 - 255.
*
*
* Global In: out_current - index of output buffer currenly being filled.
*
* Returns: Normally non-negative.
* -1 for any type of error.
*
* Description: The caller must deal with the details of mono/stereo
* and number of bytes per sample.
*
* See Also: audio_flush
* audio_wait
*
*----------------------------------------------------------------*/
int audio_put (int a, int c)
{
WAVEHDR *p;
struct adev_s *A;
A = &(adev[a]);
/*
* Wait if no buffers are available.
* Don't use p yet because compiler might might consider dwFlags a loop invariant.
*/
int timeout = 10;
while ( A->out_wavehdr[A->out_current].dwUser == DWU_PLAYING) {
SLEEP_MS (ONE_BUF_TIME);
timeout--;
if (timeout <= 0) {
text_color_set(DW_COLOR_ERROR);
// TODO: open issues 78 & 165. How can we avoid/improve this?
dw_printf ("Audio output failure waiting for buffer.\n");
dw_printf ("This can occur when we are producing audio output for\n");
dw_printf ("transmit and the operating system doesn't provide buffer\n");
dw_printf ("space after waiting and retrying many times.\n");
//dw_printf ("In recent years, this has been reported only when running the\n");
//dw_printf ("Windows version with VMWare on a Macintosh.\n");
ptt_term ();
return (-1);
}
}
p = (LPWAVEHDR)(&(A->out_wavehdr[A->out_current]));
if (p->dwUser == DWU_DONE) {
waveOutUnprepareHeader (A->audio_out_handle, p, sizeof(WAVEHDR));
p->dwBufferLength = 0;
p->dwUser = DWU_FILLING;
}
/* Should never be full at this point. */
assert (p->dwBufferLength >= 0);
assert (p->dwBufferLength < (DWORD)(A->outbuf_size));
p->lpData[p->dwBufferLength++] = c;
if (p->dwBufferLength == (DWORD)(A->outbuf_size)) {
return (audio_flush(a));
}
return (0);
} /* end audio_put */
/*------------------------------------------------------------------
*
* Name: audio_flush
*
* Purpose: Send current buffer to the audio output system.
*
* Inputs: a - Index for audio device.
*
* Returns: Normally non-negative.