Debian Codegraph @

utils/rds-ctl/rds-ctl.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /*
3 * rds-ctl.cpp is based on v4l2-ctl.cpp
4 *
5 * the following applies for all RDS related parts:
6 * Copyright 2012 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
7 * Author: Konke Radlow <[email protected]>
8 */
9
10 #include <cctype>
11 #include <cerrno>
12 #include <clocale>
13 #include <cmath>
14 #include <csignal>
15 #include <cstring>
16 #include <ctime>
17 #include <map>
18 #include <string>
19 #include <vector>
20
21 #include <dirent.h>
22 #include <fcntl.h>
23 #include <getopt.h>
24 #include <sys/ioctl.h>
25 #include <unistd.h>
26
27 #include <linux/videodev2.h>
28 #include <v4l2-info.h>
29 #include <libv4l2rds.h>
30 #include <v4l-getsubopt.h>
31
32 using dev_vec = std::vector<std::string>;
33 using dev_map = std::map<std::string, std::string>;
34
35 /* Short option list
36
37 Please keep in alphabetical order.
38 That makes it easier to see which short options are still free.
39
40 In general the lower case is used to set something and the upper
41 case is used to retrieve a setting. */
42 enum Option {
43 OptRBDS = 'b',
44 OptSetDevice = 'd',
45 OptGetDriverInfo = 'D',
46 OptGetFreq = 'F',
47 OptSetFreq = 'f',
48 OptHelp = 'h',
49 OptReadRds = 'R',
50 OptGetTuner = 'T',
51 OptAll = 128,
52 OptFreqSeek,
53 OptListDevices,
54 OptListFreqBands,
55 OptOpenFile,
56 OptPrintBlock,
57 OptSilent,
58 OptTMC,
59 OptTunerIndex,
60 OptVerbose,
61 OptWaitLimit,
62 OptLast = 256
63 };
64
65 struct ctl_parameters {
66 bool terminate_decoding;
67 char options[OptLast];
68 char fd_name[80];
69 bool filemode_active;
70 double freq;
71 uint32_t wait_limit;
72 uint8_t tuner_index;
73 struct v4l2_hw_freq_seek freq_seek;
74 };
75
76 static struct ctl_parameters params;
77 static int app_result;
78
79 static struct option long_options[] = {
80 {"all", no_argument, nullptr, OptAll},
81 {"rbds", no_argument, nullptr, OptRBDS},
82 {"device", required_argument, nullptr, OptSetDevice},
83 {"file", required_argument, nullptr, OptOpenFile},
84 {"freq-seek", required_argument, nullptr, OptFreqSeek},
85 {"get-freq", no_argument, nullptr, OptGetFreq},
86 {"get-tuner", no_argument, nullptr, OptGetTuner},
87 {"help", no_argument, nullptr, OptHelp},
88 {"info", no_argument, nullptr, OptGetDriverInfo},
89 {"list-devices", no_argument, nullptr, OptListDevices},
90 {"list-freq-bands", no_argument, nullptr, OptListFreqBands},
91 {"print-block", no_argument, nullptr, OptPrintBlock},
92 {"read-rds", no_argument, nullptr, OptReadRds},
93 {"set-freq", required_argument, nullptr, OptSetFreq},
94 {"tmc", no_argument, nullptr, OptTMC},
95 {"tuner-index", required_argument, nullptr, OptTunerIndex},
96 {"silent", no_argument, nullptr, OptSilent},
97 {"verbose", no_argument, nullptr, OptVerbose},
98 {"wait-limit", required_argument, nullptr, OptWaitLimit},
99 {nullptr, 0, nullptr, 0}
100 };
101
102 static void usage_hint()
103 {
104 fprintf(stderr, "Try 'rds-ctl --help' for more information.\n");
105 }
106
107 static void usage_common()
108 {
109 printf("\nGeneral/Common options:\n"
110 " --all display all device information available\n"
111 " -D, --info show driver info [VIDIOC_QUERYCAP]\n"
112 " -d, --device <dev> use device <dev>\n"
113 " If <dev> starts with a digit, then /dev/radio<dev> is used\n"
114 " default: checks for RDS-capable devices,\n"
115 " uses device with lowest ID\n"
116 " -h, --help display this help message\n"
117 " --list-devices list all v4l radio devices with RDS capabilities\n"
118 );
119 }
120
121 static void usage_tuner()
122 {
123 printf("\nTuner/Modulator options:\n"
124 " -F, --get-freq query the frequency [VIDIOC_G_FREQUENCY]\n"
125 " -f, --set-freq <freq>\n"
126 " set the frequency to <freq> MHz [VIDIOC_S_FREQUENCY]\n"
127 " -T, --get-tuner query the tuner settings [VIDIOC_G_TUNER]\n"
128 " --tuner-index <idx> Use idx as tuner idx for tuner/modulator commands\n"
129 " --freq-seek dir=<0/1>,wrap=<0/1>,spacing=<hz>\n"
130 " perform a hardware frequency seek [VIDIOC_S_HW_FREQ_SEEK]\n"
131 " dir is 0 (seek downward) or 1 (seek upward)\n"
132 " wrap is 0 (do not wrap around) or 1 (wrap around)\n"
133 " spacing sets the seek resolution (use 0 for default)\n"
134 " --list-freq-bands display all frequency bands for the tuner/modulator\n"
135 " [VIDIOC_ENUM_FREQ_BANDS]\n"
136 );
137 }
138
139 static void usage_rds()
140 {
141 printf("\nRDS options: \n"
142 " -b, --rbds parse the RDS data according to the RBDS standard\n"
143 " -R, --read-rds enable reading of RDS data from device\n"
144 " --file <path> open a RDS stream file dump instead of a device\n"
145 " all General and Tuner Options are disabled in this mode\n"
146 " --wait-limit <ms> defines the maximum wait duration for avaibility of new\n"
147 " RDS data\n"
148 " <default>: 5000 ms\n"
149 " --print-block prints all valid RDS fields, whenever a value is updated\n"
150 " instead of printing only updated values\n"
151 " --tmc print information about TMC (Traffic Message Channel) messages\n"
152 " --silent only set the result code, do not print any messages\n"
153 " --verbose turn on verbose mode - every received RDS group\n"
154 " will be printed\n"
155 );
156 }
157
158 static void usage()
159 {
160 printf("Usage:\n");
161 usage_common();
162 usage_tuner();
163 usage_rds();
164 }
165
166 static void signal_handler_interrupt(int signum)
167 {
168 fprintf(stderr, "Interrupt received: Terminating program\n");
169 params.terminate_decoding = true;
170 }
171
172 static int doioctl_name(int fd, unsigned long int request, void *parm, const char *name)
173 {
174 int retval = ioctl(fd, request, parm);
175
176 if (retval < 0) {
177 app_result = -1;
178 }
179 if (params.options[OptSilent]) return retval;
180 if (retval < 0)
181 printf("%s: failed: %s\n", name, strerror(errno));
182 else if (params.options[OptVerbose])
183 printf("%s: ok\n", name);
184
185 return retval;
186 }
187
188 #define doioctl(n, r, p) doioctl_name(n, r, p, #r)
189
190 static bool is_radio_dev(const char *name)
191 {
192 return !memcmp(name, "radio", 5);
193 }
194
195 static void print_devices(const dev_vec& files)
196 {
197 dev_map cards;
198 int fd = -1;
199 std::string bus_info;
200 struct v4l2_capability vcap;
201
202 for (const auto &file : files) {
203 fd = open(file.c_str(), O_RDWR);
204 memset(&vcap, 0, sizeof(vcap));
205 if (fd < 0)
206 continue;
207 doioctl(fd, VIDIOC_QUERYCAP, &vcap);
208 close(fd);
209 bus_info = reinterpret_cast<const char *>(vcap.bus_info);
210 if (cards[bus_info].empty())
211 cards[bus_info] += std::string(reinterpret_cast<char *>(vcap.card))
212 + " (" + bus_info + "):\n";
213 cards[bus_info] += "\t" + file;
214 cards[bus_info] += "\n";
215 }
216 for (const auto &card : cards) {
217 printf("%s\n", card.second.c_str());
218 }
219 }
220 static dev_vec list_devices()
221 {
222 DIR *dp;
223 struct dirent *ep;
224 dev_vec files;
225 dev_vec valid_devices;
226 dev_map links;
227
228 struct v4l2_tuner vt;
229
230 dp = opendir("/dev");
231 if (dp == nullptr) {
232 perror ("Couldn't open the directory");
233 std::exit(EXIT_FAILURE);
234 }
235 while ((ep = readdir(dp)))
236 if (is_radio_dev(ep->d_name))
237 files.push_back(std::string("/dev/") + ep->d_name);
238 closedir(dp);
239
240 /* Iterate through all devices, and remove all non-accessible devices
241 * and all devices that don't offer the RDS_BLOCK_IO capability */
242 for (auto iter = files.begin();
243 iter != files.end();) {
244 int fd = open(iter->c_str(), O_RDONLY | O_NONBLOCK);
245 std::string bus_info;
246
247 if (fd < 0) {
248 iter++;
249 continue;
250 }
251 memset(&vt, 0, sizeof(vt));
252 if (ioctl(fd, VIDIOC_G_TUNER, &vt) != 0) {
253 close(fd);
254 iter++;
255 continue;
256 }
257 /* remove device if it doesn't support rds block I/O */
258 if (vt.capability & V4L2_TUNER_CAP_RDS_BLOCK_IO)
259 valid_devices.push_back(*iter++);
260 else
261 iter = files.erase(iter);
262 close(fd);
263 }
264 return valid_devices;
265 }
266
267 static int parse_subopt(char **subs, const char * const *subopts, char **value)
268 {
269 int opt = v4l_getsubopt(subs, const_cast<char * const *>(subopts), value);
270
271 if (opt == -1) {
272 fprintf(stderr, "Invalid suboptions specified\n");
273 return -1;
274 }
275 if (*value == nullptr) {
276 fprintf(stderr, "No value given to suboption <%s>\n",
277 subopts[opt]);
278 return -1;
279 }
280 return opt;
281 }
282
283 static void parse_freq_seek(char *optarg, struct v4l2_hw_freq_seek &seek)
284 {
285 char *value;
286 char *subs = optarg;
287
288 while (*subs != '\0') {
289 static constexpr const char *subopts[] = {
290 "dir",
291 "wrap",
292 "spacing",
293 nullptr
294 };
295
296 switch (parse_subopt(&subs, subopts, &value)) {
297 case 0:
298 seek.seek_upward = strtoul(value, nullptr, 0);
299 break;
300 case 1:
301 seek.wrap_around = strtoul(value, nullptr, 0);
302 break;
303 case 2:
304 seek.spacing = strtoul(value, nullptr, 0);
305 break;
306 default:
307 usage_tuner();
308 std::exit(EXIT_FAILURE);
309 }
310 }
311 }
312
313 static void print_byte(char byte, bool linebreak)
314 {
315 int count = 8;
316 printf(" ");
317 while (count--) {
318 printf("%d", (byte & 128) ? 1 : 0 );
319 byte <<= 1;
320 }
321 if (linebreak)
322 printf("\n");
323 }
324
325 static void print_rds_group(const struct v4l2_rds_group *rds_group)
326 {
327 printf("\nComplete RDS data group received \n");
328 printf("PI: %04x\n", rds_group->pi);
329 printf("Group: %u%c \n", rds_group->group_id, rds_group->group_version);
330 printf("Data B:");
331 print_byte(rds_group->data_b_lsb, true);
332 printf("Data C:");
333 print_byte(rds_group->data_c_msb, false);
334 print_byte(rds_group->data_c_lsb, true);
335 printf("Data D:");
336 print_byte(rds_group->data_d_msb, false);
337 print_byte(rds_group->data_d_lsb, true);
338 printf("\n");
339 }
340
341 static void print_decoder_info(uint8_t di)
342 {
343 printf("\nDI: ");
344 if (di & V4L2_RDS_FLAG_STEREO)
345 printf("Stereo, ");
346 else
347 printf("Mono, ");
348 if (di & V4L2_RDS_FLAG_ARTIFICIAL_HEAD)
349 printf("Artificial Head, ");
350 else
351 printf("No Artificial Head, ");
352 if (di & V4L2_RDS_FLAG_COMPRESSED)
353 printf("Compressed, ");
354 else
355 printf("Not Compressed, ");
356 if (di & V4L2_RDS_FLAG_DYNAMIC_PTY)
357 printf("Dynamic PTY");
358 else
359 printf("Static PTY");
360 }
361
362 static void print_rds_tmc(const struct v4l2_rds *handle, uint32_t updated_fields)
363 {
364 const struct v4l2_rds_tmc_msg *msg = &handle->tmc.tmc_msg;
365 const struct v4l2_tmc_additional_set *set = &msg->additional;
366
367 if (updated_fields & V4L2_RDS_TMC_SG) {
368 printf("\nTMC Single-grp: location: %04x, event: %04x, extent: %02x "
369 "duration: %02x", msg->location, msg->event,
370 msg->extent, msg->dp);
371 return;
372 }
373 if (updated_fields & V4L2_RDS_TMC_MG) {
374 printf("\nTMC Multi-grp: length: %02d, location: %04x, event: %04x,\n"
375 " extent: %02x duration: %02x", msg->length, msg->location, msg->event,
376 msg->extent, msg->dp);
377 for (int i = 0; i < set->size; i++) {
378 printf("\n additional[%02d]: label: %02d, value: %04x",
379 i, set->fields[i].label, set->fields[i].data);
380 }
381 return;
382 }
383 }
384
385 static void print_rds_tmc_tuning(const struct v4l2_rds *handle, uint32_t updated_fields)
386 {
387 const struct v4l2_tmc_tuning *tuning = &handle->tmc.tuning;
388 const struct v4l2_tmc_station *station;
389
390 if (updated_fields & V4L2_RDS_TMC_TUNING) {
391 printf("\nTMC Service provider: %s, %u alternative stations\n", handle->tmc.spn, tuning->station_cnt);
392 for (int i = 0; i < tuning->station_cnt; i++) {
393 station = &tuning->station[i];
394 printf("PI(ON %02u) = %04x, AFs: %u, mapped AFs: %u \n", i, station->pi,
395 station->afi.af_size, station->afi.mapped_af_size);
396 for (int j = 0; j < station->afi.af_size; j++)
397 printf(" AF%02d: %.1fMHz\n", j, station->afi.af[j] / 1000000.0);
398 for (int k = 0; k < station->afi.mapped_af_size; k++)
399 printf(" m_AF%02d: %.1fMHz => %.1fMHz\n", k,
400 station->afi.mapped_af_tuning[k] / 1000000.0,
401 station->afi.mapped_af[k] / 1000000.0);
402 if (station->ltn != 0 || station->msg != 0 || station-> sid != 0)
403 printf(" ltn: %02x, msg: %02x, sid: %02x\n", station->ltn,
404 station->msg, station->sid);
405 }
406 }
407 }
408
409 static void print_rds_statistics(const struct v4l2_rds_statistics *statistics)
410 {
411 printf("\n\nRDS Statistics: \n");
412 printf("received blocks / received groups: %u / %u\n",
413 statistics->block_cnt, statistics->group_cnt);
414
415 double block_error_percentage = 0;
416
417 if (statistics->block_cnt)
418 block_error_percentage =
419 (static_cast<float>(statistics->block_error_cnt) / statistics->block_cnt) * 100.0;
420 printf("block errors / group errors: %u (%3.2f%%) / %u \n",
421 statistics->block_error_cnt,
422 block_error_percentage, statistics->group_error_cnt);
423
424 double block_corrected_percentage = 0;
425
426 if (statistics->block_cnt)
427 block_corrected_percentage = (
428 static_cast<float>(statistics->block_corrected_cnt) / statistics->block_cnt) * 100.0;
429 printf("corrected blocks: %u (%3.2f%%)\n",
430 statistics->block_corrected_cnt, block_corrected_percentage);
431 for (int i = 0; i < 16; i++)
432 printf("Group %02d: %u\n", i, statistics->group_type_cnt[i]);
433 }
434
435 static void print_rds_af(const struct v4l2_rds_af_set *af_set)
436 {
437 int counter = 0;
438
439 printf("\nAnnounced AFs: %u", af_set->announced_af);
440 for (int i = 0; i < af_set->size && i < af_set->announced_af; i++, counter++) {
441 if (af_set->af[i] >= 87500000 ) {
442 printf("\nAF%02d: %.1fMHz", counter, af_set->af[i] / 1000000.0);
443 continue;
444 }
445 printf("\nAF%02d: %.3fkHz", counter, af_set->af[i] / 1000.0);
446 }
447 }
448
449 static void print_rds_eon(const struct v4l2_rds_eon_set *eon_set)
450 {
451 int counter = 0;
452
453 printf("\n\nEnhanced Other Network information: %u channels", eon_set->size);
454 for (int i = 0; i < eon_set->size; i++, counter++) {
455 if (eon_set->eon[i].valid_fields & V4L2_RDS_PI)
456 printf("\nPI(ON %02i) = %04x", i, eon_set->eon[i].pi);
457 if (eon_set->eon[i].valid_fields & V4L2_RDS_PS)
458 printf("\nPS(ON %02i) = %s", i, eon_set->eon[i].ps);
459 if (eon_set->eon[i].valid_fields & V4L2_RDS_PTY)
460 printf("\nPTY(ON %02i) = %0u", i, eon_set->eon[i].pty);
461 if (eon_set->eon[i].valid_fields & V4L2_RDS_LSF)
462 printf("\nLSF(ON %02i) = %0u", i, eon_set->eon[i].lsf);
463 if (eon_set->eon[i].valid_fields & V4L2_RDS_AF)
464 printf("\nPTY(ON %02i) = %0u", i, eon_set->eon[i].pty);
465 if (eon_set->eon[i].valid_fields & V4L2_RDS_TP)
466 printf("\nTP(ON %02i): %s", i, eon_set->eon[i].tp? "yes":"no");
467 if (eon_set->eon[i].valid_fields & V4L2_RDS_TA)
468 printf("\nTA(ON %02i): %s", i, eon_set->eon[i].tp? "yes":"no");
469 if (eon_set->eon[i].valid_fields & V4L2_RDS_AF) {
470 printf("\nAF(ON %02i): size=%i", i, eon_set->eon[i].af.size);
471 print_rds_af(&(eon_set->eon[i].af));
472 }
473 }
474 }
475
476 static void print_rds_pi(const struct v4l2_rds *handle)
477 {
478 uint16_t pi = handle->pi;
479
480 if (handle->is_rbds) {
481 char callsign[5] = { 0 };
482 uint8_t nibble = handle->pi >> 12;
483
484 if (pi >= 0xafa1 && pi <= 0xafa9)
485 pi = (pi & 0xf) << 12;
486 else if (pi > 0xaf11 && pi <= 0xaf1f)
487 pi = (pi & 0xff) << 8;
488 else if (pi > 0xaf21 && pi <= 0xafaf)
489 pi = (pi & 0xff) << 8;
490
491 if (pi > 0xa100 && pi <= 0xa9ff)
492 pi -= 0x9100;
493 if (pi > 0x1000 && pi <= 0x54a7) {
494 pi -= 4096;
495 callsign[0] = 'K';
496 } else if (pi >= 0x54a8 && pi <= 0x994f) {
497 pi -= 21672;
498 callsign[0] = 'W';
499 }
500 if (callsign[0]) {
501 callsign[1] = 'A' + pi / 676;
502 callsign[2] = 'A' + (pi / 26) % 26;
503 callsign[3] = 'A' + pi % 26;
504 printf("\nCall Sign: %s", callsign);
505 }
506 if (nibble != 0x0b && nibble != 0x0d && nibble != 0x0e)
507 return;
508 }
509 printf("\nArea Coverage: %s", v4l2_rds_get_coverage_str(handle));
510 }
511
512 static void print_rds_data(const struct v4l2_rds *handle, uint32_t updated_fields)
513 {
514 if (params.options[OptPrintBlock])
515 updated_fields = 0xffffffff;
516
517 if ((updated_fields & V4L2_RDS_PI) &&
518 (handle->valid_fields & V4L2_RDS_PI)) {
519 printf("\nPI: %04x", handle->pi);
520 print_rds_pi(handle);
521 }
522
523 if (updated_fields & V4L2_RDS_PS &&
524 handle->valid_fields & V4L2_RDS_PS) {
525 printf("\nPS: %s", handle->ps);
526 }
527
528 if (updated_fields & V4L2_RDS_PTY && handle->valid_fields & V4L2_RDS_PTY)
529 printf("\nPTY: %0u -> %s", handle->pty, v4l2_rds_get_pty_str(handle));
530
531 if (updated_fields & V4L2_RDS_PTYN && handle->valid_fields & V4L2_RDS_PTYN) {
532 printf("\nPTYN: %s", handle->ptyn);
533 }
534
535 if (updated_fields & V4L2_RDS_TIME) {
536 printf("\nTime: %s", ctime(&handle->time));
537 }
538 if (updated_fields & V4L2_RDS_RT && handle->valid_fields & V4L2_RDS_RT) {
539 printf("\nRT: %s", handle->rt);
540 }
541
542 if ((updated_fields & (V4L2_RDS_TP | V4L2_RDS_TA)) &&
543 (handle->valid_fields & (V4L2_RDS_TP | V4L2_RDS_TA)))
544 printf("\nTP: %s TA: %s", (handle->tp) ? "yes" : "no",
545 handle->ta ? "yes" : "no");
546 if (updated_fields & V4L2_RDS_MS && handle->valid_fields & V4L2_RDS_MS)
547 printf("\nMS Flag: %s", (handle->ms) ? "Music" : "Speech");
548 if (updated_fields & V4L2_RDS_ECC && handle->valid_fields & V4L2_RDS_ECC)
549 printf("\nECC: %X%x, Country: %u -> %s",
550 handle->ecc >> 4, handle->ecc & 0x0f, handle->pi >> 12,
551 v4l2_rds_get_country_str(handle));
552 if (updated_fields & V4L2_RDS_LC && handle->valid_fields & V4L2_RDS_LC)
553 printf("\nLanguage: %u -> %s ", handle->lc,
554 v4l2_rds_get_language_str(handle));
555 if (updated_fields & V4L2_RDS_DI && handle->valid_fields & V4L2_RDS_DI)
556 print_decoder_info(handle->di);
557 if (updated_fields & V4L2_RDS_ODA &&
558 handle->decode_information & V4L2_RDS_ODA) {
559 for (int i = 0; i < handle->rds_oda.size; ++i)
560 printf("\nODA Group: %02u%c, AID: %08x", handle->rds_oda.oda[i].group_id,
561 handle->rds_oda.oda[i].group_version, handle->rds_oda.oda[i].aid);
562 }
563 if (updated_fields & V4L2_RDS_AF && handle->valid_fields & V4L2_RDS_AF)
564 print_rds_af(&handle->rds_af);
565 if (updated_fields & V4L2_RDS_TMC_TUNING && handle->valid_fields & V4L2_RDS_TMC_TUNING)
566 print_rds_tmc_tuning(handle, updated_fields);
567 if (params.options[OptPrintBlock])
568 printf("\n");
569 if (params.options[OptTMC])
570 print_rds_tmc(handle, updated_fields);
571 }
572
573 static void read_rds(struct v4l2_rds *handle, const int fd, const int wait_limit)
574 {
575 int byte_cnt = 0;
576 int error_cnt = 0;
577 uint32_t updated_fields = 0x00;
578 struct v4l2_rds_data rds_data; /* read buffer for rds blocks */
579
580 while (!params.terminate_decoding) {
581 memset(&rds_data, 0, sizeof(rds_data));
582 if ((byte_cnt=read(fd, &rds_data, 3)) != 3) {
583 if (byte_cnt == 0) {
584 printf("\nEnd of input file reached \n");
585 break;
586 }
587 if (++error_cnt > 2) {
588 fprintf(stderr, "\nError reading from "
589 "device (no RDS data available)\n");
590 break;
591 }
592 /* wait for new data to arrive: transmission of 1
593 * group takes ~88.7ms */
594 usleep(wait_limit * 1000);
595 }
596 else if (byte_cnt == 3) {
597 error_cnt = 0;
598 /* true if a new group was decoded */
599 if ((updated_fields = v4l2_rds_add(handle, &rds_data))) {
600 print_rds_data(handle, updated_fields);
601 if (params.options[OptVerbose])
602 print_rds_group(v4l2_rds_get_group(handle));
603 }
604 }
605 }
606 /* print a summary of all valid RDS-fields before exiting */
607 printf("\nSummary of valid RDS-fields:");
608 print_rds_data(handle, 0xFFFFFFFF);
609 }
610
611 static void read_rds_from_fd(const int fd)
612 {
613 struct v4l2_rds *rds_handle;
614
615 /* create an rds handle for the current device */
616 if (!(rds_handle = v4l2_rds_create(params.options[OptRBDS]))) {
617 fprintf(stderr, "Failed to init RDS lib: %s\n", strerror(errno));
618 std::exit(EXIT_FAILURE);
619 }
620
621 /* try to receive and decode RDS data */
622 read_rds(rds_handle, fd, params.wait_limit);
623 if (rds_handle->valid_fields & V4L2_RDS_EON)
624 print_rds_eon(&rds_handle->rds_eon);
625 print_rds_statistics(&rds_handle->rds_statistics);
626
627 v4l2_rds_destroy(rds_handle);
628 }
629
630 static int parse_cl(int argc, char **argv)
631 {
632 int i = 0;
633 int idx = 0;
634 int opt = 0;
635 /* 26 letters in the alphabet, case sensitive = 26 * 2 possible
636 * short options, where each option requires at most two chars
637 * {option, optional argument} */
638 char short_options[26 * 2 * 2 + 1];
639
640 if (argc == 1) {
641 usage_hint();
642 std::exit(EXIT_FAILURE);
643 }
644 for (i = 0; long_options[i].name; i++) {
645 if (!isalpha(long_options[i].val))
646 continue;
647 short_options[idx++] = long_options[i].val;
648 if (long_options[i].has_arg == required_argument)
649 short_options[idx++] = ':';
650 }
651 while (true) {
652 int option_index = 0;
653
654 short_options[idx] = 0;
655 opt = getopt_long(argc, argv, short_options,
656 long_options, &option_index);
657 if (opt == -1)
658 break;
659
660 params.options[opt] = 1;
661 switch (opt) {
662 case OptSetDevice:
663 strncpy(params.fd_name, optarg, sizeof(params.fd_name) - 1);
664 if (optarg[0] >= '0' && optarg[0] <= '9' && strlen(optarg) <= 3) {
665 snprintf(params.fd_name, sizeof(params.fd_name), "/dev/radio%s", optarg);
666 }
667 params.fd_name[sizeof(params.fd_name) - 1] = '\0';
668 break;
669 case OptSetFreq:
670 params.freq = strtod(optarg, nullptr);
671 break;
672 case OptListDevices:
673 print_devices(list_devices());
674 break;
675 case OptFreqSeek:
676 parse_freq_seek(optarg, params.freq_seek);
677 break;
678 case OptTunerIndex:
679 params.tuner_index = strtoul(optarg, nullptr, 0);
680 break;
681 case OptOpenFile:
682 {
683 if (access(optarg, F_OK) != -1) {
684 params.filemode_active = true;
685 strncpy(params.fd_name, optarg, sizeof(params.fd_name));
686 params.fd_name[sizeof(params.fd_name) - 1] = '\0';
687 } else {
688 fprintf(stderr, "Unable to open file: %s\n", optarg);
689 return -1;
690 }
691 /* enable the read-rds option by default for convenience */
692 params.options[OptReadRds] = 1;
693 break;
694 }
695 case OptWaitLimit:
696 params.wait_limit = strtoul(optarg, nullptr, 0);
697 break;
698 case ':':
699 fprintf(stderr, "Option '%s' requires a value\n",
700 argv[optind]);
701 usage_hint();
702 return 1;
703 case '?':
704 if (argv[optind])
705 fprintf(stderr, "Unknown argument '%s'\n", argv[optind]);
706 usage_hint();
707 return 1;
708 }
709 }
710 if (optind < argc) {
711 printf("unknown arguments: ");
712 while (optind < argc)
713 printf("%s ", argv[optind++]);
714 printf("\n");
715 usage_hint();
716 return 1;
717 }
718 if (params.options[OptAll]) {
719 params.options[OptGetDriverInfo] = 1;
720 params.options[OptGetFreq] = 1;
721 params.options[OptGetTuner] = 1;
722 params.options[OptSilent] = 1;
723 }
724 /* set default value for wait limit, if not specified by user */
725 if (!params.options[OptWaitLimit])
726 params.wait_limit = 5000;
727
728 return 0;
729 }
730
731 static void set_options(const int fd, const int capabilities, struct v4l2_frequency *vf,
732 struct v4l2_tuner *tuner)
733 {
734 double fac = 16; /* factor for frequency division */
735
736 if (params.options[OptSetFreq]) {
737 vf->type = V4L2_TUNER_RADIO;
738 tuner->index = params.tuner_index;
739 if (doioctl(fd, VIDIOC_G_TUNER, tuner) == 0) {
740 fac = (tuner->capability & V4L2_TUNER_CAP_LOW) ? 16000 : 16;
741 vf->type = tuner->type;
742 }
743
744 vf->tuner = params.tuner_index;
745 vf->frequency = __u32(params.freq * fac);
746 if (doioctl(fd, VIDIOC_S_FREQUENCY, vf) == 0)
747 printf("Frequency for tuner %d set to %d (%f MHz)\n",
748 vf->tuner, vf->frequency, vf->frequency / fac);
749 }
750
751 if (params.options[OptFreqSeek]) {
752 params.freq_seek.tuner = params.tuner_index;
753 params.freq_seek.type = V4L2_TUNER_RADIO;
754 doioctl(fd, VIDIOC_S_HW_FREQ_SEEK, &params.freq_seek);
755 }
756 }
757
758 static void get_options(const int fd, const int capabilities, struct v4l2_frequency *vf,
759 struct v4l2_tuner *tuner)
760 {
761 double fac = 16; /* factor for frequency division */
762
763 if (params.options[OptGetFreq]) {
764 vf->type = V4L2_TUNER_RADIO;
765 tuner->index = params.tuner_index;
766 if (doioctl(fd, VIDIOC_G_TUNER, tuner) == 0) {
767 fac = (tuner->capability & V4L2_TUNER_CAP_LOW) ? 16000 : 16;
768 vf->type = tuner->type;
769 }
770 vf->tuner = params.tuner_index;
771 if (doioctl(fd, VIDIOC_G_FREQUENCY, vf) == 0)
772 printf("Frequency for tuner %d: %d (%f MHz)\n",
773 vf->tuner, vf->frequency, vf->frequency / fac);
774 }
775
776 if (params.options[OptGetTuner]) {
777 struct v4l2_tuner vt;
778
779 memset(&vt, 0, sizeof(struct v4l2_tuner));
780 vt.index = params.tuner_index;
781 if (doioctl(fd, VIDIOC_G_TUNER, &vt) == 0) {
782 printf("Tuner %d:\n", vt.index);
783 printf("\tName : %s\n", vt.name);
784 printf("\tCapabilities : %s\n",
785 tcap2s(vt.capability).c_str());
786 if (vt.capability & V4L2_TUNER_CAP_LOW)
787 printf("\tFrequency range : %.1f MHz - %.1f MHz\n",
788 vt.rangelow / 16000.0, vt.rangehigh / 16000.0);
789 else
790 printf("\tFrequency range : %.1f MHz - %.1f MHz\n",
791 vt.rangelow / 16.0, vt.rangehigh / 16.0);
792 printf("\tSignal strength/AFC : %ld%%/%d\n",
793 lround(vt.signal / 655.25), vt.afc);
794 printf("\tCurrent audio mode : %s\n", audmode2s(vt.audmode).c_str());
795 printf("\tAvailable subchannels: %s\n",
796 rxsubchans2s(vt.rxsubchans).c_str());
797 }
798 }
799
800 if (params.options[OptListFreqBands]) {
801 struct v4l2_frequency_band band;
802
803 memset(&band, 0, sizeof(band));
804 band.tuner = params.tuner_index;
805 band.type = V4L2_TUNER_RADIO;
806 band.index = 0;
807 printf("ioctl: VIDIOC_ENUM_FREQ_BANDS\n");
808 while (ioctl(fd, VIDIOC_ENUM_FREQ_BANDS, &band) >= 0) {
809 if (band.index)
810 printf("\n");
811 printf("\tIndex : %d\n", band.index);
812 printf("\tModulation : %s\n", modulation2s(band.modulation).c_str());
813 printf("\tCapability : %s\n", tcap2s(band.capability).c_str());
814 if (band.capability & V4L2_TUNER_CAP_LOW)
815 printf("\tFrequency Range: %.3f MHz - %.3f MHz\n",
816 band.rangelow / 16000.0, band.rangehigh / 16000.0);
817 else
818 printf("\tFrequency Range: %.3f MHz - %.3f MHz\n",
819 band.rangelow / 16.0, band.rangehigh / 16.0);
820 band.index++;
821 }
822 }
823 }
824
825 int main(int argc, char **argv)
826 {
827 int fd = -1;
828
829 /* command args */
830 struct v4l2_tuner tuner; /* set_freq/get_freq */
831 struct v4l2_capability vcap; /* list_cap */
832 struct v4l2_frequency vf; /* get_freq/set_freq */
833
834 memset(&tuner, 0, sizeof(tuner));
835 memset(&vcap, 0, sizeof(vcap));
836 memset(&vf, 0, sizeof(vf));
837 strcpy(params.fd_name, "/dev/radio0");
838
839 /* define locale for unicode support */
840 if (!setlocale(LC_CTYPE, "")) {
841 fprintf(stderr, "Can't set the specified locale!\n");
842 return 1;
843 }
844 /* register signal handler for interrupt signal, to exit gracefully */
845 signal(SIGINT, signal_handler_interrupt);
846
847 /* try to parse the command line */
848 parse_cl(argc, argv);
849 if (params.options[OptHelp]) {
850 usage();
851 std::exit(EXIT_SUCCESS);
852 }
853
854 /* File Mode: disables all other features, except for RDS decoding */
855 if (params.filemode_active) {
856 if ((fd = open(params.fd_name, O_RDONLY|O_NONBLOCK)) < 0){
857 perror("error opening file");
858 std::exit(EXIT_FAILURE);
859 }
860 read_rds_from_fd(fd);
861 close(fd);
862 std::exit(EXIT_SUCCESS);
863 }
864
865 /* Device Mode: open the radio device as read-only and non-blocking */
866 if (!params.options[OptSetDevice]) {
867 /* check the system for RDS capable devices */
868 dev_vec devices = list_devices();
869 if (devices.empty()) {
870 fprintf(stderr, "No RDS-capable device found\n");
871 std::exit(EXIT_FAILURE);
872 }
873 strncpy(params.fd_name, devices[0].c_str(), sizeof(params.fd_name));
874 params.fd_name[sizeof(params.fd_name) - 1] = '\0';
875 printf("Using device: %s\n", params.fd_name);
876 }
877 if ((fd = open(params.fd_name, O_RDONLY | O_NONBLOCK)) < 0) {
878 fprintf(stderr, "Failed to open %s: %s\n", params.fd_name,
879 strerror(errno));
880 std::exit(EXIT_FAILURE);
881 }
882 doioctl(fd, VIDIOC_QUERYCAP, &vcap);
883
884 /* Info options */
885 if (params.options[OptGetDriverInfo])
886 v4l2_info_capability(vcap);
887 /* Set options */
888 set_options(fd, vcap.capabilities, &vf, &tuner);
889 /* Get options */
890 get_options(fd, vcap.capabilities, &vf, &tuner);
891 /* RDS decoding */
892 if (params.options[OptReadRds])
893 read_rds_from_fd(fd);
894
895 close(fd);
896 std::exit(app_result);
897 }