2 * rtl-sdr, turns your Realtek RTL2832 based DVB dongle into a SDR receiver
3 * Copyright (C) 2012 by Steve Markgraf <steve@steve-m.de>
4 * Copyright (C) 2012 by Hoernchen <la@tfc-server.de>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
28 #include <arpa/inet.h>
29 #include <sys/socket.h>
30 #include <sys/types.h>
31 #include <sys/socket.h>
33 #include <netinet/in.h>
37 #include "getopt/getopt.h"
45 #pragma comment(lib, "ws2_32.lib")
47 typedef int socklen_t;
50 #define closesocket close
51 #define SOCKADDR struct sockaddr
53 #define SOCKET_ERROR -1
58 static pthread_t tcp_worker_thread;
59 static pthread_t command_thread;
60 static pthread_cond_t exit_cond;
61 static pthread_mutex_t exit_cond_lock;
62 static volatile int dead[2] = {0, 0};
64 static pthread_mutex_t ll_mutex;
65 static pthread_cond_t cond;
73 typedef struct { /* structure size must be multiple of 2 bytes */
76 uint32_t tuner_gain_count;
79 static rtlsdr_dev_t *dev = NULL;
82 static struct llist *ll_buffers = 0;
84 static int do_exit = 0;
88 printf("rtl_tcp, an I/Q spectrum server for RTL2832 based DVB-T receivers\n\n"
89 "Usage:\t[-a listen address]\n"
90 "\t[-p listen port (default: 1234)]\n"
91 "\t[-f frequency to tune to [Hz]]\n"
92 "\t[-g gain (default: 0 for auto)]\n"
93 "\t[-s samplerate in Hz (default: 2048000 Hz)]\n"
94 "\t[-b number of buffers (default: 32, set by library)]\n"
95 "\t[-d device index (default: 0)]\n");
100 int gettimeofday(struct timeval *tv, void* ignored)
103 unsigned __int64 tmp = 0;
105 GetSystemTimeAsFileTime(&ft);
106 tmp |= ft.dwHighDateTime;
108 tmp |= ft.dwLowDateTime;
110 tmp -= 11644473600000000Ui64;
111 tv->tv_sec = (long)(tmp / 1000000UL);
112 tv->tv_usec = (long)(tmp % 1000000UL);
118 sighandler(int signum)
120 if (CTRL_C_EVENT == signum) {
121 fprintf(stderr, "Signal caught, exiting!\n");
123 rtlsdr_cancel_async(dev);
129 static void sighandler(int signum)
131 fprintf(stderr, "Signal caught, exiting!\n");
133 rtlsdr_cancel_async(dev);
139 void rtlsdr_callback(unsigned char *buf, uint32_t len, void *ctx)
142 struct llist *rpt = (struct llist*)malloc(sizeof(struct llist));
143 rpt->data = (char*)malloc(len);
144 memcpy(rpt->data, buf, len);
148 pthread_mutex_lock(&ll_mutex);
150 if (ll_buffers == NULL) {
153 struct llist *cur = ll_buffers;
156 while (cur->next != NULL) {
162 if (num_queued > global_numq)
163 printf("ll+, now %d\n", num_queued);
164 else if (num_queued < global_numq)
165 printf("ll-, now %d\n", num_queued);
167 global_numq = num_queued;
169 pthread_cond_signal(&cond);
170 pthread_mutex_unlock(&ll_mutex);
174 static void *tcp_worker(void *arg)
176 struct llist *curelem,*prev;
177 int bytesleft,bytessent, index;
178 struct timeval tv= {1,0};
188 pthread_mutex_lock(&ll_mutex);
189 gettimeofday(&tp, NULL);
190 ts.tv_sec = tp.tv_sec+5;
191 ts.tv_nsec = tp.tv_usec * 1000;
192 r = pthread_cond_timedwait(&cond, &ll_mutex, &ts);
194 pthread_mutex_unlock(&ll_mutex);
195 printf("worker cond timeout\n");
201 curelem = ll_buffers;
203 pthread_mutex_unlock(&ll_mutex);
205 while(curelem != 0) {
206 bytesleft = curelem->len;
209 while(bytesleft > 0) {
211 FD_SET(s, &writefds);
214 r = select(s+1, NULL, &writefds, NULL, &tv);
216 bytessent = send(s, &curelem->data[index], bytesleft, 0);
217 if (bytessent == SOCKET_ERROR) {
218 perror("worker socket error");
222 } else if (do_exit) {
227 bytesleft -= bytessent;
231 printf("worker socket bye\n");
238 curelem = curelem->next;
245 static int set_gain_by_index(rtlsdr_dev_t *_dev, unsigned int index)
249 int count = rtlsdr_get_tuner_gains(_dev, NULL);
251 if (count > 0 && (unsigned int)count > index) {
252 gains = malloc(sizeof(int) * count);
253 count = rtlsdr_get_tuner_gains(_dev, gains);
255 res = rtlsdr_set_tuner_gain(_dev, gains[index]);
264 #define __attribute__(x)
265 #pragma pack(push, 1)
270 }__attribute__((packed));
274 static void *command_worker(void *arg)
278 struct command cmd={0, 0};
279 struct timeval tv= {1, 0};
290 r = select(s+1, &readfds, NULL, NULL, &tv);
292 received = recv(s, (char*)&cmd+(sizeof(cmd)-left), left, 0);
293 if(received == SOCKET_ERROR){
294 perror("comm recv socket error");
306 printf("comm recv bye\n");
314 printf("set freq %d\n", ntohl(cmd.param));
315 rtlsdr_set_center_freq(dev,ntohl(cmd.param));
318 printf("set sample rate %d\n", ntohl(cmd.param));
319 rtlsdr_set_sample_rate(dev, ntohl(cmd.param));
322 printf("set gain mode %d\n", ntohl(cmd.param));
323 rtlsdr_set_tuner_gain_mode(dev, ntohl(cmd.param));
326 printf("set gain %d\n", ntohl(cmd.param));
327 rtlsdr_set_tuner_gain(dev, ntohl(cmd.param));
330 printf("set freq correction %d\n", ntohl(cmd.param));
331 rtlsdr_set_freq_correction(dev, ntohl(cmd.param));
334 tmp = ntohl(cmd.param);
335 printf("set if stage %d, gain %d\n", tmp >> 16, tmp & 0xffff);
336 rtlsdr_set_tuner_if_gain(dev, tmp >> 16, tmp & 0xffff);
339 printf("set test mode %d\n", ntohl(cmd.param));
340 rtlsdr_set_testmode(dev, ntohl(cmd.param));
343 printf("set agc mode %d\n", ntohl(cmd.param));
344 rtlsdr_set_agc_mode(dev, ntohl(cmd.param));
347 printf("set direct sampling %d\n", ntohl(cmd.param));
348 rtlsdr_set_direct_sampling(dev, ntohl(cmd.param));
351 printf("set offset tuning %d\n", ntohl(cmd.param));
352 rtlsdr_set_offset_tuning(dev, ntohl(cmd.param));
355 printf("set rtl xtal %d\n", ntohl(cmd.param));
356 rtlsdr_set_xtal_freq(dev, ntohl(cmd.param), 0);
359 printf("set tuner xtal %d\n", ntohl(cmd.param));
360 rtlsdr_set_xtal_freq(dev, 0, ntohl(cmd.param));
363 printf("set tuner gain by index %d\n", ntohl(cmd.param));
364 set_gain_by_index(dev, ntohl(cmd.param));
373 int main(int argc, char **argv)
376 char* addr = "127.0.0.1";
378 uint32_t frequency = 100000000, samp_rate = 2048000;
379 struct sockaddr_in local, remote;
381 uint32_t dev_index = 0, buf_num = 0;
383 struct llist *curelem,*prev;
386 struct timeval tv = {1,0};
387 struct linger ling = {1,0};
391 u_long blockmode = 1;
392 dongle_info_t dongle_info;
395 i = WSAStartup(MAKEWORD(2,2), &wsd);
397 struct sigaction sigact, sigign;
400 while ((opt = getopt(argc, argv, "a:p:f:g:s:b:d:")) != -1) {
403 dev_index = atoi(optarg);
406 frequency = (uint32_t)atof(optarg);
409 gain = (int)(atof(optarg) * 10); /* tenths of a dB */
412 samp_rate = (uint32_t)atof(optarg);
421 buf_num = atoi(optarg);
432 device_count = rtlsdr_get_device_count();
434 fprintf(stderr, "No supported devices found.\n");
438 printf("Found %d device(s).\n", device_count);
440 rtlsdr_open(&dev, dev_index);
442 fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
446 printf("Using %s\n", rtlsdr_get_device_name(dev_index));
448 sigact.sa_handler = sighandler;
449 sigemptyset(&sigact.sa_mask);
451 sigign.sa_handler = SIG_IGN;
452 sigaction(SIGINT, &sigact, NULL);
453 sigaction(SIGTERM, &sigact, NULL);
454 sigaction(SIGQUIT, &sigact, NULL);
455 sigaction(SIGPIPE, &sigign, NULL);
457 SetConsoleCtrlHandler( (PHANDLER_ROUTINE) sighandler, TRUE );
459 /* Set the sample rate */
460 r = rtlsdr_set_sample_rate(dev, samp_rate);
462 fprintf(stderr, "WARNING: Failed to set sample rate.\n");
464 /* Set the frequency */
465 r = rtlsdr_set_center_freq(dev, frequency);
467 fprintf(stderr, "WARNING: Failed to set center freq.\n");
469 fprintf(stderr, "Tuned to %i Hz.\n", frequency);
472 /* Enable automatic gain */
473 r = rtlsdr_set_tuner_gain_mode(dev, 0);
475 fprintf(stderr, "WARNING: Failed to enable automatic gain.\n");
477 /* Enable manual gain */
478 r = rtlsdr_set_tuner_gain_mode(dev, 1);
480 fprintf(stderr, "WARNING: Failed to enable manual gain.\n");
482 /* Set the tuner gain */
483 r = rtlsdr_set_tuner_gain(dev, gain);
485 fprintf(stderr, "WARNING: Failed to set tuner gain.\n");
487 fprintf(stderr, "Tuner gain set to %f dB.\n", gain/10.0);
490 /* Reset endpoint before we start reading from it (mandatory) */
491 r = rtlsdr_reset_buffer(dev);
493 fprintf(stderr, "WARNING: Failed to reset buffers.\n");
495 pthread_mutex_init(&exit_cond_lock, NULL);
496 pthread_mutex_init(&ll_mutex, NULL);
497 pthread_mutex_init(&exit_cond_lock, NULL);
498 pthread_cond_init(&cond, NULL);
499 pthread_cond_init(&exit_cond, NULL);
501 memset(&local,0,sizeof(local));
502 local.sin_family = AF_INET;
503 local.sin_port = htons(port);
504 local.sin_addr.s_addr = inet_addr(addr);
506 listensocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
508 setsockopt(listensocket, SOL_SOCKET, SO_REUSEADDR, (char *)&r, sizeof(int));
509 setsockopt(listensocket, SOL_SOCKET, SO_LINGER, (char *)&ling, sizeof(ling));
510 bind(listensocket,(struct sockaddr *)&local,sizeof(local));
513 ioctlsocket(listensocket, FIONBIO, &blockmode);
515 r = fcntl(listensocket, F_GETFL, 0);
516 r = fcntl(listensocket, F_SETFL, r | O_NONBLOCK);
520 printf("listening...\n");
521 printf("Use the device argument 'rtl_tcp=%s:%d' in OsmoSDR "
522 "(gr-osmosdr) source\n"
523 "to receive samples in GRC and control "
524 "rtl_tcp parameters (frequency, gain, ...).\n",
526 listen(listensocket,1);
530 FD_SET(listensocket, &readfds);
533 r = select(listensocket+1, &readfds, NULL, NULL, &tv);
537 rlen = sizeof(remote);
538 s = accept(listensocket,(struct sockaddr *)&remote, &rlen);
543 setsockopt(s, SOL_SOCKET, SO_LINGER, (char *)&ling, sizeof(ling));
545 printf("client accepted!\n");
547 memset(&dongle_info, 0, sizeof(dongle_info));
548 memcpy(&dongle_info.magic, "RTL0", 4);
550 r = rtlsdr_get_tuner_type(dev);
552 dongle_info.tuner_type = htonl(r);
554 r = rtlsdr_get_tuner_gains(dev, NULL);
556 dongle_info.tuner_gain_count = htonl(r);
558 r = send(s, (const char *)&dongle_info, sizeof(dongle_info), 0);
559 if (sizeof(dongle_info) != r)
560 printf("failed to send dongle information\n");
562 pthread_attr_init(&attr);
563 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
564 r = pthread_create(&tcp_worker_thread, &attr, tcp_worker, NULL);
565 r = pthread_create(&command_thread, &attr, command_worker, NULL);
566 pthread_attr_destroy(&attr);
568 r = rtlsdr_read_async(dev, rtlsdr_callback, NULL, buf_num, 0);
571 pthread_join(tcp_worker_thread, &status);
575 pthread_join(command_thread, &status);
580 printf("all threads dead..\n");
581 curelem = ll_buffers;
584 while(curelem != 0) {
586 curelem = curelem->next;
597 closesocket(listensocket);
603 return r >= 0 ? r : -r;