forked from rtl-airband/RTLSDR-Airband
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrtl_airband.cpp
More file actions
1645 lines (1535 loc) · 58.9 KB
/
Copy pathrtl_airband.cpp
File metadata and controls
1645 lines (1535 loc) · 58.9 KB
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
/*
* RTLSDR AM demodulator and streaming
*
* Copyright (c) 2014 Wong Man Hang <microtony@gmail.com>
* Copyright (c) 2015-2016 Tomasz Lemiech <szpajder@gmail.com>
*
* 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 3 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/>.
*/
#define RTL_AIRBAND_VERSION "2.1.0"
#if defined USE_BCM_VC && !defined __arm__
#error Broadcom VideoCore support can only be enabled on ARM builds
#endif
// From this point we may safely assume that USE_BCM_VC implies __arm__
#if defined _WIN32
#define WIN32_LEAN_AND_MEAN
#define _USE_MATH_DEFINES
#include <SDKDDKVer.h>
#include <windows.h>
#include <process.h>
#include <complex>
#include <MMSystem.h>
#include <xmmintrin.h>
#define ALIGN __declspec(align(32))
#define ALIGN2
#define SLEEP(x) Sleep(x)
#define THREAD HANDLE
#define GOTOXY(x, y) { COORD xy; xy.X = x; xy.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), xy); }
#define scanf scanf_s
#define sscanf sscanf_s
#define fscanf fscanf_s
#define CFGFILE "rtl_airband.conf"
#elif defined __arm__
#ifdef USE_BCM_VC
#include "hello_fft/mailbox.h"
#include "hello_fft/gpu_fft.h"
#else
#include <fftw3.h>
#endif
#else /* x86 */
#include <xmmintrin.h>
#include <fftw3.h>
#endif /* x86 */
#ifndef _WIN32
#define ALIGN
#define ALIGN2 __attribute__((aligned(32)))
#define SLEEP(x) usleep(x * 1000)
#define THREAD pthread_t
#define GOTOXY(x, y) printf("%c[%d;%df",0x1B,y,x)
#ifndef SYSCONFDIR
#define SYSCONFDIR "/usr/local/etc"
#endif
#define CFGFILE SYSCONFDIR "/rtl_airband.conf"
#define PIDFILE "/run/rtl_airband.pid"
#define AUTO_GAIN -100
#include <unistd.h>
#include <pthread.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <algorithm>
#include <csignal>
#include <cstdarg>
#include <cerrno>
#endif /* !_WIN32 */
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <libconfig.h++>
#include <ogg/ogg.h>
#include <vorbis/vorbisenc.h>
#include <shout/shout.h>
#ifdef _WIN32
#include <lame.h>
#else
#include <lame/lame.h>
#endif
#include <rtl-sdr.h>
#define BUF_SIZE 2560000
#define SOURCE_RATE 2560000
#ifdef NFM
#define WAVE_RATE 16000
#else
#define WAVE_RATE 8000
#endif
#define WAVE_BATCH WAVE_RATE / 8
#define AGC_EXTRA WAVE_RATE / 160
#define WAVE_LEN 2 * WAVE_BATCH + AGC_EXTRA
#define MP3_RATE 8000
#define MAX_SHOUT_QUEUELEN 32768
#define CHANNELS 8
#define FFT_SIZE_LOG 9
#define LAMEBUF_SIZE 22000 //todo: calculate
#if defined USE_BCM_VC
struct sample_fft_arg
{
int fft_size_by4;
GPU_FFT_COMPLEX* dest;
};
extern "C" void samplefft(sample_fft_arg *a, unsigned char* buffer, float* window, float* levels);
# define FFT_BATCH 250
#else
# define FFT_BATCH 1
#endif
#define FFT_SIZE (2<<(FFT_SIZE_LOG - 1))
//#define AFC_LOGGING
#if defined _WIN32
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#endif /* _WIN32 */
using namespace std;
using namespace libconfig;
enum output_type { O_ICECAST, O_FILE };
struct output_t {
enum output_type type;
bool enabled;
bool active;
void *data;
};
struct icecast_data {
const char *hostname;
int port;
const char *username;
const char *password;
const char *mountpoint;
const char *name;
const char *genre;
shout_t *shout;
};
struct file_data {
const char *dir;
const char *prefix;
char *suffix;
bool continuous;
bool append;
FILE *f;
};
enum modulations {
MOD_AM
#ifdef NFM
, MOD_NFM
#endif
};
struct channel_t {
float wavein[WAVE_LEN]; // FFT output waveform
float waveout[WAVE_LEN]; // waveform after squelch + AGC
#ifdef NFM
float complex_samples[2*WAVE_LEN]; // raw samples for NFM demod
float timeref_nsin[WAVE_RATE];
float timeref_cos[WAVE_RATE];
int wavecnt; // sample counter for timeref shift
// FIXME: get this from complex_samples?
float pr; // previous sample - real part
float pj; // previous sample - imaginary part
float alpha;
#endif
enum modulations modulation;
int agcsq; // squelch status, 0 = signal, 1 = suppressed
float agcavgfast; // average power, for AGC
float agcavgslow; // average power, for squelch level detection
float agcmin; // noise level
int sqlevel; // manually configured squelch level
int agclow; // low level sample count
char axcindicate; // squelch/AFC status indicator: ' ' - no signal; '*' - has signal; '>', '<' - signal tuned by AFC
unsigned char afc; //0 - AFC disabled; 1 - minimal AFC; 2 - more aggressive AFC and so on to 255
int frequency;
int freq_count;
int *freqlist;
int output_count;
output_t *outputs;
lame_t lame;
};
enum rec_modes { R_MULTICHANNEL, R_SCAN };
struct device_t {
unsigned char buffer[BUF_SIZE + FFT_SIZE * 2 + 48];
int bufs;
int bufe;
rtlsdr_dev_t* rtlsdr;
int device;
int centerfreq;
int correction;
int gain;
#ifdef NFM
float alpha;
#endif
int channel_count;
int base_bins[8];
int bins[8];
channel_t channels[8];
int waveend;
int waveavail;
THREAD rtl_thread;
THREAD controller_thread;
int row;
int failed;
enum rec_modes mode;
};
device_t* devices;
int device_count;
volatile int device_opened = 0;
int rtlsdr_buffers = 10;
#ifdef _WIN32
int avx;
#endif
int foreground = 0, do_syslog = 1;
static volatile int do_exit = 0;
#ifdef NFM
float alpha = exp(-1.0f/(WAVE_RATE * 2e-4));
enum fm_demod_algo {
FM_FAST_ATAN2,
FM_QUADRI_DEMOD
};
enum fm_demod_algo fm_demod = FM_FAST_ATAN2;
#endif
void error() {
#ifdef _WIN32
system("pause");
#endif
exit(1);
}
int atomic_inc(volatile int *pv)
{
#ifdef _WIN32
return InterlockedIncrement((volatile LONG *)pv);
#else
return __sync_fetch_and_add(pv, 1);
#endif
}
int atomic_dec(volatile int *pv)
{
#ifdef _WIN32
return InterlockedDecrement((volatile LONG *)pv);
#else
return __sync_fetch_and_sub(pv, 1);
#endif
}
int atomic_get(volatile int *pv)
{
#ifdef _WIN32
return InterlockedCompareExchange((volatile LONG *)pv, 0, 0);
#else
return __sync_fetch_and_add(pv, 0);
#endif
}
void log(int priority, const char *format, ...) {
va_list args;
va_start(args, format);
#ifdef _WIN32
if(!foreground)
vprintf(format, args);
#else
if(do_syslog)
vsyslog(priority, format, args);
else if(foreground)
vprintf(format, args);
#endif
va_end(args);
}
void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx) {
if(do_exit) return;
device_t *dev = (device_t*)ctx;
memcpy(dev->buffer + dev->bufe, buf, len);
if (dev->bufe == 0) {
memcpy(dev->buffer + BUF_SIZE, buf, FFT_SIZE * 2);
}
dev->bufe = dev->bufe + len;
if (dev->bufe == BUF_SIZE) dev->bufe = 0;
}
#ifdef _WIN32
BOOL WINAPI sighandler(int sig) {
if (CTRL_C_EVENT == sig) {
log(LOG_NOTICE, "Got signal %d, exiting\n", sig);
do_exit = 1;
return TRUE;
}
return FALSE;
}
#else
void sighandler(int sig) {
log(LOG_NOTICE, "Got signal %d, exiting\n", sig);
do_exit = 1;
}
#endif
#ifdef _WIN32
void rtlsdr_exec(void* params) {
#else
void* rtlsdr_exec(void* params) {
#endif
int r;
device_t *dev = (device_t*)params;
dev->rtlsdr = NULL;
rtlsdr_open(&dev->rtlsdr, dev->device);
if (NULL == dev->rtlsdr) {
log(LOG_ERR, "Failed to open rtlsdr device #%d.\n", dev->device);
error();
return NULL;
}
r = rtlsdr_set_sample_rate(dev->rtlsdr, SOURCE_RATE);
if (r < 0) log(LOG_ERR, "Failed to set sample rate for device #%d. Error %d.\n", dev->device, r);
r = rtlsdr_set_center_freq(dev->rtlsdr, dev->centerfreq);
if (r < 0) log(LOG_ERR, "Failed to set center freq for device #%d. Error %d.\n", dev->device, r);
r = rtlsdr_set_freq_correction(dev->rtlsdr, dev->correction);
if (r < 0 && r != -2 ) log(LOG_ERR, "Failed to set freq correction for device #%d. Error %d.\n", dev->device, r);
if(dev->gain == AUTO_GAIN) {
r = rtlsdr_set_tuner_gain_mode(dev->rtlsdr, 0);
if (r < 0)
log(LOG_ERR, "Failed to set automatic gain for device #%d. Error %d.\n", dev->device, r);
else
log(LOG_INFO, "Device #%d: gain set to automatic\n", dev->device);
} else {
r = rtlsdr_set_tuner_gain_mode(dev->rtlsdr, 1);
r |= rtlsdr_set_tuner_gain(dev->rtlsdr, dev->gain);
if (r < 0)
log(LOG_ERR, "Failed to set gain to %0.2f for device #%d. Error %d.\n", (float)rtlsdr_get_tuner_gain(dev->rtlsdr) / 10.0, dev->device, r);
else
log(LOG_INFO, "Device #%d: gain set to %0.2f dB\n", dev->device, (float)rtlsdr_get_tuner_gain(dev->rtlsdr) / 10.0);
}
r = rtlsdr_set_agc_mode(dev->rtlsdr, 0);
if (r < 0) log(LOG_ERR, "Failed to disable AGC for device #%d. Error %d.\n", dev->device, r);
rtlsdr_reset_buffer(dev->rtlsdr);
log(LOG_INFO, "Device %d started.\n", dev->device);
atomic_inc(&device_opened);
dev->failed = 0;
if(rtlsdr_read_async(dev->rtlsdr, rtlsdr_callback, params, rtlsdr_buffers, 320000) < 0) {
log(LOG_WARNING, "Device #%d: async read failed, disabling\n", dev->device);
dev->failed = 1;
atomic_dec(&device_opened);
}
return 0;
}
void shout_setup(icecast_data *icecast) {
int ret;
shout_t * shouttemp = shout_new();
if (shouttemp == NULL) {
printf("cannot allocate\n");
}
if (shout_set_host(shouttemp, icecast->hostname) != SHOUTERR_SUCCESS) {
shout_free(shouttemp); return;
}
if (shout_set_protocol(shouttemp, SHOUT_PROTOCOL_HTTP) != SHOUTERR_SUCCESS) {
shout_free(shouttemp); return;
}
if (shout_set_port(shouttemp, icecast->port) != SHOUTERR_SUCCESS) {
shout_free(shouttemp); return;
}
char mp[100];
#ifdef _WIN32
sprintf_s(mp, 80, "/%s", icecast->mountpoint);
#else
sprintf(mp, "/%s", icecast->mountpoint);
#endif
if (shout_set_mount(shouttemp, mp) != SHOUTERR_SUCCESS) {
shout_free(shouttemp); return;
}
if (shout_set_user(shouttemp, icecast->username) != SHOUTERR_SUCCESS) {
shout_free(shouttemp); return;
}
if (shout_set_password(shouttemp, icecast->password) != SHOUTERR_SUCCESS) {
shout_free(shouttemp); return;
}
if (shout_set_format(shouttemp, SHOUT_FORMAT_MP3) != SHOUTERR_SUCCESS){
shout_free(shouttemp); return;
}
if(icecast->name && shout_set_name(shouttemp, icecast->name) != SHOUTERR_SUCCESS) {
shout_free(shouttemp); return;
}
if(icecast->genre && shout_set_genre(shouttemp, icecast->genre) != SHOUTERR_SUCCESS) {
shout_free(shouttemp); return;
}
char samplerates[20];
#ifdef _WIN32
sprintf_s(samplerates, 15, "%d", MP3_RATE);
#else
sprintf(samplerates, "%d", MP3_RATE);
#endif
shout_set_audio_info(shouttemp, SHOUT_AI_SAMPLERATE, samplerates);
shout_set_audio_info(shouttemp, SHOUT_AI_CHANNELS, "1");
if (shout_set_nonblocking(shouttemp, 1) != SHOUTERR_SUCCESS) {
log(LOG_ERR, "Error setting non-blocking mode: %s\n", shout_get_error(shouttemp));
return;
}
ret = shout_open(shouttemp);
if (ret == SHOUTERR_SUCCESS)
ret = SHOUTERR_CONNECTED;
if (ret == SHOUTERR_BUSY)
log(LOG_NOTICE, "Connecting to %s:%d/%s...\n",
icecast->hostname, icecast->port, icecast->mountpoint);
while (ret == SHOUTERR_BUSY) {
usleep(10000);
ret = shout_get_connected(shouttemp);
}
if (ret == SHOUTERR_CONNECTED) {
log(LOG_NOTICE, "Connected to %s:%d/%s\n",
icecast->hostname, icecast->port, icecast->mountpoint);
SLEEP(100);
icecast->shout = shouttemp;
} else {
log(LOG_WARNING, "Could not connect to %s:%d/%s\n",
icecast->hostname, icecast->port, icecast->mountpoint);
shout_free(shouttemp);
return;
}
}
lame_t airlame_init() {
lame_t lame = lame_init();
if (!lame) {
log(LOG_WARNING, "lame_init failed\n");
return NULL;
}
lame_set_in_samplerate(lame, WAVE_RATE);
lame_set_VBR(lame, vbr_mtrh);
lame_set_brate(lame, 16);
lame_set_quality(lame, 7);
lame_set_out_samplerate(lame, MP3_RATE);
lame_set_num_channels(lame, 1);
lame_set_mode(lame, MONO);
lame_init_params(lame);
return lame;
}
class LameTone
{
unsigned char* _data;
int _bytes;
public:
LameTone(int msec, unsigned int hz = 0) : _data(NULL), _bytes(0) {
_data = (unsigned char *)malloc(LAMEBUF_SIZE);
if (!_data) {
log(LOG_WARNING, "LameTone: can't alloc %u bytes\n", LAMEBUF_SIZE);
return;
}
int samples = (msec * WAVE_RATE) / 1000;
float *buf = (float *)malloc(samples * sizeof(float));
if (!buf) {
log(LOG_WARNING, "LameTone: can't alloc %u samples\n", samples);
return;
}
if (hz > 0) {
const float period = 1.0 / (float)hz;
const float sample_time = 1.0 / (float)WAVE_RATE;
float t = 0;
for (int i = 0; i < samples; ++i, t+= sample_time) {
buf[i] = 0.9 * sinf(t * 2.0 * M_PI / period);
}
} else
memset(buf, 0, samples * sizeof(float));
lame_t lame = airlame_init();
if (lame) {
_bytes = lame_encode_buffer_ieee_float(lame, buf, NULL, samples, _data, LAMEBUF_SIZE);
if (_bytes > 0) {
int flush_ofs = _bytes;
if (flush_ofs&0x1f)
flush_ofs+= 0x20 - (flush_ofs&0x1f);
if (flush_ofs < LAMEBUF_SIZE) {
int flush_bytes = lame_encode_flush(lame, _data + flush_ofs, LAMEBUF_SIZE - flush_ofs);
if (flush_bytes > 0) {
memmove(_data + _bytes, _data + flush_ofs, flush_bytes);
_bytes+= flush_bytes;
}
}
}
else
log(LOG_WARNING, "lame_encode_buffer_ieee_float: %d\n", _bytes);
lame_close(lame);
}
free(buf);
}
~LameTone() {
if (_data)
free(_data);
}
int write(FILE *f) {
if (!_data || _bytes<=0)
return 1;
if(fwrite(_data, 1, _bytes, f) != (unsigned int)_bytes) {
log(LOG_WARNING, "LameTone: failed to write %d bytes\n", _bytes);
return -1;
}
return 0;
}
};
static int fdata_open(file_data *fdata, const char *filename) {
fdata->f = fopen(filename, fdata->append ? "a+" : "w");
if(fdata->f == NULL)
return -1;
struct stat st = {0};
if (!fdata->append || fstat(fileno(fdata->f), &st)!=0 || st.st_size == 0) {
log(LOG_INFO, "Writing to %s\n", filename);
return 0;
}
log(LOG_INFO, "Appending from pos %llu to %s\n", (unsigned long long)st.st_size, filename);
//fill missing space with marker tones
LameTone lt_a(120, 2222);
LameTone lt_b(120, 1111);
LameTone lt_c(120, 555);
int r = lt_a.write(fdata->f);
if (r==0) r = lt_b.write(fdata->f);
if (r==0) r = lt_c.write(fdata->f);
if (fdata->continuous) {
time_t now = time(NULL);
if (now > st.st_mtime ) {
time_t delta = now - st.st_mtime;
if (delta > 3600) {
log(LOG_WARNING, "Too big time difference: %llu sec, limiting to one hour\n", (unsigned long long)delta);
delta = 3600;
}
LameTone lt_silence(1000);
for (; (r==0 && delta > 1); --delta)
r = lt_silence.write(fdata->f);
}
}
if (r==0) r = lt_c.write(fdata->f);
if (r==0) r = lt_b.write(fdata->f);
if (r==0) r = lt_a.write(fdata->f);
if (r<0) fseek(fdata->f, st.st_size, SEEK_SET);
return 0;
}
unsigned char lamebuf[LAMEBUF_SIZE];
void process_outputs(channel_t* channel) {
int bytes = lame_encode_buffer_ieee_float(channel->lame, channel->waveout, NULL, WAVE_BATCH, lamebuf, LAMEBUF_SIZE);
if (bytes < 0) {
log(LOG_WARNING, "lame_encode_buffer_ieee_float: %d\n", bytes);
return;
} else if (bytes == 0)
return;
for (int k = 0; k < channel->output_count; k++) {
if(channel->outputs[k].enabled == false) continue;
if(channel->outputs[k].type == O_ICECAST) {
icecast_data *icecast = (icecast_data *)(channel->outputs[k].data);
if(icecast->shout == NULL) continue;
int ret = shout_send(icecast->shout, lamebuf, bytes);
if (ret != SHOUTERR_SUCCESS || shout_queuelen(icecast->shout) > MAX_SHOUT_QUEUELEN) {
if (shout_queuelen(icecast->shout) > MAX_SHOUT_QUEUELEN)
log(LOG_WARNING, "Exceeded max backlog for %s:%d/%s, disconnecting\n",
icecast->hostname, icecast->port, icecast->mountpoint);
// reset connection
log(LOG_WARNING, "Lost connection to %s:%d/%s\n",
icecast->hostname, icecast->port, icecast->mountpoint);
shout_close(icecast->shout);
shout_free(icecast->shout);
icecast->shout = NULL;
}
} else if(channel->outputs[k].type == O_FILE) {
file_data *fdata = (file_data *)(channel->outputs[k].data);
if(fdata->continuous == false && channel->axcindicate == ' ' && channel->outputs[k].active == false) continue;
time_t t = time(NULL);
struct tm *tmp = gmtime(&t);
char suffix[32];
if(strftime(suffix, sizeof(suffix), "_%Y%m%d_%H.mp3", tmp) == 0) {
log(LOG_NOTICE, "strftime returned 0\n");
continue;
}
if(fdata->suffix == NULL || strcmp(suffix, fdata->suffix)) { // need to open new file
fdata->suffix = strdup(suffix);
char *filename = (char *)malloc(strlen(fdata->dir) + strlen(fdata->prefix) + strlen(fdata->suffix) + 2);
if(filename == NULL) {
log(LOG_WARNING, "process_outputs: cannot allocate memory, output disabled\n");
channel->outputs[k].enabled = false;
continue;
}
sprintf(filename, "%s/%s%s", fdata->dir, fdata->prefix, fdata->suffix);
if(fdata->f != NULL) {
//todo: finalize file stream with lame_encode_flush_nogap
fclose(fdata->f);
fdata->f = NULL;
}
int r = fdata_open(fdata, filename);
free(filename);
if (r<0) {
log(LOG_WARNING, "Cannot open output file %s (%s), output disabled\n", filename, strerror(errno));
channel->outputs[k].enabled = false;
continue;
}
}
// bytes is signed, but we've checked for negative values earlier
// so it's save to ignore the warning here
#pragma GCC diagnostic ignored "-Wsign-compare"
if(fwrite(lamebuf, 1, bytes, fdata->f) < bytes) {
#pragma GCC diagnostic warning "-Wsign-compare"
if(ferror(fdata->f))
log(LOG_WARNING, "Cannot write to %s/%s%s (%s), output disabled\n",
fdata->dir, fdata->prefix, fdata->suffix, strerror(errno));
else
log(LOG_WARNING, "Short write on %s/%s%s, output disabled\n",
fdata->dir, fdata->prefix, fdata->suffix);
fclose(fdata->f);
fdata->f = NULL;
channel->outputs[k].enabled = false;
}
channel->outputs[k].active = (channel->axcindicate != ' ');
}
}
}
#ifndef _WIN32
pthread_cond_t mp3_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mp3_mutex = PTHREAD_MUTEX_INITIALIZER;
void* output_thread(void* params) {
while (!do_exit) {
pthread_cond_wait(&mp3_cond, &mp3_mutex);
for (int i = 0; i < device_count; i++) {
if (!devices[i].failed && devices[i].waveavail) {
devices[i].waveavail = 0;
for (int j = 0; j < devices[i].channel_count; j++) {
channel_t* channel = devices[i].channels + j;
process_outputs(channel);
memcpy(channel->waveout, channel->waveout + WAVE_BATCH, AGC_EXTRA * 4);
}
}
}
}
return 0;
}
#endif
void* controller_thread(void* params) {
device_t *dev = (device_t*)params;
int i = 1;
int consecutive_squelch_off = 0;
if(dev->channels[0].freq_count < 2) return 0;
while(!do_exit) {
SLEEP(200);
if(dev->channels[0].axcindicate == ' ') {
if(consecutive_squelch_off < 10) {
consecutive_squelch_off++;
} else {
dev->channels[0].frequency = dev->channels[0].freqlist[i];
dev->centerfreq = dev->channels[0].freqlist[i] + 2 * (double)(SOURCE_RATE / FFT_SIZE);
rtlsdr_set_center_freq(dev->rtlsdr, dev->centerfreq);
i++; i %= dev->channels[0].freq_count;
}
} else {
consecutive_squelch_off = 0;
}
}
return 0;
}
// reconnect as required
#ifdef _WIN32
void icecast_check(void* params) {
#else
void* icecast_check(void* params) {
#endif
while (!do_exit) {
SLEEP(10000);
for (int i = 0; i < device_count; i++) {
device_t* dev = devices + i;
for (int j = 0; j < dev->channel_count; j++) {
for (int k = 0; k < dev->channels[j].output_count; k++) {
if(dev->channels[j].outputs[k].type != O_ICECAST)
continue;
icecast_data *icecast = (icecast_data *)(dev->channels[j].outputs[k].data);
if(dev->failed) {
if(icecast->shout) {
log(LOG_WARNING, "Device #%d failed, disconnecting stream %s:%d/%s\n",
i, icecast->hostname, icecast->port, icecast->mountpoint);
shout_close(icecast->shout);
shout_free(icecast->shout);
icecast->shout = NULL;
}
} else {
if (icecast->shout == NULL){
log(LOG_NOTICE, "Trying to reconnect to %s:%d/%s...\n",
icecast->hostname, icecast->port, icecast->mountpoint);
shout_setup(icecast);
}
}
}
}
}
}
#ifndef _WIN32
return 0;
#endif
}
#ifdef NFM
void multiply(float ar, float aj, float br, float bj, float *cr, float *cj)
{
*cr = ar*br - aj*bj;
*cj = aj*br + ar*bj;
}
float fast_atan2(float y, float x)
{
float yabs, angle;
float pi4=M_PI_4, pi34=3*M_PI_4;
if (x==0.0f && y==0.0f) {
return 0;
}
yabs = y;
if (yabs < 0.0f) {
yabs = -yabs;
}
if (x >= 0.0f) {
angle = pi4 - pi4 * (x-yabs) / (x+yabs);
} else {
angle = pi34 - pi4 * (x+yabs) / (yabs-x);
}
if (y < 0.0f) {
return -angle;
}
return angle;
}
float polar_disc_fast(float ar, float aj, float br, float bj)
{
float cr, cj;
multiply(ar, aj, br, -bj, &cr, &cj);
return (float)(fast_atan2(cj, cr) * M_1_PI);
}
float fm_quadri_demod(float ar, float aj, float br, float bj) {
return (float)((br*aj - ar*bj)/(ar*ar + aj*aj + 1.0f) * M_1_PI);
}
#endif
class AFC
{
const char _prev_axcindicate;
#ifdef USE_BCM_VC
float square(const GPU_FFT_COMPLEX *fft_results, int index)
{
return fft_results[index].re * fft_results[index].re + fft_results[index].im * fft_results[index].im;
}
#else
float square(const fftwf_complex *fft_results, int index)
{
return fft_results[index][0] * fft_results[index][0] + fft_results[index][1] * fft_results[index][1];
}
#endif
template <class FFT_RESULTS, int STEP>
int check(const FFT_RESULTS* fft_results, const int base, const float base_value, unsigned char afc)
{
float threshold = 0;
int bin;
for (bin = base;; bin+= STEP) {
if (STEP < 0) {
if (bin < -STEP)
break;
} else if ( (bin + STEP) >= FFT_SIZE)
break;
const float value = square(fft_results, bin + STEP);
if (value <= base_value)
break;
if (base == bin) {
threshold = (value - base_value) / (float)afc;
} else {
if ((value - base_value) < threshold)
break;
threshold+= threshold / 10.0;
}
}
return bin;
}
public:
AFC(device_t* dev, int index) : _prev_axcindicate(dev->channels[index].axcindicate)
{
}
template <class FFT_RESULTS>
void finalize(device_t* dev, int index, const FFT_RESULTS* fft_results)
{
channel_t *channel = &dev->channels[index];
if (channel->afc==0)
return;
const char axcindicate = channel->axcindicate;
if (axcindicate != ' ' && _prev_axcindicate == ' ') {
const int base = dev->base_bins[index];
const float base_value = square(fft_results, base);
int bin = check<FFT_RESULTS, -1>(fft_results, base, base_value, channel->afc);
if (bin == base)
bin = check<FFT_RESULTS, 1>(fft_results, base, base_value, channel->afc);
if (dev->bins[index] != bin) {
#ifdef AFC_LOGGING
log(LOG_INFO, "AFC device=%d channel=%d: base=%d prev=%d now=%d\n", dev->device, index, base, dev->bins[index], bin);
#endif
dev->bins[index] = bin;
if ( bin > base )
channel->axcindicate = '>';
else if ( bin < base )
channel->axcindicate = '<';
}
}
else if (axcindicate == ' ' && _prev_axcindicate != ' ')
dev->bins[index] = dev->base_bins[index];
}
};
void demodulate() {
// initialize fft engine
#ifndef USE_BCM_VC
fftwf_plan fft;
fftwf_complex* fftin;
fftwf_complex* fftout;
fftin = fftwf_alloc_complex(FFT_SIZE);
fftout = fftwf_alloc_complex(FFT_SIZE);
fft = fftwf_plan_dft_1d(FFT_SIZE, fftin, fftout, FFTW_FORWARD, FFTW_MEASURE);
#else
int mb = mbox_open();
struct GPU_FFT *fft;
int ret = gpu_fft_prepare(mb, FFT_SIZE_LOG, GPU_FFT_FWD, FFT_BATCH, &fft);
switch (ret) {
case -1: log(LOG_CRIT, "Unable to enable V3D. Please check your firmware is up to date.\n"); error();
case -2: log(LOG_CRIT, "log2_N=%d not supported. Try between 8 and 17.\n", FFT_SIZE_LOG); error();
case -3: log(LOG_CRIT, "Out of memory. Try a smaller batch or increase GPU memory.\n"); error();
}
#endif
#ifdef NFM
float rotated_r, rotated_j;
#endif
ALIGN float ALIGN2 levels[256];
for (int i=0; i<256; i++) {
levels[i] = i-127.5f;
}
// initialize fft window
// blackman 7
// the whole matrix is computed
ALIGN float ALIGN2 window[FFT_SIZE * 2];
const double a0 = 0.27105140069342f;
const double a1 = 0.43329793923448f; const double a2 = 0.21812299954311f;
const double a3 = 0.06592544638803f; const double a4 = 0.01081174209837f;
const double a5 = 0.00077658482522f; const double a6 = 0.00001388721735f;
for (int i = 0; i < FFT_SIZE; i++) {
double x = a0 - (a1 * cos((2.0 * M_PI * i) / (FFT_SIZE-1)))
+ (a2 * cos((4.0 * M_PI * i) / (FFT_SIZE - 1)))
- (a3 * cos((6.0 * M_PI * i) / (FFT_SIZE - 1)))
+ (a4 * cos((8.0 * M_PI * i) / (FFT_SIZE - 1)))
- (a5 * cos((10.0 * M_PI * i) / (FFT_SIZE - 1)))
+ (a6 * cos((12.0 * M_PI * i) / (FFT_SIZE - 1)));
window[i * 2] = window[i * 2 + 1] = (float)x;
}
// speed2 = number of bytes per wave sample (x 2 for I and Q)
int speed2 = (SOURCE_RATE * 2) / WAVE_RATE;
int device_num = 0;
while (true) {
if(do_exit) {
#ifdef USE_BCM_VC
log(LOG_INFO, "Freeing GPU memory\n");
gpu_fft_release(fft);
#endif
return;
}
device_t* dev = devices + device_num;
int available = dev->bufe - dev->bufs;
if (dev->bufe < dev->bufs) {
available = (BUF_SIZE - dev->bufe) + dev->bufs;
}
if(atomic_get(&device_opened)==0) {
log(LOG_ERR, "All receivers failed, exiting\n");
do_exit = 1;
continue;
}
if (dev->failed) {
// move to next device
device_num = (device_num + 1) % device_count;
continue;
} else if (available < speed2 * FFT_BATCH + FFT_SIZE * 2) {
// move to next device
device_num = (device_num + 1) % device_count;
SLEEP(10);
continue;
}
#if defined USE_BCM_VC
sample_fft_arg sfa = {FFT_SIZE / 4, fft->in};
for (int i = 0; i < FFT_BATCH; i++) {
samplefft(&sfa, dev->buffer + dev->bufs + i * speed2, window, levels);
sfa.dest+= fft->step;
}
#elif defined __arm__
for (int i = 0; i < FFT_SIZE; i++) {
unsigned char* buf2 = dev->buffer + dev->bufs + i * 2;
fftin[i][0] = levels[*(buf2)] * window[i*2];
fftin[i][1] = levels[*(buf2+1)] * window[i*2];
}
#elif defined _WIN32
// process 4 rtl samples (16 bytes)
if (avx) {
for (int i = 0; i < FFT_SIZE; i += 4) {
unsigned char* buf2 = dev->buffer + dev->bufs + i * 2;
__m256 a = _mm256_set_ps(levels[*(buf2+7)], levels[*(buf2+6)], levels[*(buf2+5)], levels[*(buf2+4)], levels[*(buf2+3)], levels[*(buf2+2)], levels[*(buf2+1)], levels[*(buf2)]);
__m256 b = _mm256_load_ps(&window[i * 2]);
a = _mm256_mul_ps(a, b);
_mm_prefetch((const CHAR *)&window[i * 2 + 128], _MM_HINT_T0);
_mm_prefetch((const CHAR *)buf2 + 128, _MM_HINT_T0);
_mm256_store_ps(&fftin[i][0], a);
}
} else {
for (int i = 0; i < FFT_SIZE; i += 2) {
unsigned char* buf2 = dev->buffer + dev->bufs + i * 2;
__m128 a = _mm_set_ps(levels[*(buf2 + 3)], levels[*(buf2 + 2)], levels[*(buf2 + 1)], levels[*(buf2)]);
__m128 b = _mm_load_ps(&window[i * 2]);
a = _mm_mul_ps(a, b);
_mm_store_ps(&fftin[i][0], a);
}
}
#else /* x86 */
for (int i = 0; i < FFT_SIZE; i += 2) {
unsigned char* buf2 = dev->buffer + dev->bufs + i * 2;
__m128 a = _mm_set_ps(levels[*(buf2 + 3)], levels[*(buf2 + 2)], levels[*(buf2 + 1)], levels[*(buf2)]);
__m128 b = _mm_load_ps(&window[i * 2]);
a = _mm_mul_ps(a, b);
_mm_store_ps(&fftin[i][0], a);
}
#endif