├── .gitignore ├── LICENSE ├── README.md ├── doc ├── filter_response.png ├── firpreemphasis.m ├── galaxy_s2.jpg ├── spectrum.png └── vfd_display.jpg └── src ├── Makefile ├── control_pipe.c ├── control_pipe.h ├── fm_mpx.c ├── fm_mpx.h ├── generate_pulses.py ├── generate_waveforms.py ├── mailbox.c ├── mailbox.h ├── noise_22050.wav ├── pi_fm_rds.c ├── pi_fm_rds.cpp ├── pulses.wav ├── rds.c ├── rds.h ├── rds_wav.c ├── sound.wav ├── sound_22050.wav ├── stereo_44100.wav ├── waveforms.c └── waveforms.h /.gitignore: -------------------------------------------------------------------------------- 1 | src/waveform_*.wav 2 | src/pydemod 3 | src/test 4 | *.o 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Pi-FM-RDS 2 | ========= 3 | 4 | 5 | ## FM-RDS transmitter using the Raspberry Pi 6 | 7 | This program generates an FM modulation, with RDS (Radio Data System) data generated in real time. It can include monophonic or stereophonic audio. 8 | 9 | This version modulates the PLL instead of the clock divider for superior signal purity. The harmonics are unaffected, so the [legal warning](#warning-and-disclaimer) still applies. 10 | 11 | ![](doc/spectrum.png) 12 | 13 | TODO list 14 | *watchdog for PLL settings to prevent radio interference 15 | *measure PLL loop filter response 16 | 17 | It is based on the FM transmitter created by [Oliver Mattos and Oskar Weigl](http://www.icrobotics.co.uk/wiki/index.php/Turning_the_Raspberry_Pi_Into_an_FM_Transmitter), and later adapted to using DMA by [Richard Hirst](https://github.com/richardghirst). Christophe Jacquet adapted it and added the RDS data generator and modulator. The transmitter uses the Raspberry Pi's clock divider to produce VHF signals. 18 | 19 | It is compatible with both the Raspberry Pi 1 (the original one) and the Raspberry Pi 2 and 3. Users of Raspberry Pi 3 should add gpu_freq=250 to /boot/config.txt . The Pi 3 has very sensitive low voltage detection. When low voltage is detected, clocks are reduced to safe values in an attempt to prevent crashes. This program changes clocks to generate the desired radio frequency without the knowledge of the power management system. While it would be possible to detect and undo changes, this would cause radio interference each time it happens. Setting gpu_freq=250 appears to prevent undesired clock changes because the normal value and safe value are the same. 20 | 21 | ![](doc/vfd_display.jpg) 22 | 23 | PiFmRds has been developed for experimentation only. It is not a media center, it is not intended to broadcast music to your stereo system. See the [legal warning](#warning-and-disclaimer). 24 | 25 | ## How to use it? 26 | 27 | Pi-FM-RDS, depends on the `sndfile` library. To install this library on Debian-like distributions, for instance Raspbian, run `sudo apt-get install libsndfile1-dev`. 28 | 29 | Pi-FM-RDS also depends on the Linux `rpi-mailbox` driver, so you need a recent Linux kernel. The Raspbian releases from August 2015 have this. 30 | 31 | **Important.** The binaries compiled for the Raspberry Pi 1 are not compatible with the Raspberry Pi 2/3, and conversely. Always re-compile when switching models, so do not skip the `make clean` step in the instructions below! 32 | 33 | Clone the source repository and run `make` in the `src` directory: 34 | 35 | ```bash 36 | git clone https://github.com/F5OEO/PiFmRds.git 37 | cd PiFmRds/src 38 | git clone https://github.com/F5OEO/librpitx.git 39 | cd librpitx/src 40 | make 41 | cd ../../ 42 | make clean 43 | make 44 | ``` 45 | 46 | Then you can just run: 47 | 48 | ``` 49 | sudo ./pi_fm_rds 50 | ``` 51 | 52 | This will generate an FM transmission on 107.9 MHz, with default station name (PS), radiotext (RT) and PI-code, without audio. The radiofrequency signal is emitted on GPIO 4 (pin 7 on header P1). 53 | 54 | 55 | You can add monophonic or stereophonic audio by referencing an audio file as follows: 56 | 57 | ``` 58 | sudo ./pi_fm_rds -audio sound.wav 59 | ``` 60 | 61 | To test stereophonic audio, you can try the file `stereo_44100.wav` provided. 62 | 63 | The more general syntax for running Pi-FM-RDS is as follows: 64 | 65 | ``` 66 | pi_fm_rds [-freq freq] [-audio file] [-ppm ppm_error] [-pi pi_code] [-ps ps_text] [-rt rt_text] 67 | ``` 68 | 69 | All arguments are optional: 70 | 71 | * `-freq` specifies the carrier frequency (in MHz). Example: `-freq 107.9`. 72 | * `-audio` specifies an audio file to play as audio. The sample rate does not matter: Pi-FM-RDS will resample and filter it. If a stereo file is provided, Pi-FM-RDS will produce an FM-Stereo signal. Example: `-audio sound.wav`. The supported formats depend on `libsndfile`. This includes WAV and Ogg/Vorbis (among others) but not MP3. Specify `-` as the file name to read audio data on standard input (useful for piping audio into Pi-FM-RDS, see below). 73 | * `-pi` specifies the PI-code of the RDS broadcast. 4 hexadecimal digits. Example: `-pi FFFF`. 74 | * `-ps` specifies the station name (Program Service name, PS) of the RDS broadcast. Limit: 8 characters. Example: `-ps RASP-PI`. 75 | * `-rt` specifies the radiotext (RT) to be transmitted. Limit: 64 characters. Example: `-rt 'Hello, world!'`. 76 | * `-ctl` specifies a named pipe (FIFO) to use as a control channel to change PS and RT at run-time (see below). 77 | * `-ppm` specifies your Raspberry Pi's oscillator error in parts per million (ppm), see below. 78 | 79 | By default the PS changes back and forth between `Pi-FmRds` and a sequence number, starting at `00000000`. The PS changes around one time per second. 80 | 81 | 82 | ### Clock calibration (only if experiencing difficulties) 83 | 84 | The RDS standards states that the error for the 57 kHz subcarrier must be less than ± 6 Hz, i.e. less than 105 ppm (parts per million). The Raspberry Pi's oscillator error may be above this figure. That is where the `-ppm` parameter comes into play: you specify your Pi's error and Pi-FM-RDS adjusts the clock dividers accordingly. 85 | 86 | In practice, I found that Pi-FM-RDS works okay even without using the `-ppm` parameter. I suppose the receivers are more tolerant than stated in the RDS spec. 87 | 88 | One way to measure the ppm error is to play the `pulses.wav` file: it will play a pulse for precisely 1 second, then play a 1-second silence, and so on. Record the audio output from a radio with a good audio card. Say you sample at 44.1 kHz. Measure 10 intervals. Using [Audacity](http://audacity.sourceforge.net/) for example determine the number of samples of these 10 intervals: in the absence of clock error, it should be 441,000 samples. With my Pi, I found 441,132 samples. Therefore, my ppm error is (441132-441000)/441000 * 1e6 = 299 ppm, **assuming that my sampling device (audio card) has no clock error...** 89 | 90 | 91 | ### Piping audio into Pi-FM-RDS 92 | 93 | If you use the argument `-audio -`, Pi-FM-RDS reads audio data on standard input. This allows you to pipe the output of a program into Pi-FM-RDS. For instance, this can be used to read MP3 files using Sox: 94 | 95 | ``` 96 | sox -t mp3 http://www.linuxvoice.com/episodes/lv_s02e01.mp3 -t wav - | sudo ./pi_fm_rds -audio - 97 | ``` 98 | 99 | Or to pipe the AUX input of a sound card into Pi-FM-RDS: 100 | 101 | ``` 102 | sudo arecord -fS16_LE -r 44100 -Dplughw:1,0 -c 2 - | sudo ./pi_fm_rds -audio - 103 | ``` 104 | 105 | 106 | ### Changing PS, RT and TA at run-time 107 | 108 | You can control PS, RT and TA (Traffic Announcement flag) at run-time using a named pipe (FIFO). For this run Pi-FM-RDS with the `-ctl` argument. 109 | 110 | Example: 111 | 112 | ``` 113 | mkfifo rds_ctl 114 | sudo ./pi_fm_rds -ctl rds_ctl 115 | ``` 116 | 117 | Then you can send “commands” to change PS, RT and TA: 118 | 119 | ``` 120 | cat >rds_ctl 121 | PS MyText 122 | RT A text to be sent as radiotext 123 | TA ON 124 | PS OtherTxt 125 | TA OFF 126 | ... 127 | ``` 128 | 129 | Every line must start with either `PS`, `RT` or `TA`, followed by one space character, and the desired value. Any other line format is silently ignored. `TA ON` switches the Traffic Announcement flag to *on*, any other value switches it to *off*. 130 | 131 | 132 | ## Warning and Disclaimer 133 | 134 | PiFmRds is an **experimental** program, designed **only for experimentation**. It is in no way intended to become a personal *media center* or a tool to operate a *radio station*, or even broadcast sound to one's own stereo system. 135 | 136 | In most countries, transmitting radio waves without a state-issued licence specific to the transmission modalities (frequency, power, bandwidth, etc.) is **illegal**. 137 | 138 | Therefore, always connect a shielded transmission line from the RaspberryPi directly 139 | to a radio receiver, so as **not** to emit radio waves. Never use an antenna. 140 | 141 | Even if you are a licensed amateur radio operator, using PiFmRds to transmit radio waves on ham frequencies without any filtering between the RaspberryPi and an antenna is most probably illegal because the square-wave carrier is very rich in harmonics, so the bandwidth requirements are likely not met. 142 | 143 | I could not be held liable for any misuse of your own Raspberry Pi. Any experiment is made under your own responsibility. 144 | 145 | 146 | ## Tests 147 | 148 | Pi-FM-RDS was successfully tested with all my RDS-able devices, namely: 149 | 150 | * a Sony ICF-C20RDS alarm clock from 1995, 151 | * a Sangean PR-D1 portable receiver from 1998, and an ATS-305 from 1999, 152 | * a Samsung Galaxy S2 mobile phone from 2011, 153 | * a Philips MBD7020 hifi system from 2012, 154 | * a Silicon Labs [USBFMRADIO-RD](http://www.silabs.com/products/mcu/Pages/USBFMRadioRD.aspx) USB stick, employing an Si4701 chip, and using my [RDS Surveyor](http://rds-surveyor.sourceforge.net/) program, 155 | * a “PCear Fm Radio”, a Chinese clone of the above, again using RDS Surveyor. 156 | 157 | Reception works perfectly with all the devices above. RDS Surveyor reports no group errors. 158 | 159 | ![](doc/galaxy_s2.jpg) 160 | 161 | 162 | ### CPU Usage 163 | 164 | CPU usage on a Raspberry Pi 1 is as follows: 165 | 166 | * without audio: 9% 167 | * with mono audio: 33% 168 | * with stereo audio: 40% 169 | 170 | CPU usage increases dramatically when adding audio because the program has to upsample the (unspecified) sample rate of the input audio file to 228 kHz, its internal operating sample rate. Doing so, it has to apply an FIR filter, which is costly. 171 | 172 | ## Design 173 | 174 | The RDS data generator lies in the `rds.c` file. 175 | 176 | The RDS data generator generates cyclically four 0A groups (for transmitting PS), and one 2A group (for transmitting RT). In addition, every minute, it inserts a 4A group (for transmitting CT, clock time). `get_rds_group` generates one group, and uses `crc` for computing the CRC. 177 | 178 | To get samples of RDS data, call `get_rds_samples`. It calls `get_rds_group`, differentially encodes the signal and generates a shaped biphase symbol. Successive biphase symbols overlap: the samples are added so that the result is equivalent to applying the shaping filter (a [root-raised-cosine (RRC) filter ](http://en.wikipedia.org/wiki/Root-raised-cosine_filter) specified in the RDS standard) to a sequence of Manchester-encoded pulses. 179 | 180 | The shaped biphase symbol is generated once and for all by a Python program called `generate_waveforms.py` that uses [Pydemod](https://github.com/ChristopheJacquet/Pydemod), one of my other software radio projects. This Python program generates an array called `waveform_biphase` that results from the application of the RRC filter to a positive-negative impulse pair. *Note that the output of `generate_waveforms.py`, two files named `waveforms.c` and `waveforms.h`, are included in the Git repository, so you don't need to run the Python script yourself to compile Pi-FM-RDS.* 181 | 182 | Internally, the program samples all signals at 228 kHz, four times the RDS subcarrier's 57 kHz. 183 | 184 | The FM multiplex signal (baseband signal) is generated by `fm_mpx.c`. This file handles the upsampling of the input audio file to 228 kHz, and the generation of the multiplex: unmodulated left+right signal (limited to 15 kHz), possibly the stereo pilot at 19 kHz, possibly the left-right signal, amplitude-modulated on 38 kHz (suppressed carrier) and RDS signal from `rds.c`. Upsampling is performed using a polyphase filter bank of 32 filters, each with 32 coefficients. To help understand the polyphase filter bank, consider upsampling the input signal by zero stuffing. Then, apply a low pass filter with the cutoff at the original Nyquist frequency. Finally, collect some of the filtered samples at the new sampling rate. The polyphase filter bank does the same thing mathematically, but avoids computing output samples that will not be used. It also avoids processing all of the suffed zeros. The low pass part of the filter is a sampled sinc. The filter is also used to provide pre-emphasis. The low pass filter coefficients are convolved with the pre-emphasis filter, providing pre-emphasis at no additional cost. The combined filter is windowed by a Hamming window. The filter coefficients are generated at startup so that the filter cuts frequencies above the minimum of: 185 | * the Nyquist frequency of the input audio file (half the sample rate) to avoid aliasing (this is the typical case for resampling), 186 | * 15 kHz, the bandpass of the left+right and left-right channels, as per the FM broadcasting standards. 187 | 188 | An Octave script to compute the frequency response of the filter is provided in the doc folder. 189 | 190 | The samples are played by `pi_fm_rds.c` that is adapted from Richard Hirst's [PiFmDma](https://github.com/richardghirst/PiBits/tree/master/PiFmDma). The program was changed to support a sample rate of precisely 228 kHz. 191 | 192 | 193 | ### References 194 | 195 | * [EN 50067, Specification of the radio data system (RDS) for VHF/FM sound broadcasting in the frequency range 87.5 to 108.0 MHz](http://www.interactive-radio-system.com/docs/EN50067_RDS_Standard.pdf) 196 | 197 | 198 | ## History 199 | * 2018-03-19: Use librpitx for easy integration 200 | * 2015-09-05: support for the Raspberry Pi 2 201 | * 2014-11-01: support for toggling the Traffic Announcement (TA) flag at run-time 202 | * 2014-10-19: bugfix (cleanly stop the DMA engine when the specified file does not exist, or it's not possible to read from stdin) 203 | * 2014-08-04: bugfix (ppm now uses floats) 204 | * 2014-06-22: generate CT (clock time) signals, bugfixes 205 | * 2014-05-04: possibility to change PS and RT at run-time 206 | * 2014-04-28: support piping audio file data to Pi-FM-RDS' standard input 207 | * 2014-04-14: new release that supports any sample rate for the audio input, and that can generate a proper FM-Stereo signal if a stereophonic input file is provided 208 | * 2014-04-06: initial release, which only supported 228 kHz monophonic audio input files 209 | 210 | -------- 211 | 212 | © [Christophe Jacquet](http://www.jacquet80.eu/) (F8FTK), 2014-2015. Released under the GNU GPL v3. 213 | -------------------------------------------------------------------------------- /doc/filter_response.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/F5OEO/PiFmRds/2707ecc8ab32164060de53e4774e682a718aecb3/doc/filter_response.png -------------------------------------------------------------------------------- /doc/firpreemphasis.m: -------------------------------------------------------------------------------- 1 | 2 | 3 | % Filter analysis for combined LPF and preemphasis 4 | % IIR reference material: http://jontio.zapto.org/hda1/preempiir.pdf 5 | % 6 | % Tested on GNU Octave, should work on Matlab 7 | 8 | cutoff_freq=15700 9 | if 1 10 | FIR_PHASES=32 % Values for PiFmRds 11 | sample_rate=44100 12 | tau=75e-6 13 | delta=1.96e-6 14 | else 15 | FIR_PHASES=4 % Values used in reference material 16 | sample_rate=48000 % 48000*4 = 192000 17 | tau=50e-6 % to verify results against example values 18 | delta=7.96e-6 19 | end 20 | 21 | 22 | FIR_SIZE=1024 23 | 24 | taup=1/(2*sample_rate*FIR_PHASES)*cot(1/(2*tau*sample_rate*FIR_PHASES)) 25 | deltap=1/(2*sample_rate*FIR_PHASES)*cot(1/(2*delta*sample_rate*FIR_PHASES)) 26 | bp=sqrt(-(taup^2) + sqrt( (taup.^4) + 8*(taup^2)*(deltap^2) ) )/2 27 | ap=sqrt(2*(bp^2) + (taup^2) ) 28 | a0=( 2*ap + 1/(sample_rate*FIR_PHASES) )/(2*bp + 1/(sample_rate*FIR_PHASES) ) 29 | a1=(-2*ap + 1/(sample_rate*FIR_PHASES) )/(2*bp + 1/(sample_rate*FIR_PHASES) ) 30 | b1=( 2*bp - 1/(sample_rate*FIR_PHASES) )/(2*bp + 1/(sample_rate*FIR_PHASES) ) 31 | 32 | x=0; 33 | y=0; 34 | 35 | for j=1:FIR_SIZE 36 | sincpos=j-((FIR_SIZE+1)/2); 37 | if (sincpos==0) 38 | firlowpass(j)= 2 * cutoff_freq / (sample_rate*FIR_PHASES) ; 39 | disp('Oops: sincpos hit zero'); 40 | else 41 | firlowpass(j)= sin(2 * pi * cutoff_freq * sincpos / (sample_rate*FIR_PHASES) ) / (pi * sincpos) ; 42 | end 43 | y=a0*firlowpass(j) + a1*x + b1*y; 44 | x=firlowpass(j); 45 | firpreemph(j)=y; 46 | win(j)=(.54 - .46 * cos(2*pi * (j) / (FIR_SIZE))) * FIR_PHASES ; 47 | 48 | end 49 | 50 | fullfilt=firpreemph.*win; 51 | 52 | hold off 53 | 54 | for j=1:FIR_PHASES 55 | phasefreqs=linspace(0,sample_rate*FIR_PHASES*((FIR_SIZE/FIR_PHASES)-1)/FIR_SIZE,FIR_SIZE/FIR_PHASES); 56 | phasedb=20*log10(abs(fft(fullfilt(j:FIR_PHASES:FIR_SIZE)))); 57 | % real data, so only show the positive frequencies 58 | l1=plot( phasefreqs(1:(end/2)+1) , phasedb(1:(end/2+1))); 59 | hold on 60 | 61 | %plot( fullfilt(j:FIR_PHASES:FIR_SIZE) ) 62 | end 63 | 64 | fulldb= 20*log10(abs(fft(fullfilt))/FIR_PHASES); 65 | fullfreqs=linspace(0,sample_rate*FIR_PHASES*(FIR_SIZE-1)/FIR_SIZE,FIR_SIZE); 66 | l2=plot( fullfreqs(1:(end/2+1)) ,fulldb(1:(end/2+1)),'r' ); 67 | 68 | 69 | l3=plot( [19000 19000 ] , [0 -59] , 'g' ,'linewidth',2 ); % Pilot frequency 70 | 71 | 72 | legend([l1,l2,l3],'Individual Phases','Full Filter Response','Pilot Tone') 73 | 74 | title('PiFmRds Polyphase Filter Response') 75 | xlim([0 60000]); 76 | xlabel('Hz'); 77 | ylabel('dB'); 78 | hold off 79 | 80 | % semilogx( linspace(0,sample_rate*FIR_PHASES*(FIR_SIZE-1)/FIR_SIZE,FIR_SIZE) ,20*log10(abs(fft(fullfilt))/FIR_PHASES) , 'r' ) 81 | 82 | -------------------------------------------------------------------------------- /doc/galaxy_s2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/F5OEO/PiFmRds/2707ecc8ab32164060de53e4774e682a718aecb3/doc/galaxy_s2.jpg -------------------------------------------------------------------------------- /doc/spectrum.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/F5OEO/PiFmRds/2707ecc8ab32164060de53e4774e682a718aecb3/doc/spectrum.png -------------------------------------------------------------------------------- /doc/vfd_display.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/F5OEO/PiFmRds/2707ecc8ab32164060de53e4774e682a718aecb3/doc/vfd_display.jpg -------------------------------------------------------------------------------- /src/Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | STD_CFLAGS = -Wall -std=gnu99 -c -g -O3 3 | 4 | # Enable ARM-specific options only on ARM, and compilation of the app only on ARM 5 | UNAME := $(shell uname -m) 6 | 7 | # Determine the hardware platform. Below, pi1 stands for the RaspberryPi 1 (the original one), 8 | # and pi2 stands for both the RaspberryPi 2 and 3. 9 | ifeq ($(UNAME), armv6l) 10 | CFLAGS = $(STD_CFLAGS) -march=armv6 -mtune=arm1176jzf-s -mfloat-abi=hard -mfpu=vfp -ffast-math -DRASPI=1 11 | TARGET = pi1 12 | else ifeq ($(UNAME), armv7l) 13 | CFLAGS = $(STD_CFLAGS) -march=armv7-a -mtune=arm1176jzf-s -mfloat-abi=hard -mfpu=vfp -ffast-math -DRASPI=2 14 | TARGET = pi2 15 | else 16 | CFLAGS = $(STD_CFLAGS) 17 | TARGET = other 18 | endif 19 | 20 | ifneq ($(TARGET), other) 21 | 22 | app: rds.o waveforms.o pi_fm_rds.o fm_mpx.o control_pipe.o mailbox.o librpitx/src/librpitx.a 23 | g++ -Wall -g -O3 -o pi_fm_rds rds.o waveforms.o pi_fm_rds.o fm_mpx.o control_pipe.o librpitx/src/librpitx.a -lm -lsndfile -lrt -lpthread 24 | 25 | endif 26 | 27 | 28 | rds_wav: rds.o waveforms.o rds_wav.o fm_mpx.o 29 | $(CC) -o rds_wav rds_wav.o rds.o waveforms.o fm_mpx.o -lm -lsndfile 30 | 31 | rds.o: rds.c waveforms.h 32 | $(CC) $(CFLAGS) rds.c 33 | 34 | control_pipe.o: control_pipe.c control_pipe.h rds.h 35 | $(CC) $(CFLAGS) control_pipe.c 36 | 37 | waveforms.o: waveforms.c waveforms.h 38 | $(CC) $(CFLAGS) waveforms.c 39 | 40 | mailbox.o: mailbox.c mailbox.h 41 | $(CC) $(CFLAGS) mailbox.c 42 | 43 | pi_fm_rds.o: pi_fm_rds.cpp control_pipe.h fm_mpx.h rds.h 44 | g++ -Wall -c -g -O3 pi_fm_rds.cpp 45 | 46 | rds_wav.o: rds_wav.c 47 | $(CC) $(CFLAGS) rds_wav.c 48 | 49 | fm_mpx.o: fm_mpx.c fm_mpx.h 50 | $(CC) $(CFLAGS) fm_mpx.c 51 | 52 | clean: 53 | rm -f *.o 54 | -------------------------------------------------------------------------------- /src/control_pipe.c: -------------------------------------------------------------------------------- 1 | /* 2 | PiFmRds - FM/RDS transmitter for the Raspberry Pi 3 | Copyright (C) 2014 Christophe Jacquet, F8FTK 4 | 5 | See https://github.com/ChristopheJacquet/PiFmRds 6 | 7 | rds_wav.c is a test program that writes a RDS baseband signal to a WAV 8 | file. It requires libsndfile. 9 | 10 | This program is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | This program is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU General Public License for more details. 19 | 20 | You should have received a copy of the GNU General Public License 21 | along with this program. If not, see . 22 | 23 | control_pipe.c: handles command written to a non-blocking control pipe, 24 | in order to change RDS PS and RT at runtime. 25 | */ 26 | 27 | 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #include "rds.h" 35 | #include "control_pipe.h" 36 | 37 | #define CTL_BUFFER_SIZE 100 38 | 39 | FILE *f_ctl; 40 | 41 | /* 42 | * Opens a file (pipe) to be used to control the RDS coder, in non-blocking mode. 43 | */ 44 | int open_control_pipe(char *filename) { 45 | int fd = open(filename, O_RDONLY | O_NONBLOCK); 46 | if(fd == -1) return -1; 47 | 48 | int flags; 49 | flags = fcntl(fd, F_GETFL, 0); 50 | flags |= O_NONBLOCK; 51 | if( fcntl(fd, F_SETFL, flags) == -1 ) return -1; 52 | 53 | f_ctl = fdopen(fd, "r"); 54 | if(f_ctl == NULL) return -1; 55 | 56 | return 0; 57 | } 58 | 59 | 60 | /* 61 | * Polls the control file (pipe), non-blockingly, and if a command is received, 62 | * processes it and updates the RDS data. 63 | */ 64 | int poll_control_pipe() { 65 | static char buf[CTL_BUFFER_SIZE]; 66 | 67 | char *res = fgets(buf, CTL_BUFFER_SIZE, f_ctl); 68 | if(res == NULL) return -1; 69 | if(strlen(res) > 3 && res[2] == ' ') { 70 | char *arg = res+3; 71 | if(arg[strlen(arg)-1] == '\n') arg[strlen(arg)-1] = 0; 72 | if(res[0] == 'P' && res[1] == 'S') { 73 | arg[8] = 0; 74 | set_rds_ps(arg); 75 | printf("PS set to: \"%s\"\n", arg); 76 | return CONTROL_PIPE_PS_SET; 77 | } 78 | if(res[0] == 'R' && res[1] == 'T') { 79 | arg[64] = 0; 80 | set_rds_rt(arg); 81 | printf("RT set to: \"%s\"\n", arg); 82 | return CONTROL_PIPE_RT_SET; 83 | } 84 | if(res[0] == 'T' && res[1] == 'A') { 85 | int ta = ( strcmp(arg, "ON") == 0 ); 86 | set_rds_ta(ta); 87 | printf("Set TA to "); 88 | if(ta) printf("ON\n"); else printf("OFF\n"); 89 | return CONTROL_PIPE_TA_SET; 90 | } 91 | } 92 | 93 | return -1; 94 | } 95 | 96 | /* 97 | * Closes the control pipe. 98 | */ 99 | int close_control_pipe() { 100 | if(f_ctl) return fclose(f_ctl); 101 | else return 0; 102 | } 103 | -------------------------------------------------------------------------------- /src/control_pipe.h: -------------------------------------------------------------------------------- 1 | /* 2 | PiFmRds - FM/RDS transmitter for the Raspberry Pi 3 | Copyright (C) 2014 Christophe Jacquet, F8FTK 4 | 5 | See https://github.com/ChristopheJacquet/PiFmRds 6 | 7 | rds_wav.c is a test program that writes a RDS baseband signal to a WAV 8 | file. It requires libsndfile. 9 | 10 | This program is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | This program is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU General Public License for more details. 19 | 20 | You should have received a copy of the GNU General Public License 21 | along with this program. If not, see . 22 | */ 23 | 24 | 25 | #define CONTROL_PIPE_PS_SET 1 26 | #define CONTROL_PIPE_RT_SET 2 27 | #define CONTROL_PIPE_TA_SET 3 28 | 29 | extern int open_control_pipe(char *filename); 30 | extern int close_control_pipe(); 31 | extern int poll_control_pipe(); 32 | -------------------------------------------------------------------------------- /src/fm_mpx.c: -------------------------------------------------------------------------------- 1 | /* 2 | PiFmRds - FM/RDS transmitter for the Raspberry Pi 3 | Copyright (C) 2014 Christophe Jacquet, F8FTK 4 | 5 | See https://github.com/ChristopheJacquet/PiFmRds 6 | 7 | rds_wav.c is a test program that writes a RDS baseband signal to a WAV 8 | file. It requires libsndfile. 9 | 10 | This program is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | This program is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU General Public License for more details. 19 | 20 | You should have received a copy of the GNU General Public License 21 | along with this program. If not, see . 22 | 23 | fm_mpx.c: generates an FM multiplex signal containing RDS plus possibly 24 | monaural or stereo audio. 25 | */ 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | #include "rds.h" 33 | 34 | 35 | #define PI 3.141592654 36 | 37 | 38 | #define FIR_PHASES (32) 39 | #define FIR_TAPS (32) // MUST be a power of 2 for the circular buffer 40 | 41 | size_t length; 42 | 43 | // coefficients of the low-pass FIR filter 44 | float low_pass_fir[FIR_PHASES][FIR_TAPS]; 45 | 46 | 47 | float carrier_38[] = {0.0, 0.8660254037844386, 0.8660254037844388, 1.2246467991473532e-16, -0.8660254037844384, -0.8660254037844386}; 48 | 49 | float carrier_19[] = {0.0, 0.5, 0.8660254037844386, 1.0, 0.8660254037844388, 0.5, 1.2246467991473532e-16, -0.5, -0.8660254037844384, -1.0, -0.8660254037844386, -0.5}; 50 | 51 | int phase_38 = 0; 52 | int phase_19 = 0; 53 | 54 | 55 | float downsample_factor; 56 | 57 | 58 | float *audio_buffer; 59 | int audio_index = 0; 60 | int audio_len = 0; 61 | float audio_pos; 62 | 63 | float fir_buffer_left[FIR_TAPS] = {0}; 64 | float fir_buffer_right[FIR_TAPS] = {0}; 65 | int fir_index = 0; 66 | int channels; 67 | float left_max=1, right_max=1; // start compressor with low gain 68 | 69 | SNDFILE *inf; 70 | 71 | 72 | 73 | float *alloc_empty_buffer(size_t length) { 74 | float *p = malloc(length * sizeof(float)); 75 | if(p == NULL) return NULL; 76 | 77 | bzero(p, length * sizeof(float)); 78 | 79 | return p; 80 | } 81 | 82 | 83 | int fm_mpx_open(char *filename, size_t len) { 84 | length = len; 85 | 86 | if(filename != NULL) { 87 | // Open the input file 88 | SF_INFO sfinfo; 89 | 90 | // stdin or file on the filesystem? 91 | if(filename[0] == '-') { 92 | if(! (inf = sf_open_fd(fileno(stdin), SFM_READ, &sfinfo, 0))) { 93 | fprintf(stderr, "Error: could not open stdin for audio input.\n") ; 94 | return -1; 95 | } else { 96 | printf("Using stdin for audio input.\n"); 97 | } 98 | } else { 99 | if(! (inf = sf_open(filename, SFM_READ, &sfinfo))) { 100 | fprintf(stderr, "Error: could not open input file %s.\n", filename) ; 101 | return -1; 102 | } else { 103 | printf("Using audio file: %s\n", filename); 104 | } 105 | } 106 | 107 | int in_samplerate = sfinfo.samplerate; 108 | downsample_factor = 228000. / in_samplerate; 109 | 110 | printf("Input: %d Hz, upsampling factor: %.2f\n", in_samplerate, downsample_factor); 111 | 112 | channels = sfinfo.channels; 113 | if(channels > 1) { 114 | printf("%d channels, generating stereo multiplex.\n", channels); 115 | } else { 116 | printf("1 channel, monophonic operation.\n"); 117 | } 118 | 119 | // Choose a cutoff frequency for the low-pass FIR filter 120 | float cutoff_freq = 15700; 121 | //float cutoff_freq = 3000; //For NBFM 122 | if(in_samplerate/2 < cutoff_freq) cutoff_freq = in_samplerate/2 * .8; 123 | 124 | 125 | // Create the low-pass FIR filter, with pre-emphasis 126 | double window, firlowpass, firpreemph , sincpos; 127 | double gain=FIR_PHASES/25.0; // Why??? Maybe gain adjustment for preemphais 128 | 129 | // IIR pre-emphasis filter 130 | // Reference material: http://jontio.zapto.org/hda1/preempiir.pdf 131 | double tau=75e-6; 132 | double delta=1.96e-6; 133 | double taup, deltap, bp, ap, a0, a1, b1; 134 | taup=1.0/(2.0*(in_samplerate*FIR_PHASES))/tan( 1.0/(2*tau*(in_samplerate*FIR_PHASES) )); 135 | deltap=1.0/(2.0*(in_samplerate*FIR_PHASES))/tan( 1.0/(2*delta*(in_samplerate*FIR_PHASES) )); 136 | bp=sqrt( -taup*taup + sqrt(taup*taup*taup*taup + 8.0*taup*taup*deltap*deltap) ) / 2.0 ; 137 | ap=sqrt( 2*bp*bp + taup*taup ); 138 | a0=( 2.0*ap + 1/(in_samplerate*FIR_PHASES) )/(2.0*bp + 1/(in_samplerate*FIR_PHASES) ); 139 | a1=(-2.0*ap + 1/(in_samplerate*FIR_PHASES) )/(2.0*bp + 1/(in_samplerate*FIR_PHASES) ); 140 | b1=( 2.0*bp + 1/(in_samplerate*FIR_PHASES) )/(2.0*bp + 1/(in_samplerate*FIR_PHASES) ); 141 | double x=0,y=0; 142 | 143 | for(int i=0; i= downsample_factor) { 196 | audio_pos -= downsample_factor; 197 | 198 | if(audio_len <= channels ) { 199 | for(int j=0; j<2; j++) { // one retry 200 | audio_len = sf_read_float(inf, audio_buffer, length); 201 | if (audio_len < 0) { 202 | fprintf(stderr, "Error reading audio\n"); 203 | return -1; 204 | } 205 | if(audio_len == 0) { 206 | if( sf_seek(inf, 0, SEEK_SET) < 0 ) { 207 | fprintf(stderr, "Could not rewind in audio file, terminating\n"); 208 | return -1; 209 | } 210 | } else { 211 | break; 212 | } 213 | } 214 | audio_index = 0; 215 | } else { 216 | audio_index += channels; 217 | audio_len -= channels; 218 | } 219 | 220 | fir_index++; // fir_index will point to newest valid data soon 221 | if(fir_index >= FIR_TAPS) fir_index = 0; 222 | // Store the current sample(s) into the FIR filter's ring buffer 223 | fir_buffer_left[fir_index] = audio_buffer[audio_index]; 224 | if(channels > 1) { 225 | fir_buffer_right[fir_index] = audio_buffer[audio_index+1]; 226 | } 227 | } // if need new sample 228 | 229 | // Polyphase FIR filter 230 | float out_left = 0; 231 | float out_right = 0; 232 | // Calculate which FIR phase to use 233 | //int iphase = FIR_PHASES-1 - ((int) (audio_pos/downsample_factor*FIR_PHASES) ); 234 | int iphase = ((int) (audio_pos*FIR_PHASES/downsample_factor) );// I think this is correct 235 | //int iphase=FIR_PHASES-1; // test override 236 | //printf("%d %d \n",fir_index,iphase); // diagnostics 237 | // Sanity checks 238 | if ( iphase < 0 ) {iphase=0; printf("low\n"); }// Seems to run faster with these checks in place 239 | if ( iphase >= FIR_PHASES ) {iphase=FIR_PHASES-2; printf("high\n"); } 240 | 241 | if( channels > 1 ) 242 | { 243 | for(int fi=0; fileft_max ) 271 | { 272 | left_max+= (left_abs-left_max)*compressor_attack; 273 | } 274 | else 275 | { 276 | left_max*=compressor_decay; 277 | } 278 | 279 | if( channels > 1 ) 280 | { 281 | right_abs=fabsf(out_right); 282 | if( right_abs>right_max ) 283 | { 284 | right_max+= (right_abs-right_max)*compressor_attack; 285 | } 286 | else 287 | { 288 | right_max*=compressor_decay; 289 | } 290 | if( 1 )// Experimental joint compressor mode 291 | { 292 | if( left_max > right_max ) 293 | right_max=left_max; 294 | else if( left_max < right_max ) 295 | left_max=right_max; 296 | } 297 | out_right=out_right/(right_max+compressor_max_gain_recip); 298 | } 299 | out_left= out_left/(left_max+compressor_max_gain_recip); // Adjust volume with limited maximum gain 300 | 301 | // Generate the stereo mpx 302 | if( channels > 1 ) { 303 | mpx_buffer[i] += 4.05*(out_left+out_right) + // Stereo sum signal 304 | 4.05 * carrier_38[phase_38] * (out_left-out_right) + // Stereo difference signal 305 | .9*carrier_19[phase_19]; // Stereo pilot tone 306 | 307 | phase_19++; 308 | phase_38++; 309 | if(phase_19 >= 12) phase_19 = 0; 310 | if(phase_38 >= 6) phase_38 = 0; 311 | } 312 | else 313 | { 314 | mpx_buffer[i] = 315 | mpx_buffer[i] + // RDS data samples are currently in mpx_buffer :to be Remove in NBFM 316 | 9.0*out_left; // Unmodulated monophonic signal 317 | } 318 | 319 | audio_pos++; 320 | 321 | } 322 | 323 | return 0; 324 | } 325 | 326 | 327 | int fm_mpx_close() { 328 | if(sf_close(inf) ) { 329 | fprintf(stderr, "Error closing audio file"); 330 | } 331 | 332 | if(audio_buffer != NULL) free(audio_buffer); 333 | 334 | return 0; 335 | } 336 | -------------------------------------------------------------------------------- /src/fm_mpx.h: -------------------------------------------------------------------------------- 1 | /* 2 | PiFmRds - FM/RDS transmitter for the Raspberry Pi 3 | Copyright (C) 2014 Christophe Jacquet, F8FTK 4 | 5 | See https://github.com/ChristopheJacquet/PiFmRds 6 | 7 | rds_wav.c is a test program that writes a RDS baseband signal to a WAV 8 | file. It requires libsndfile. 9 | 10 | This program is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | This program is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU General Public License for more details. 19 | 20 | You should have received a copy of the GNU General Public License 21 | along with this program. If not, see . 22 | */ 23 | 24 | extern int fm_mpx_open(char *filename, size_t len); 25 | extern int fm_mpx_get_samples(float *mpx_buffer); 26 | extern int fm_mpx_close(); -------------------------------------------------------------------------------- /src/generate_pulses.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | 4 | # PiFmRds - FM/RDS transmitter for the Raspberry Pi 5 | # Copyright (C) 2014 Christophe Jacquet, F8FTK 6 | # 7 | # See https://github.com/ChristopheJacquet/PiFmRds 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | # This program generates a WAV file with a 1-second sine wave at 440 Hz, 23 | # followed by a 1-second silence. 24 | 25 | 26 | import scipy.io.wavfile as wavfile 27 | import numpy 28 | 29 | sample_rate = 228000 30 | samples = numpy.zeros(2 * sample_rate, dtype=numpy.dtype('>i2')) 31 | 32 | # 1-second tune 33 | samples[:sample_rate] = (numpy.sin(2*numpy.pi*440*numpy.arange(sample_rate)/sample_rate) 34 | * 20000).astype(numpy.dtype('>i2')) 35 | 36 | wavfile.write("pulses.wav", sample_rate, samples) 37 | -------------------------------------------------------------------------------- /src/generate_waveforms.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | 4 | # PiFmRds - FM/RDS transmitter for the Raspberry Pi 5 | # Copyright (C) 2014 Christophe Jacquet, F8FTK 6 | # 7 | # See https://github.com/ChristopheJacquet/PiFmRds 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program. If not, see . 21 | 22 | # This program generates the waveform of a single biphase symbol 23 | # 24 | # This program uses Pydemod, see https://github.com/ChristopheJacquet/Pydemod 25 | 26 | import pydemod.app.rds as rds 27 | import numpy 28 | import scipy.io.wavfile as wavfile 29 | import io 30 | import matplotlib.pyplot as plt 31 | 32 | sample_rate = 228000 33 | 34 | outc = io.open("waveforms.c", mode="w", encoding="utf8") 35 | outh = io.open("waveforms.h", mode="w", encoding="utf8") 36 | 37 | header = u""" 38 | /* This file was automatically generated by "generate_waveforms.py". 39 | (C) 2014 Christophe Jacquet. 40 | Released under the GNU GPL v3 license. 41 | */ 42 | 43 | """ 44 | 45 | outc.write(header) 46 | outh.write(header) 47 | 48 | def generate_bit(name): 49 | offset = 240 50 | l = 96 51 | count = 2 52 | 53 | 54 | sample = numpy.zeros(3*l) 55 | sample[l] = 1 56 | sample[2*l] = -1 57 | 58 | # Apply the data-shaping filter 59 | sf = rds.pulse_shaping_filter(96*8, 228000) 60 | shapedSamples = numpy.convolve(sample, sf) 61 | 62 | 63 | out = shapedSamples[528-288:528+288] #[offset:offset+l*count] 64 | #plt.plot(sf) 65 | #plt.plot(out) 66 | #plt.show() 67 | 68 | iout = (out * 20000./max(abs(out)) ).astype(numpy.dtype('>i2')) 69 | wavfile.write(u"waveform_{}.wav".format(name), sample_rate, iout) 70 | 71 | outc.write(u"float waveform_{name}[] = {{{values}}};\n\n".format( 72 | name = name, 73 | values = u", ".join(map(unicode, out/2.5)))) 74 | # note: need to limit the amplitude so as not to saturate when the biphase 75 | # waveforms are summed 76 | 77 | outh.write(u"extern float waveform_{name}[{size}];\n".format(name=name, size=len(out))) 78 | 79 | 80 | generate_bit("biphase") 81 | 82 | outc.close() 83 | outh.close() -------------------------------------------------------------------------------- /src/mailbox.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012, Broadcom Europe Ltd. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright 10 | notice, this list of conditions and the following disclaimer in the 11 | documentation and/or other materials provided with the distribution. 12 | * Neither the name of the copyright holder nor the 13 | names of its contributors may be used to endorse or promote products 14 | derived from this software without specific prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY 20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | #include "mailbox.h" 40 | 41 | #define PAGE_SIZE (4*1024) 42 | 43 | void *mapmem(unsigned base, unsigned size) 44 | { 45 | int mem_fd; 46 | unsigned offset = base % PAGE_SIZE; 47 | base = base - offset; 48 | /* open /dev/mem */ 49 | if ((mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) { 50 | printf("can't open /dev/mem\nThis program should be run as root. Try prefixing command with: sudo\n"); 51 | exit (-1); 52 | } 53 | void *mem = mmap( 54 | 0, 55 | size, 56 | PROT_READ|PROT_WRITE, 57 | MAP_SHARED/*|MAP_FIXED*/, 58 | mem_fd, 59 | base); 60 | #ifdef DEBUG 61 | printf("base=0x%x, mem=%p\n", base, mem); 62 | #endif 63 | if (mem == MAP_FAILED) { 64 | printf("mmap error %d\n", (int)mem); 65 | exit (-1); 66 | } 67 | close(mem_fd); 68 | return (char *)mem + offset; 69 | } 70 | 71 | void *unmapmem(void *addr, unsigned size) 72 | { 73 | int s = munmap(addr, size); 74 | if (s != 0) { 75 | printf("munmap error %d\n", s); 76 | exit (-1); 77 | } 78 | 79 | return NULL; 80 | } 81 | 82 | /* 83 | * use ioctl to send mbox property message 84 | */ 85 | 86 | static int mbox_property(int file_desc, void *buf) 87 | { 88 | int ret_val = ioctl(file_desc, IOCTL_MBOX_PROPERTY, buf); 89 | 90 | if (ret_val < 0) { 91 | printf("ioctl_set_msg failed:%d\n", ret_val); 92 | } 93 | 94 | #ifdef DEBUG 95 | unsigned *p = buf; int i; unsigned size = *(unsigned *)buf; 96 | for (i=0; i= 0) { 252 | printf("Using mbox device " DEVICE_FILE_NAME ".\n"); 253 | return file_desc; 254 | } 255 | 256 | // Try to create one 257 | unlink(LOCAL_DEVICE_FILE_NAME); 258 | if(mknod(LOCAL_DEVICE_FILE_NAME, S_IFCHR|0600, makedev(MAJOR_NUM_A, 0)) >= 0 && 259 | (file_desc = open(LOCAL_DEVICE_FILE_NAME, 0)) >= 0) { 260 | printf("Using local mbox device file with major %d.\n", MAJOR_NUM_A); 261 | return file_desc; 262 | } 263 | 264 | unlink(LOCAL_DEVICE_FILE_NAME); 265 | if(mknod(LOCAL_DEVICE_FILE_NAME, S_IFCHR|0600, makedev(MAJOR_NUM_B, 0)) >= 0 && 266 | (file_desc = open(LOCAL_DEVICE_FILE_NAME, 0)) >= 0) { 267 | printf("Using local mbox device file with major %d.\n", MAJOR_NUM_B); 268 | return file_desc; 269 | } 270 | 271 | return -1; 272 | } 273 | 274 | void mbox_close(int file_desc) { 275 | close(file_desc); 276 | } 277 | -------------------------------------------------------------------------------- /src/mailbox.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012, Broadcom Europe Ltd. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright 10 | notice, this list of conditions and the following disclaimer in the 11 | documentation and/or other materials provided with the distribution. 12 | * Neither the name of the copyright holder nor the 13 | names of its contributors may be used to endorse or promote products 14 | derived from this software without specific prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY 20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include 29 | 30 | // Newer kernels (>= 4.1) use major 249, older ones major 100. 31 | #define MAJOR_NUM_A 249 32 | #define MAJOR_NUM_B 100 33 | #define IOCTL_MBOX_PROPERTY _IOWR(MAJOR_NUM_B, 0, char *) 34 | #define DEVICE_FILE_NAME "/dev/vcio" 35 | #define LOCAL_DEVICE_FILE_NAME "mbox" 36 | 37 | int mbox_open(); 38 | void mbox_close(int file_desc); 39 | 40 | unsigned get_version(int file_desc); 41 | unsigned mem_alloc(int file_desc, unsigned size, unsigned align, unsigned flags); 42 | unsigned mem_free(int file_desc, unsigned handle); 43 | unsigned mem_lock(int file_desc, unsigned handle); 44 | unsigned mem_unlock(int file_desc, unsigned handle); 45 | void *mapmem(unsigned base, unsigned size); 46 | void *unmapmem(void *addr, unsigned size); 47 | 48 | unsigned execute_code(int file_desc, unsigned code, unsigned r0, unsigned r1, unsigned r2, unsigned r3, unsigned r4, unsigned r5); 49 | unsigned execute_qpu(int file_desc, unsigned num_qpus, unsigned control, unsigned noflush, unsigned timeout); 50 | unsigned qpu_enable(int file_desc, unsigned enable); 51 | -------------------------------------------------------------------------------- /src/noise_22050.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/F5OEO/PiFmRds/2707ecc8ab32164060de53e4774e682a718aecb3/src/noise_22050.wav -------------------------------------------------------------------------------- /src/pi_fm_rds.c: -------------------------------------------------------------------------------- 1 | /* 2 | * PiFmRds - FM/RDS transmitter for the Raspberry Pi 3 | * Copyright (C) 2014, 2015 Christophe Jacquet, F8FTK 4 | * Copyright (C) 2012, 2015 Richard Hirst 5 | * Copyright (C) 2012 Oliver Mattos and Oskar Weigl 6 | * 7 | * See https://github.com/ChristopheJacquet/PiFmRds 8 | * 9 | * PI-FM-RDS: RaspberryPi FM transmitter, with RDS. 10 | * 11 | * This file contains the VHF FM modulator. All credit goes to the original 12 | * authors, Oliver Mattos and Oskar Weigl for the original idea, and to 13 | * Richard Hirst for using the Pi's DMA engine, which reduced CPU usage 14 | * dramatically. 15 | * 16 | * I (Christophe Jacquet) have adapted their idea to transmitting samples 17 | * at 228 kHz, allowing to build the 57 kHz subcarrier for RDS BPSK data. 18 | * 19 | * To make it work on the Raspberry Pi 2, I used a fix by Richard Hirst 20 | * (again) to request memory using Broadcom's mailbox interface. This fix 21 | * was published for ServoBlaster here: 22 | * https://www.raspberrypi.org/forums/viewtopic.php?p=699651#p699651 23 | * 24 | * Never use this to transmit VHF-FM data through an antenna, as it is 25 | * illegal in most countries. This code is for testing purposes only. 26 | * Always connect a shielded transmission line from the RaspberryPi directly 27 | * to a radio receiver, so as *not* to emit radio waves. 28 | * 29 | * --------------------------------------------------------------------------- 30 | * These are the comments from Richard Hirst's version: 31 | * 32 | * RaspberryPi based FM transmitter. For the original idea, see: 33 | * 34 | * http://www.icrobotics.co.uk/wiki/index.php/Turning_the_Raspberry_Pi_Into_an_FM_Transmitter 35 | * 36 | * All credit to Oliver Mattos and Oskar Weigl for creating the original code. 37 | * 38 | * I have taken their idea and reworked it to use the Pi DMA engine, so 39 | * reducing the CPU overhead for playing a .wav file from 100% to about 1.6%. 40 | * 41 | * I have implemented this in user space, using an idea I picked up from Joan 42 | * on the Raspberry Pi forums - credit to Joan for the DMA from user space 43 | * idea. 44 | * 45 | * The idea of feeding the PWM FIFO in order to pace DMA control blocks comes 46 | * from ServoBlaster, and I take credit for that :-) 47 | * 48 | * This code uses DMA channel 5 and the PWM hardware, with no regard for 49 | * whether something else might be trying to use it at the same time (such as 50 | * the 3.5mm jack audio driver). 51 | * 52 | * I know nothing much about sound, subsampling, or FM broadcasting, so it is 53 | * quite likely the sound quality produced by this code can be improved by 54 | * someone who knows what they are doing. There may be issues realting to 55 | * caching, as the user space process just writes to its virtual address space, 56 | * and expects the DMA controller to see the data; it seems to work for me 57 | * though. 58 | * 59 | * NOTE: THIS CODE MAY WELL CRASH YOUR PI, TRASH YOUR FILE SYSTEMS, AND 60 | * POTENTIALLY EVEN DAMAGE YOUR HARDWARE. THIS IS BECAUSE IT STARTS UP THE DMA 61 | * CONTROLLER USING MEMORY OWNED BY A USER PROCESS. IF THAT USER PROCESS EXITS 62 | * WITHOUT STOPPING THE DMA CONTROLLER, ALL HELL COULD BREAK LOOSE AS THE 63 | * MEMORY GETS REALLOCATED TO OTHER PROCESSES WHILE THE DMA CONTROLLER IS STILL 64 | * USING IT. I HAVE ATTEMPTED TO MINIMISE ANY RISK BY CATCHING SIGNALS AND 65 | * RESETTING THE DMA CONTROLLER BEFORE EXITING, BUT YOU HAVE BEEN WARNED. I 66 | * ACCEPT NO LIABILITY OR RESPONSIBILITY FOR ANYTHING THAT HAPPENS AS A RESULT 67 | * OF YOU RUNNING THIS CODE. IF IT BREAKS, YOU GET TO KEEP ALL THE PIECES. 68 | * 69 | * NOTE ALSO: THIS MAY BE ILLEGAL IN YOUR COUNTRY. HERE ARE SOME COMMENTS 70 | * FROM MORE KNOWLEDGEABLE PEOPLE ON THE FORUM: 71 | * 72 | * "Just be aware that in some countries FM broadcast and especially long 73 | * distance FM broadcast could get yourself into trouble with the law, stray FM 74 | * broadcasts over Airband aviation is also strictly forbidden." 75 | * 76 | * "A low pass filter is really really required for this as it has strong 77 | * harmonics at the 3rd, 5th 7th and 9th which sit in licensed and rather 78 | * essential bands, ie GSM, HAM, emergency services and others. Polluting these 79 | * frequencies is immoral and dangerous, whereas "breaking in" on FM bands is 80 | * just plain illegal." 81 | * 82 | * "Don't get caught, this GPIO use has the potential to exceed the legal 83 | * limits by about 2000% with a proper aerial." 84 | * 85 | * 86 | * As for the original code, this code is released under the GPL. 87 | * 88 | * Richard Hirst December 2012 89 | */ 90 | 91 | #include 92 | #include 93 | #include 94 | #include 95 | #include 96 | #include 97 | #include 98 | #include 99 | #include 100 | #include 101 | #include 102 | #include 103 | #include 104 | #include 105 | #include 106 | 107 | #include "rds.h" 108 | #include "fm_mpx.h" 109 | #include "control_pipe.h" 110 | 111 | #include "mailbox.h" 112 | #define MBFILE DEVICE_FILE_NAME /* From mailbox.h */ 113 | 114 | #if (RASPI)==1 115 | #define PERIPH_VIRT_BASE 0x20000000 116 | #define PERIPH_PHYS_BASE 0x7e000000 117 | #define DRAM_PHYS_BASE 0x40000000 118 | #define MEM_FLAG 0x0c 119 | #elif (RASPI)==2 120 | #define PERIPH_VIRT_BASE 0x3f000000 121 | #define PERIPH_PHYS_BASE 0x7e000000 122 | #define DRAM_PHYS_BASE 0xc0000000 123 | #define MEM_FLAG 0x04 124 | #else 125 | #error Unknown Raspberry Pi version (variable RASPI) 126 | #endif 127 | 128 | #define NUM_SAMPLES 50000 129 | #define NUM_CBS (NUM_SAMPLES * 2) 130 | 131 | #define BCM2708_DMA_NO_WIDE_BURSTS (1<<26) 132 | #define BCM2708_DMA_WAIT_RESP (1<<3) 133 | #define BCM2708_DMA_D_DREQ (1<<6) 134 | #define BCM2708_DMA_PER_MAP(x) ((x)<<16) 135 | #define BCM2708_DMA_END (1<<1) 136 | #define BCM2708_DMA_RESET (1<<31) 137 | #define BCM2708_DMA_INT (1<<2) 138 | 139 | #define DMA_CS (0x00/4) 140 | #define DMA_CONBLK_AD (0x04/4) 141 | #define DMA_DEBUG (0x20/4) 142 | 143 | #define DMA_NUMBER 5 144 | #define DMA_BASE_OFFSET 0x00007000 145 | #define DMA_LEN 0xe24 146 | #define PWM_BASE_OFFSET 0x0020C000 147 | #define PWM_LEN 0x28 148 | #define CLK_BASE_OFFSET 0x00101000 149 | #define CLK_LEN 0x1300 150 | #define GPIO_BASE_OFFSET 0x00200000 151 | #define GPIO_LEN 0x100 152 | 153 | #define DMA_VIRT_BASE (PERIPH_VIRT_BASE + DMA_BASE_OFFSET) 154 | #define PWM_VIRT_BASE (PERIPH_VIRT_BASE + PWM_BASE_OFFSET) 155 | #define CLK_VIRT_BASE (PERIPH_VIRT_BASE + CLK_BASE_OFFSET) 156 | #define GPIO_VIRT_BASE (PERIPH_VIRT_BASE + GPIO_BASE_OFFSET) 157 | #define PCM_VIRT_BASE (PERIPH_VIRT_BASE + PCM_BASE_OFFSET) 158 | 159 | #define PWM_PHYS_BASE (PERIPH_PHYS_BASE + PWM_BASE_OFFSET) 160 | #define PCM_PHYS_BASE (PERIPH_PHYS_BASE + PCM_BASE_OFFSET) 161 | #define GPIO_PHYS_BASE (PERIPH_PHYS_BASE + GPIO_BASE_OFFSET) 162 | 163 | 164 | #define PWM_CTL (0x00/4) 165 | #define PWM_DMAC (0x08/4) 166 | #define PWM_RNG1 (0x10/4) 167 | #define PWM_FIFO (0x18/4) 168 | 169 | #define PWMCLK_CNTL 40 170 | #define PWMCLK_DIV 41 171 | 172 | #define CM_GP0DIV (0x7e101074) 173 | #define CM_PLLCFRAC (0x7e102220) 174 | 175 | #define CORECLK_CNTL (0x08/4) 176 | #define CORECLK_DIV (0x0c/4) 177 | #define GPCLK_CNTL (0x70/4) 178 | #define GPCLK_DIV (0x74/4) 179 | #define EMMCCLK_CNTL (0x1C0/4) 180 | #define EMMCCLK_DIV (0x1C4/4) 181 | #define PLLC_CTRL (0x1120/4) 182 | #define PLLC_FRAC (0x1220/4) 183 | 184 | #define PWMCTL_MODE1 (1<<1) 185 | #define PWMCTL_PWEN1 (1<<0) 186 | #define PWMCTL_CLRF (1<<6) 187 | #define PWMCTL_USEF1 (1<<5) 188 | 189 | #define PWMDMAC_ENAB (1<<31) 190 | // I think this means it requests as soon as there is one free slot in the FIFO 191 | // which is what we want as burst DMA would mess up our timing. 192 | #define PWMDMAC_THRSHLD ((15<<8)|(15<<0)) 193 | 194 | #define GPFSEL0 (0x00/4) 195 | 196 | #define PLLFREQ 500000000. // PLLD is running at 500MHz 197 | 198 | // The deviation specifies how wide the signal is. 199 | // Use 75kHz for WBFM (broadcast radio) 200 | // and about 2.5kHz for NBFM (walkie-talkie style radio) 201 | #define DEVIATION 75000 202 | 203 | 204 | typedef struct { 205 | uint32_t info, src, dst, length, 206 | stride, next, pad[2]; 207 | } dma_cb_t; 208 | 209 | #define BUS_TO_PHYS(x) ((x)&~0xC0000000) 210 | 211 | 212 | static struct { 213 | int handle; /* From mbox_open() */ 214 | unsigned mem_ref; /* From mem_alloc() */ 215 | unsigned bus_addr; /* From mem_lock() */ 216 | uint8_t *virt_addr; /* From mapmem() */ 217 | } mbox; 218 | 219 | 220 | 221 | static volatile uint32_t *pwm_reg; 222 | static volatile uint32_t *clk_reg; 223 | static volatile uint32_t *dma_reg; 224 | static volatile uint32_t *gpio_reg; 225 | 226 | struct control_data_s { 227 | dma_cb_t cb[NUM_CBS]; 228 | uint32_t sample[NUM_SAMPLES]; 229 | }; 230 | 231 | #define PAGE_SIZE 4096 232 | #define PAGE_SHIFT 12 233 | #define NUM_PAGES ((sizeof(struct control_data_s) + PAGE_SIZE - 1) >> PAGE_SHIFT) 234 | 235 | static struct control_data_s *ctl; 236 | 237 | static void 238 | print_clock_tree(void) 239 | { 240 | 241 | if( clk_reg==NULL ) return; 242 | #define PLLA_CTRL (0x1100/4) 243 | #define PLLA_FRAC (0x1200/4) 244 | #define PLLA_DSI0 (0x1300/4) 245 | #define PLLA_CORE (0x1400/4) 246 | #define PLLA_PER (0x1500/4) 247 | #define PLLA_CCP2 (0x1600/4) 248 | 249 | #define PLLB_CTRL (0x11e0/4) 250 | #define PLLB_FRAC (0x12e0/4) 251 | #define PLLB_ARM (0x13e0/4) 252 | #define PLLB_SP0 (0x14e0/4) 253 | #define PLLB_SP1 (0x15e0/4) 254 | #define PLLB_SP2 (0x16e0/4) 255 | 256 | #define PLLC_CTRL (0x1120/4) 257 | #define PLLC_FRAC (0x1220/4) 258 | #define PLLC_CORE2 (0x1320/4) 259 | #define PLLC_CORE1 (0x1420/4) 260 | #define PLLC_PER (0x1520/4) 261 | #define PLLC_CORE0 (0x1620/4) 262 | 263 | #define PLLD_CTRL (0x1140/4) 264 | #define PLLD_FRAC (0x1240/4) 265 | #define PLLD_DSI0 (0x1340/4) 266 | #define PLLD_CORE (0x1440/4) 267 | #define PLLD_PER (0x1540/4) 268 | #define PLLD_DSI1 (0x1640/4) 269 | 270 | #define PLLH_CTRL (0x1160/4) 271 | #define PLLH_FRAC (0x1260/4) 272 | #define PLLH_AUX (0x1360/4) 273 | #define PLLH_RCAL (0x1460/4) 274 | #define PLLH_PIX (0x1560/4) 275 | #define PLLH_STS (0x1660/4) 276 | 277 | #define XOSC_CTRL (0x1190/4) 278 | printf("PLLC_DIG0=%08x\n",clk_reg[(0x1020/4)]); 279 | printf("PLLC_DIG1=%08x\n",clk_reg[(0x1024/4)]); 280 | printf("PLLC_DIG2=%08x\n",clk_reg[(0x1028/4)]); 281 | printf("PLLC_DIG3=%08x\n",clk_reg[(0x102c/4)]); 282 | printf("PLLC_ANA0=%08x\n",clk_reg[(0x1030/4)]); 283 | printf("PLLC_ANA1=%08x\n",clk_reg[(0x1034/4)]); 284 | printf("PLLC_ANA2=%08x\n",clk_reg[(0x1038/4)]); 285 | printf("PLLC_ANA3=%08x\n",clk_reg[(0x103c/4)]); 286 | printf("PLLC_DIG0R=%08x\n",clk_reg[(0x1820/4)]); 287 | printf("PLLC_DIG1R=%08x\n",clk_reg[(0x1824/4)]); 288 | printf("PLLC_DIG2R=%08x\n",clk_reg[(0x1828/4)]); 289 | printf("PLLC_DIG3R=%08x\n",clk_reg[(0x182c/4)]); 290 | 291 | printf("GNRIC CTL=%08x DIV=%8x ",clk_reg[ 0],clk_reg[ 1]); 292 | printf("VPU CTL=%08x DIV=%8x\n",clk_reg[ 2],clk_reg[ 3]); 293 | printf("SYS CTL=%08x DIV=%8x ",clk_reg[ 4],clk_reg[ 5]); 294 | printf("PERIA CTL=%08x DIV=%8x\n",clk_reg[ 6],clk_reg[ 7]); 295 | printf("PERII CTL=%08x DIV=%8x ",clk_reg[ 8],clk_reg[ 9]); 296 | printf("H264 CTL=%08x DIV=%8x\n",clk_reg[10],clk_reg[11]); 297 | printf("ISP CTL=%08x DIV=%8x ",clk_reg[12],clk_reg[13]); 298 | printf("V3D CTL=%08x DIV=%8x\n",clk_reg[14],clk_reg[15]); 299 | 300 | printf("CAM0 CTL=%08x DIV=%8x ",clk_reg[16],clk_reg[17]); 301 | printf("CAM1 CTL=%08x DIV=%8x\n",clk_reg[18],clk_reg[19]); 302 | printf("CCP2 CTL=%08x DIV=%8x ",clk_reg[20],clk_reg[21]); 303 | printf("DSI0E CTL=%08x DIV=%8x\n",clk_reg[22],clk_reg[23]); 304 | printf("DSI0P CTL=%08x DIV=%8x ",clk_reg[24],clk_reg[25]); 305 | printf("DPI CTL=%08x DIV=%8x\n",clk_reg[26],clk_reg[27]); 306 | printf("GP0 CTL=%08x DIV=%8x ",clk_reg[28],clk_reg[29]); 307 | printf("GP1 CTL=%08x DIV=%8x\n",clk_reg[30],clk_reg[31]); 308 | 309 | printf("GP2 CTL=%08x DIV=%8x ",clk_reg[32],clk_reg[33]); 310 | printf("HSM CTL=%08x DIV=%8x\n",clk_reg[34],clk_reg[35]); 311 | printf("OTP CTL=%08x DIV=%8x ",clk_reg[36],clk_reg[37]); 312 | printf("PCM CTL=%08x DIV=%8x\n",clk_reg[38],clk_reg[39]); 313 | printf("PWM CTL=%08x DIV=%8x ",clk_reg[40],clk_reg[41]); 314 | printf("SLIM CTL=%08x DIV=%8x\n",clk_reg[42],clk_reg[43]); 315 | printf("SMI CTL=%08x DIV=%8x ",clk_reg[44],clk_reg[45]); 316 | printf("SMPS CTL=%08x DIV=%8x\n",clk_reg[46],clk_reg[47]); 317 | 318 | printf("TCNT CTL=%08x DIV=%8x ",clk_reg[48],clk_reg[49]); 319 | printf("TEC CTL=%08x DIV=%8x\n",clk_reg[50],clk_reg[51]); 320 | printf("TD0 CTL=%08x DIV=%8x ",clk_reg[52],clk_reg[53]); 321 | printf("TD1 CTL=%08x DIV=%8x\n",clk_reg[54],clk_reg[55]); 322 | 323 | printf("TSENS CTL=%08x DIV=%8x ",clk_reg[56],clk_reg[57]); 324 | printf("TIMER CTL=%08x DIV=%8x\n",clk_reg[58],clk_reg[59]); 325 | printf("UART CTL=%08x DIV=%8x ",clk_reg[60],clk_reg[61]); 326 | printf("VEC CTL=%08x DIV=%8x\n",clk_reg[62],clk_reg[63]); 327 | 328 | printf("PULSE CTL=%08x DIV=%8x ",clk_reg[100],clk_reg[101]); 329 | printf("PLLT CTL=%08x DIV=????????\n",clk_reg[76]); 330 | 331 | printf("DSI1E CTL=%08x DIV=%8x ",clk_reg[86],clk_reg[87]); 332 | printf("DSI1P CTL=%08x DIV=%8x\n",clk_reg[88],clk_reg[89]); 333 | printf("AVE0 CTL=%08x DIV=%8x\n",clk_reg[90],clk_reg[91]); 334 | 335 | printf("SDC CTL=%08x DIV=%8x ",clk_reg[106],clk_reg[107]); 336 | printf("ARM CTL=%08x DIV=%8x\n",clk_reg[108],clk_reg[109]); 337 | printf("AVE0 CTL=%08x DIV=%8x ",clk_reg[110],clk_reg[111]); 338 | printf("EMMC CTL=%08x DIV=%8x\n",clk_reg[112],clk_reg[113]); 339 | 340 | // Sometimes calculated frequencies are off by a factor of 2 341 | // ANA1 bit 14 may indicate that a /2 prescaler is active 342 | printf("PLLA PDIV=%d NDIV=%d FRAC=%d ",(clk_reg[PLLA_CTRL]>>16) ,clk_reg[PLLA_CTRL]&0x3ff, clk_reg[PLLA_FRAC] ); 343 | printf(" %f MHz\n",19.2* ((float)(clk_reg[PLLA_CTRL]&0x3ff) + ((float)clk_reg[PLLA_FRAC])/((float)(1<<20))) ); 344 | printf("DSI0=%d CORE=%d PER=%d CCP2=%d\n\n",clk_reg[PLLA_DSI0],clk_reg[PLLA_CORE],clk_reg[PLLA_PER],clk_reg[PLLA_CCP2]); 345 | 346 | 347 | printf("PLLB PDIV=%d NDIV=%d FRAC=%d ",(clk_reg[PLLB_CTRL]>>16) ,clk_reg[PLLB_CTRL]&0x3ff, clk_reg[PLLB_FRAC] ); 348 | printf(" %f MHz\n",19.2* ((float)(clk_reg[PLLB_CTRL]&0x3ff) + ((float)clk_reg[PLLB_FRAC])/((float)(1<<20))) ); 349 | printf("ARM=%d SP0=%d SP1=%d SP2=%d\n\n",clk_reg[PLLB_ARM],clk_reg[PLLB_SP0],clk_reg[PLLB_SP1],clk_reg[PLLB_SP2]); 350 | 351 | printf("PLLC PDIV=%d NDIV=%d FRAC=%d ",(clk_reg[PLLC_CTRL]>>16) ,clk_reg[PLLC_CTRL]&0x3ff, clk_reg[PLLC_FRAC] ); 352 | printf(" %f MHz\n",19.2* ((float)(clk_reg[PLLC_CTRL]&0x3ff) + ((float)clk_reg[PLLC_FRAC])/((float)(1<<20))) ); 353 | printf("CORE2=%d CORE1=%d PER=%d CORE0=%d\n\n",clk_reg[PLLC_CORE2],clk_reg[PLLC_CORE1],clk_reg[PLLC_PER],clk_reg[PLLC_CORE0]); 354 | 355 | printf("PLLD PDIV=%d NDIV=%d FRAC=%d ",(clk_reg[PLLD_CTRL]>>16) ,clk_reg[PLLD_CTRL]&0x3ff, clk_reg[PLLD_FRAC] ); 356 | printf(" %f MHz\n",19.2* ((float)(clk_reg[PLLD_CTRL]&0x3ff) + ((float)clk_reg[PLLD_FRAC])/((float)(1<<20))) ); 357 | printf("DSI0=%d CORE=%d PER=%d DSI1=%d\n\n",clk_reg[PLLD_DSI0],clk_reg[PLLD_CORE],clk_reg[PLLD_PER],clk_reg[PLLD_DSI1]); 358 | 359 | printf("PLLH PDIV=%d NDIV=%d FRAC=%d ",(clk_reg[PLLH_CTRL]>>16) ,clk_reg[PLLH_CTRL]&0x3ff, clk_reg[PLLH_FRAC] ); 360 | printf(" %f MHz\n",19.2* ((float)(clk_reg[PLLH_CTRL]&0x3ff) + ((float)clk_reg[PLLH_FRAC])/((float)(1<<20))) ); 361 | printf("AUX=%d RCAL=%d PIX=%d STS=%d\n\n",clk_reg[PLLH_AUX],clk_reg[PLLH_RCAL],clk_reg[PLLH_PIX],clk_reg[PLLH_STS]); 362 | 363 | 364 | } 365 | 366 | static void 367 | udelay(int us) 368 | { 369 | struct timespec ts = { 0, us * 1000 }; 370 | 371 | nanosleep(&ts, NULL); 372 | } 373 | 374 | static void 375 | terminate(int num) 376 | { 377 | // Stop outputting and generating the clock. 378 | if (clk_reg && gpio_reg && mbox.virt_addr) { 379 | // Set GPIO4 to be an output (instead of ALT FUNC 0, which is the clock). 380 | gpio_reg[GPFSEL0] = (gpio_reg[GPFSEL0] & ~(7 << 12)) | (1 << 12); 381 | 382 | // Disable the clock generator. 383 | clk_reg[GPCLK_CNTL] = 0x5A; 384 | } 385 | 386 | if (dma_reg && mbox.virt_addr) { 387 | dma_reg[DMA_CS] = BCM2708_DMA_RESET; 388 | udelay(10); 389 | } 390 | 391 | fm_mpx_close(); 392 | close_control_pipe(); 393 | 394 | if (mbox.virt_addr != NULL) { 395 | unmapmem(mbox.virt_addr, NUM_PAGES * 4096); 396 | mem_unlock(mbox.handle, mbox.mem_ref); 397 | mem_free(mbox.handle, mbox.mem_ref); 398 | } 399 | 400 | print_clock_tree(); 401 | 402 | printf("Terminating: cleanly deactivated the DMA engine and killed the carrier.\n"); 403 | 404 | exit(num); 405 | } 406 | 407 | static void 408 | fatal(char *fmt, ...) 409 | { 410 | va_list ap; 411 | 412 | va_start(ap, fmt); 413 | vfprintf(stderr, fmt, ap); 414 | va_end(ap); 415 | terminate(0); 416 | } 417 | 418 | static uint32_t 419 | mem_virt_to_phys(void *virt) 420 | { 421 | uint32_t offset = (uint8_t *)virt - mbox.virt_addr; 422 | 423 | return mbox.bus_addr + offset; 424 | } 425 | 426 | static uint32_t 427 | mem_phys_to_virt(uint32_t phys) 428 | { 429 | return phys - (uint32_t)mbox.bus_addr + (uint32_t)mbox.virt_addr; 430 | } 431 | 432 | static void * 433 | map_peripheral(uint32_t base, uint32_t len) 434 | { 435 | int fd = open("/dev/mem", O_RDWR | O_SYNC); 436 | void * vaddr; 437 | 438 | if (fd < 0) 439 | fatal("Failed to open /dev/mem: %m.\n"); 440 | vaddr = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, base); 441 | if (vaddr == MAP_FAILED) 442 | fatal("Failed to map peripheral at 0x%08x: %m.\n", base); 443 | close(fd); 444 | 445 | return vaddr; 446 | } 447 | 448 | 449 | 450 | #define SUBSIZE 1 451 | #define DATA_SIZE 5000 452 | 453 | 454 | int tx(uint32_t carrier_freq, uint32_t divider, char *audio_file, uint16_t pi, char *ps, char *rt, float ppm, char *control_pipe) { 455 | // Catch all signals possible - it is vital we kill the DMA engine 456 | // on process exit! 457 | for (int i = 0; i < 64; i++) { 458 | struct sigaction sa; 459 | 460 | memset(&sa, 0, sizeof(sa)); 461 | sa.sa_handler = terminate; 462 | sigaction(i, &sa, NULL); 463 | } 464 | 465 | dma_reg = map_peripheral(DMA_VIRT_BASE, DMA_LEN); 466 | dma_reg = dma_reg+((0x100/sizeof(int))*(DMA_NUMBER)); 467 | pwm_reg = map_peripheral(PWM_VIRT_BASE, PWM_LEN); 468 | clk_reg = map_peripheral(CLK_VIRT_BASE, CLK_LEN); 469 | gpio_reg = map_peripheral(GPIO_VIRT_BASE, GPIO_LEN); 470 | 471 | // Use the mailbox interface to the VC to ask for physical memory. 472 | mbox.handle = mbox_open(); 473 | if (mbox.handle < 0) 474 | fatal("Failed to open mailbox. Check kernel support for vcio / BCM2708 mailbox.\n"); 475 | printf("Allocating physical memory: size = %d ", NUM_PAGES * 4096); 476 | if(! (mbox.mem_ref = mem_alloc(mbox.handle, NUM_PAGES * 4096, 4096, MEM_FLAG))) { 477 | fatal("Could not allocate memory.\n"); 478 | } 479 | // TODO: How do we know that succeeded? 480 | printf("mem_ref = %u ", mbox.mem_ref); 481 | if(! (mbox.bus_addr = mem_lock(mbox.handle, mbox.mem_ref))) { 482 | fatal("Could not lock memory.\n"); 483 | } 484 | printf("bus_addr = %x ", mbox.bus_addr); 485 | if(! (mbox.virt_addr = mapmem(BUS_TO_PHYS(mbox.bus_addr), NUM_PAGES * 4096))) { 486 | fatal("Could not map memory.\n"); 487 | } 488 | printf("virt_addr = %p\n", mbox.virt_addr); 489 | 490 | 491 | uint32_t freq_ctl; 492 | if( divider ) // PLL modulation 493 | { 494 | // switch the core over to PLLA 495 | clk_reg[CORECLK_DIV] = (0x5a<<24) | (4<<12) ; // core div 4 496 | udelay(100); 497 | clk_reg[CORECLK_CNTL] = (0x5a<<24) | (1<<4) | (4); // run, src=PLLA 498 | 499 | // switch the EMMC over to PLLD 500 | // FIXME should also adjust divider to keep same frequency 501 | // or possibly not if the gpu decides to change clocks due to low voltage 502 | // TODO put clocks back to their original state when we are done? 503 | int clktmp; 504 | clktmp = clk_reg[EMMCCLK_CNTL]; 505 | clk_reg[EMMCCLK_CNTL] = (0xF0F&clktmp) | (0x5a<<24) ; // clear run 506 | udelay(100); 507 | clk_reg[EMMCCLK_CNTL] = (0xF00&clktmp) | (0x5a<<24) | (6); // src=PLLD 508 | udelay(100); 509 | clk_reg[EMMCCLK_CNTL] = (0xF00&clktmp) | (0x5a<<24) | (1<<4) | (6); // run , src=PLLD 510 | 511 | // Adjust PLLC frequency 512 | freq_ctl = (unsigned int)(((carrier_freq*divider)/19.2e6)*((double)(1<<20))) ; // todo PPM 513 | clk_reg[PLLC_CTRL] = (0x5a<<24) | (0x21<<12) | (freq_ctl>>20 ); // integer part 514 | freq_ctl&=0xFFFFF; 515 | clk_reg[PLLC_FRAC] = (0x5a<<24) | (freq_ctl&0xFFFFC) ; // fractional part 516 | udelay(1000); 517 | 518 | // Program GPCLK integer division 519 | clktmp = clk_reg[GPCLK_CNTL]; 520 | clk_reg[GPCLK_CNTL] = (0xF0F&clktmp) | (0x5a<<24) ; // clear run 521 | udelay(100); 522 | clk_reg[GPCLK_DIV] = (0x5a<<24) | (divider<<12); 523 | udelay(100); 524 | clk_reg[GPCLK_CNTL] = (0x5a<<24) | (5); // src=PLLC 525 | udelay(100); 526 | clk_reg[GPCLK_CNTL] = (0x5a<<24) | (1<<4) | (5); // run , src=PLLC 527 | 528 | 529 | 530 | 531 | } 532 | else // MASH modulation 533 | { 534 | // Program GPCLK to use MASH setting 1, so fractional dividers work 535 | clk_reg[GPCLK_CNTL] = 0x5A << 24 | 6; // src 6 = PLLD 536 | udelay(100); 537 | clk_reg[GPCLK_CNTL] = 0x5A << 24 | 1 << 9 | 1 << 4 | 6; 538 | 539 | 540 | // Calculate the frequency control word 541 | // The fractional part is stored in the lower 12 bits 542 | freq_ctl = ((float)(PLLFREQ / carrier_freq)) * ( 1 << 12 ); //PLLD=500MHz 543 | } 544 | 545 | // GPIO4 needs to be ALT FUNC 0 to output the clock 546 | gpio_reg[GPFSEL0] = (gpio_reg[GPFSEL0] & ~(7 << 12)) | (4 << 12); 547 | 548 | 549 | ctl = (struct control_data_s *) mbox.virt_addr; 550 | dma_cb_t *cbp = ctl->cb; 551 | uint32_t phys_sample_dst = divider ? CM_PLLCFRAC : CM_GP0DIV; 552 | uint32_t phys_pwm_fifo_addr = PWM_PHYS_BASE + 0x18; 553 | 554 | for (int i = 0; i < NUM_SAMPLES; i++) { 555 | ctl->sample[i] = 0x5a << 24 | freq_ctl; // Silence 556 | // Write a frequency sample 557 | cbp->info = BCM2708_DMA_NO_WIDE_BURSTS | BCM2708_DMA_WAIT_RESP; 558 | cbp->src = mem_virt_to_phys(ctl->sample + i); 559 | cbp->dst = phys_sample_dst; 560 | cbp->length = 4; 561 | cbp->stride = 0; 562 | cbp->next = mem_virt_to_phys(cbp + 1); 563 | cbp++; 564 | // Delay 565 | cbp->info = BCM2708_DMA_NO_WIDE_BURSTS | BCM2708_DMA_WAIT_RESP | BCM2708_DMA_D_DREQ | BCM2708_DMA_PER_MAP(5); 566 | cbp->src = mem_virt_to_phys(mbox.virt_addr); 567 | cbp->dst = phys_pwm_fifo_addr; 568 | cbp->length = 4; 569 | cbp->stride = 0; 570 | cbp->next = mem_virt_to_phys(cbp + 1); 571 | cbp++; 572 | } 573 | cbp--; 574 | cbp->next = mem_virt_to_phys(mbox.virt_addr); 575 | 576 | // Here we define the rate at which we want to update the GPCLK control 577 | // register. 578 | // 579 | // Set the range to 2 bits. PLLD is at 500 MHz, therefore to get 228 kHz 580 | // we need a divisor of 500000 / 2 / 228 = 1096.491228 581 | // 582 | // This is 1096 + 2012*2^-12 theoretically 583 | // 584 | // However the fractional part may have to be adjusted to take the actual 585 | // frequency of your Pi's oscillator into account. For example on my Pi, 586 | // the fractional part should be 1916 instead of 2012 to get exactly 587 | // 228 kHz. However RDS decoding is still okay even at 2012. 588 | // 589 | // So we use the 'ppm' parameter to compensate for the oscillator error 590 | 591 | float srdivider = (500000./(2*228*(1.+ppm/1.e6))); 592 | uint32_t idivider = (uint32_t) srdivider; 593 | uint32_t fdivider = (uint32_t) ((srdivider - idivider)*pow(2, 12)); 594 | 595 | printf("ppm corr is %.4f, divider is %.4f (%d + %d*2^-12) [nominal 1096.4912].\n", 596 | ppm, srdivider, idivider, fdivider); 597 | 598 | pwm_reg[PWM_CTL] = 0; 599 | udelay(10); 600 | clk_reg[PWMCLK_CNTL] = 0x5A000006; // Source=PLLD and disable 601 | udelay(100); 602 | // theorically : 1096 + 2012*2^-12 603 | clk_reg[PWMCLK_DIV] = 0x5A000000 | (idivider<<12) | fdivider; 604 | udelay(100); 605 | clk_reg[PWMCLK_CNTL] = 0x5A000216; // Source=PLLD and enable + MASH filter 1 606 | udelay(100); 607 | pwm_reg[PWM_RNG1] = 2; 608 | udelay(10); 609 | pwm_reg[PWM_DMAC] = PWMDMAC_ENAB | PWMDMAC_THRSHLD; 610 | udelay(10); 611 | pwm_reg[PWM_CTL] = PWMCTL_CLRF; 612 | udelay(10); 613 | pwm_reg[PWM_CTL] = PWMCTL_USEF1 | PWMCTL_PWEN1; 614 | udelay(10); 615 | 616 | 617 | // Initialise the DMA 618 | dma_reg[DMA_CS] = BCM2708_DMA_RESET; 619 | udelay(10); 620 | dma_reg[DMA_CS] = BCM2708_DMA_INT | BCM2708_DMA_END; 621 | dma_reg[DMA_CONBLK_AD] = mem_virt_to_phys(ctl->cb); 622 | dma_reg[DMA_DEBUG] = 7; // clear debug error flags 623 | dma_reg[DMA_CS] = 0x10880001; // go, mid priority, wait for outstanding writes 624 | 625 | 626 | uint32_t last_cb = (uint32_t)ctl->cb; 627 | 628 | // Data structures for baseband data 629 | float data[DATA_SIZE]; 630 | int data_len = 0; 631 | int data_index = 0; 632 | 633 | // Initialize the baseband generator 634 | if(fm_mpx_open(audio_file, DATA_SIZE) < 0) return 1; 635 | 636 | // Initialize the RDS modulator 637 | char myps[9] = {0}; 638 | set_rds_pi(pi); 639 | set_rds_rt(rt); 640 | uint16_t count = 0; 641 | uint16_t count2 = 0; 642 | int varying_ps = 0; 643 | 644 | if(ps) { 645 | set_rds_ps(ps); 646 | printf("PI: %04X, PS: \"%s\".\n", pi, ps); 647 | } else { 648 | printf("PI: %04X, PS: .\n", pi); 649 | varying_ps = 1; 650 | } 651 | printf("RT: \"%s\"\n", rt); 652 | 653 | // Initialize the control pipe reader 654 | if(control_pipe) { 655 | if(open_control_pipe(control_pipe) == 0) { 656 | printf("Reading control commands on %s.\n", control_pipe); 657 | } else { 658 | printf("Failed to open control pipe: %s.\n", control_pipe); 659 | control_pipe = NULL; 660 | } 661 | } 662 | 663 | 664 | printf("Starting to transmit on %3.1f MHz.\n", carrier_freq/1e6); 665 | 666 | 667 | float deviation_scale_factor; 668 | if( divider ) // PLL modulation 669 | { // note samples are [-10:10] 670 | deviation_scale_factor= 0.1 * (divider*DEVIATION/ (19.2e6/((double)(1<<20))) ) ; // todo PPM 671 | } 672 | else // MASH modulation 673 | { 674 | double normdivider=((double)PLLFREQ / (double)carrier_freq) * ( 1 << 12 ); //PLLD=500MHz 675 | double highdivider=((double)PLLFREQ / (((double)carrier_freq)+(DEVIATION))) * ( 1 << 12 ); 676 | deviation_scale_factor= 0.1 * (highdivider-normdivider); 677 | // Scaling factor for mash is negative because 678 | // a higher division ratio equals a lower frequency. 679 | } 680 | //printf("deviation_scale_factor = %f \n", deviation_scale_factor); 681 | 682 | 683 | for (;;) { 684 | // Default (varying) PS 685 | if(varying_ps) { 686 | if(count == 512) { 687 | snprintf(myps, 9, "%08d", count2); 688 | set_rds_ps(myps); 689 | count2++; 690 | } 691 | if(count == 1024) { 692 | set_rds_ps("RPi-Live"); 693 | count = 0; 694 | } 695 | count++; 696 | } 697 | 698 | if(control_pipe && poll_control_pipe() == CONTROL_PIPE_PS_SET) { 699 | varying_ps = 0; 700 | } 701 | 702 | usleep(5000); 703 | 704 | uint32_t cur_cb = mem_phys_to_virt(dma_reg[DMA_CONBLK_AD]); 705 | int last_sample = (last_cb - (uint32_t)mbox.virt_addr) / (sizeof(dma_cb_t) * 2); 706 | int this_sample = (cur_cb - (uint32_t)mbox.virt_addr) / (sizeof(dma_cb_t) * 2); 707 | int free_slots = this_sample - last_sample; 708 | if (free_slots < 0) 709 | free_slots += NUM_SAMPLES; 710 | 711 | while (free_slots >= SUBSIZE) { 712 | // get more baseband samples if necessary 713 | if(data_len == 0) { 714 | if( fm_mpx_get_samples(data) < 0 ) { 715 | terminate(0); 716 | } 717 | data_len = DATA_SIZE; 718 | data_index = 0; 719 | } 720 | 721 | float dval = data[data_index]*deviation_scale_factor; 722 | int intval; 723 | if( divider ) // PLL modulation 724 | { 725 | intval = ( (int)((floor)(dval)) & ~0x3 ) ; 726 | // clock settings from boot code seem to always leave 2 lsb clear 727 | } 728 | else // MASH modulation 729 | { 730 | intval = (int)((floor)(dval)) ; 731 | } 732 | data_index++; 733 | data_len--; 734 | 735 | 736 | 737 | ctl->sample[last_sample++] = ( 0x5A << 24 | freq_ctl) + intval; 738 | if (last_sample == NUM_SAMPLES) 739 | last_sample = 0; 740 | 741 | free_slots -= SUBSIZE; 742 | } 743 | last_cb = (uint32_t)mbox.virt_addr + last_sample * sizeof(dma_cb_t) * 2; 744 | } 745 | 746 | return 0; 747 | } 748 | 749 | 750 | int main(int argc, char **argv) { 751 | char *audio_file = NULL; 752 | char *control_pipe = NULL; 753 | uint32_t carrier_freq = 107900000; 754 | char *ps = NULL; 755 | char *rt = "PiFmRds: live FM-RDS transmission from the RaspberryPi"; 756 | uint16_t pi = 0x1234; 757 | uint32_t mash = -1; 758 | float ppm = 0; 759 | 760 | 761 | // Parse command-line arguments 762 | for(int i=1; i 108e6) 775 | fatal("Incorrect frequency specification. Must be in megahertz, of the form 107.9, between 76 and 108.\n"); 776 | } else if(strcmp("-pi", arg)==0 && param != NULL) { 777 | i++; 778 | pi = (uint16_t) strtol(param, NULL, 16); 779 | } else if(strcmp("-ps", arg)==0 && param != NULL) { 780 | i++; 781 | ps = param; 782 | } else if(strcmp("-rt", arg)==0 && param != NULL) { 783 | i++; 784 | rt = param; 785 | } else if(strcmp("-ppm", arg)==0 && param != NULL) { 786 | i++; 787 | ppm = atof(param); 788 | } else if(strcmp("-ctl", arg)==0 && param != NULL) { 789 | i++; 790 | control_pipe = param; 791 | } else if(strcmp("-mash", arg)==0 ) { 792 | i++; 793 | mash=1; 794 | } else { 795 | fatal("Unrecognised argument: %s.\n" 796 | "Syntax: pi_fm_rds [-freq freq] [-audio file] [-ppm ppm_error] [-pi pi_code]\n" 797 | " [-ps ps_text] [-rt rt_text] [-ctl control_pipe] [-mash]\n", arg); 798 | } 799 | } 800 | 801 | 802 | // Choose an integer divider for GPCLK0 803 | // 804 | // There may be improvements possible to this algorithm. 805 | double xtal_freq_recip=1.0/19.2e6; // todo PPM correction 806 | int best_divider=0; 807 | 808 | // Optional loop to print tuning solutions for all FM frequencies 809 | //for( carrier_freq=76000000 ; carrier_freq<108000000 ; carrier_freq+=100000 ) 810 | { 811 | int solution_count=0; 812 | printf("carrier:%3.2f ",carrier_freq/1e6); 813 | int divider,min_int_multiplier,max_int_multiplier, fom, int_multiplier, best_fom=0; 814 | double frac_multiplier; 815 | best_divider=0; 816 | for( divider=2;divider<20;divider+=1) 817 | { 818 | if( carrier_freq*divider < 760e6 ) continue; // widest accepted frequency range 819 | if( carrier_freq*divider > 1300e6 ) break; 820 | 821 | max_int_multiplier=((int)((double)(carrier_freq+10+DEVIATION)*divider*xtal_freq_recip)); 822 | min_int_multiplier=((int)((double)(carrier_freq-10-DEVIATION)*divider*xtal_freq_recip)); 823 | if( min_int_multiplier!=max_int_multiplier ) continue; // don't cross integer boundary 824 | 825 | solution_count++; // if we make it here the solution is acceptable, 826 | fom=0; // but we want a good solution 827 | 828 | if( carrier_freq*divider > 900e6 ) fom++; // prefer freqs closer to 1000 829 | if( carrier_freq*divider < 1100e6 ) fom++; 830 | if( carrier_freq*divider > 800e6 ) fom++; // accepted frequency range 831 | if( carrier_freq*divider < 1200e6 ) fom++; 832 | 833 | 834 | frac_multiplier=((double)(carrier_freq)*divider*xtal_freq_recip); 835 | int_multiplier = (int) frac_multiplier; 836 | frac_multiplier = frac_multiplier - int_multiplier; 837 | if( (frac_multiplier>0.2) && (frac_multiplier<0.8) ) fom++; // prefer mulipliers away from integer boundaries 838 | 839 | 840 | //if( divider%2 == 1 ) fom+=2; // prefer odd dividers 841 | // Even and odd dividers could have different harmonic content, 842 | // but the latest measurements have shown no significant difference. 843 | 844 | 845 | //printf(" multiplier:%f divider:%d VCO: %4.1fMHz\n",carrier_freq*divider*xtal_freq_recip,divider,(double)carrier_freq*divider/1e6); 846 | if( fom > best_fom ) 847 | { 848 | best_fom=fom; 849 | best_divider=divider; 850 | } 851 | } 852 | printf(" multiplier:%f divider:%d VCO: %4.1fMHz\n",carrier_freq*best_divider*xtal_freq_recip,best_divider,(double)carrier_freq*best_divider/1e6); 853 | 854 | if( solution_count==0) 855 | printf("No tuning solution found. (76.8 and 96.0 are not supported.)\n"); 856 | 857 | }// Optional loop to print tuning solutions 858 | 859 | if( best_divider==0) return -1 ; 860 | 861 | if( mash!=-1 ) 862 | { 863 | best_divider=0; // if divider=0, use MASH divider instead of PLL modulation 864 | } 865 | int errcode = tx(carrier_freq, best_divider, audio_file, pi, ps, rt, ppm, control_pipe); 866 | 867 | terminate(errcode); 868 | } 869 | -------------------------------------------------------------------------------- /src/pi_fm_rds.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * PiFmRds - FM/RDS transmitter for the Raspberry Pi 3 | * Copyright (C) 1028 Evariste Courjaud, F5OEO 4 | * Copyright (C) 2014, 2015 Christophe Jacquet, F8FTK 5 | * Copyright (C) 2012, 2015 Richard Hirst 6 | * Copyright (C) 2012 Oliver Mattos and Oskar Weigl 7 | * 8 | * See https://github.com/ChristopheJacquet/PiFmRds 9 | * 10 | * PI-FM-RDS: RaspberryPi FM transmitter, with RDS. 11 | * 12 | * This file contains the VHF FM modulator. All credit goes to the original 13 | * authors, Oliver Mattos and Oskar Weigl for the original idea, and to 14 | * Richard Hirst for using the Pi's DMA engine, which reduced CPU usage 15 | * dramatically. 16 | * 17 | * I (Christophe Jacquet) have adapted their idea to transmitting samples 18 | * at 228 kHz, allowing to build the 57 kHz subcarrier for RDS BPSK data. 19 | * 20 | * To make it work on the Raspberry Pi 2, I used a fix by Richard Hirst 21 | * (again) to request memory using Broadcom's mailbox interface. This fix 22 | * was published for ServoBlaster here: 23 | * https://www.raspberrypi.org/forums/viewtopic.php?p=699651#p699651 24 | * 25 | * Never use this to transmit VHF-FM data through an antenna, as it is 26 | * illegal in most countries. This code is for testing purposes only. 27 | * Always connect a shielded transmission line from the RaspberryPi directly 28 | * to a radio receiver, so as *not* to emit radio waves. 29 | * 30 | * --------------------------------------------------------------------------- 31 | * These are the comments from Richard Hirst's version: 32 | * 33 | * RaspberryPi based FM transmitter. For the original idea, see: 34 | * 35 | * http://www.icrobotics.co.uk/wiki/index.php/Turning_the_Raspberry_Pi_Into_an_FM_Transmitter 36 | * 37 | * All credit to Oliver Mattos and Oskar Weigl for creating the original code. 38 | * 39 | * I have taken their idea and reworked it to use the Pi DMA engine, so 40 | * reducing the CPU overhead for playing a .wav file from 100% to about 1.6%. 41 | * 42 | * I have implemented this in user space, using an idea I picked up from Joan 43 | * on the Raspberry Pi forums - credit to Joan for the DMA from user space 44 | * idea. 45 | * 46 | * The idea of feeding the PWM FIFO in order to pace DMA control blocks comes 47 | * from ServoBlaster, and I take credit for that :-) 48 | * 49 | * This code uses DMA channel 5 and the PWM hardware, with no regard for 50 | * whether something else might be trying to use it at the same time (such as 51 | * the 3.5mm jack audio driver). 52 | * 53 | * I know nothing much about sound, subsampling, or FM broadcasting, so it is 54 | * quite likely the sound quality produced by this code can be improved by 55 | * someone who knows what they are doing. There may be issues realting to 56 | * caching, as the user space process just writes to its virtual address space, 57 | * and expects the DMA controller to see the data; it seems to work for me 58 | * though. 59 | * 60 | * NOTE: THIS CODE MAY WELL CRASH YOUR PI, TRASH YOUR FILE SYSTEMS, AND 61 | * POTENTIALLY EVEN DAMAGE YOUR HARDWARE. THIS IS BECAUSE IT STARTS UP THE DMA 62 | * CONTROLLER USING MEMORY OWNED BY A USER PROCESS. IF THAT USER PROCESS EXITS 63 | * WITHOUT STOPPING THE DMA CONTROLLER, ALL HELL COULD BREAK LOOSE AS THE 64 | * MEMORY GETS REALLOCATED TO OTHER PROCESSES WHILE THE DMA CONTROLLER IS STILL 65 | * USING IT. I HAVE ATTEMPTED TO MINIMISE ANY RISK BY CATCHING SIGNALS AND 66 | * RESETTING THE DMA CONTROLLER BEFORE EXITING, BUT YOU HAVE BEEN WARNED. I 67 | * ACCEPT NO LIABILITY OR RESPONSIBILITY FOR ANYTHING THAT HAPPENS AS A RESULT 68 | * OF YOU RUNNING THIS CODE. IF IT BREAKS, YOU GET TO KEEP ALL THE PIECES. 69 | * 70 | * NOTE ALSO: THIS MAY BE ILLEGAL IN YOUR COUNTRY. HERE ARE SOME COMMENTS 71 | * FROM MORE KNOWLEDGEABLE PEOPLE ON THE FORUM: 72 | * 73 | * "Just be aware that in some countries FM broadcast and especially long 74 | * distance FM broadcast could get yourself into trouble with the law, stray FM 75 | * broadcasts over Airband aviation is also strictly forbidden." 76 | * 77 | * "A low pass filter is really really required for this as it has strong 78 | * harmonics at the 3rd, 5th 7th and 9th which sit in licensed and rather 79 | * essential bands, ie GSM, HAM, emergency services and others. Polluting these 80 | * frequencies is immoral and dangerous, whereas "breaking in" on FM bands is 81 | * just plain illegal." 82 | * 83 | * "Don't get caught, this GPIO use has the potential to exceed the legal 84 | * limits by about 2000% with a proper aerial." 85 | * 86 | * 87 | * As for the original code, this code is released under the GPL. 88 | * 89 | * Richard Hirst December 2012 90 | */ 91 | 92 | #include 93 | #include 94 | #include 95 | #include 96 | #include 97 | #include 98 | #include 99 | #include 100 | #include 101 | #include 102 | #include 103 | #include 104 | #include 105 | #include 106 | #include 107 | 108 | extern "C" 109 | { 110 | #include "rds.h" 111 | #include "fm_mpx.h" 112 | #include "control_pipe.h" 113 | } 114 | 115 | #include "librpitx/src/librpitx.h" 116 | 117 | ngfmdmasync *fmmod; 118 | // The deviation specifies how wide the signal is. 119 | // Use 75kHz for WBFM (broadcast radio) 120 | // and about 2.5kHz for NBFM (walkie-talkie style radio) 121 | #define DEVIATION 75000 122 | //FOR NBFM 123 | //#define DEVIATION 2500 124 | 125 | static void 126 | terminate(int num) 127 | { 128 | delete fmmod; 129 | fm_mpx_close(); 130 | close_control_pipe(); 131 | 132 | 133 | exit(num); 134 | } 135 | 136 | static void 137 | fatal(char *fmt, ...) 138 | { 139 | va_list ap; 140 | 141 | va_start(ap, fmt); 142 | vfprintf(stderr, fmt, ap); 143 | va_end(ap); 144 | terminate(0); 145 | } 146 | 147 | 148 | 149 | 150 | #define SUBSIZE 512 151 | #define DATA_SIZE 5000 152 | 153 | 154 | int tx(uint32_t carrier_freq, char *audio_file, uint16_t pi, char *ps, char *rt, float ppm, char *control_pipe) { 155 | // Catch all signals possible - it is vital we kill the DMA engine 156 | // on process exit! 157 | for (int i = 0; i < 64; i++) { 158 | struct sigaction sa; 159 | 160 | memset(&sa, 0, sizeof(sa)); 161 | sa.sa_handler = terminate; 162 | sigaction(i, &sa, NULL); 163 | } 164 | 165 | 166 | 167 | // Data structures for baseband data 168 | float data[DATA_SIZE]; 169 | float devfreq[DATA_SIZE]; 170 | int data_len = 0; 171 | int data_index = 0; 172 | 173 | // Initialize the baseband generator 174 | if(fm_mpx_open(audio_file, DATA_SIZE) < 0) return 1; 175 | 176 | // Initialize the RDS modulator 177 | char myps[9] = {0}; 178 | set_rds_pi(pi); 179 | set_rds_rt(rt); 180 | uint16_t count = 0; 181 | uint16_t count2 = 0; 182 | int varying_ps = 0; 183 | 184 | if(ps) { 185 | set_rds_ps(ps); 186 | printf("PI: %04X, PS: \"%s\".\n", pi, ps); 187 | } else { 188 | printf("PI: %04X, PS: .\n", pi); 189 | varying_ps = 1; 190 | } 191 | printf("RT: \"%s\"\n", rt); 192 | 193 | // Initialize the control pipe reader 194 | if(control_pipe) { 195 | if(open_control_pipe(control_pipe) == 0) { 196 | printf("Reading control commands on %s.\n", control_pipe); 197 | } else { 198 | printf("Failed to open control pipe: %s.\n", control_pipe); 199 | control_pipe = NULL; 200 | } 201 | } 202 | 203 | 204 | printf("Starting to transmit on %3.1f MHz.\n", carrier_freq/1e6); 205 | 206 | 207 | float deviation_scale_factor; 208 | //if( divider ) // PLL modulation 209 | { // note samples are [-10:10] 210 | deviation_scale_factor= 0.1 * (DEVIATION ) ; // todo PPM 211 | } 212 | 213 | 214 | 215 | for (;;) 216 | { 217 | // Default (varying) PS 218 | if(varying_ps) { 219 | if(count == 512) { 220 | snprintf(myps, 9, "%08d", count2); 221 | set_rds_ps(myps); 222 | count2++; 223 | } 224 | if(count == 1024) { 225 | set_rds_ps("RPi-Live"); 226 | count = 0; 227 | } 228 | count++; 229 | } 230 | 231 | if(control_pipe && poll_control_pipe() == CONTROL_PIPE_PS_SET) { 232 | varying_ps = 0; 233 | } 234 | 235 | if( fm_mpx_get_samples(data) < 0 ) { 236 | terminate(0); 237 | } 238 | data_len = DATA_SIZE; 239 | for(int i=0;i< data_len;i++) 240 | { 241 | 242 | devfreq[i] = data[i]*deviation_scale_factor; 243 | 244 | 245 | } 246 | fmmod->SetFrequencySamples(devfreq,data_len); 247 | } 248 | 249 | return 0; 250 | } 251 | 252 | 253 | int main(int argc, char **argv) { 254 | char *audio_file = NULL; 255 | char *control_pipe = NULL; 256 | uint32_t carrier_freq = 107900000; 257 | char *ps = "Librpitx"; 258 | char *rt = "PiFmRds: live FM-RDS transmission from the RaspberryPi"; 259 | uint16_t pi = 0x1234; 260 | uint32_t mash = -1; 261 | float ppm = 0; 262 | 263 | 264 | // Parse command-line arguments 265 | for(int i=1; i 108e6) 278 | // fatal("Incorrect frequency specification. Must be in megahertz, of the form 107.9, between 76 and 108.\n"); 279 | } else if(strcmp("-pi", arg)==0 && param != NULL) { 280 | i++; 281 | pi = (uint16_t) strtol(param, NULL, 16); 282 | } else if(strcmp("-ps", arg)==0 && param != NULL) { 283 | i++; 284 | ps = param; 285 | } else if(strcmp("-rt", arg)==0 && param != NULL) { 286 | i++; 287 | rt = param; 288 | } else if(strcmp("-ppm", arg)==0 && param != NULL) { 289 | i++; 290 | ppm = atof(param); 291 | } else if(strcmp("-ctl", arg)==0 && param != NULL) { 292 | i++; 293 | control_pipe = param; 294 | } else if(strcmp("-mash", arg)==0 ) { 295 | i++; 296 | mash=1; 297 | } else { 298 | fatal("Unrecognised argument: %s.\n" 299 | "Syntax: pi_fm_rds [-freq freq] [-audio file] [-ppm ppm_error] [-pi pi_code]\n" 300 | " [-ps ps_text] [-rt rt_text] [-ctl control_pipe] [-mash]\n", arg); 301 | } 302 | } 303 | int FifoSize=DATA_SIZE*2; 304 | fmmod=new ngfmdmasync(carrier_freq,228000,14,FifoSize); 305 | int errcode = tx(carrier_freq, audio_file, pi, ps, rt, ppm, control_pipe); 306 | 307 | terminate(errcode); 308 | } 309 | -------------------------------------------------------------------------------- /src/pulses.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/F5OEO/PiFmRds/2707ecc8ab32164060de53e4774e682a718aecb3/src/pulses.wav -------------------------------------------------------------------------------- /src/rds.c: -------------------------------------------------------------------------------- 1 | /* 2 | PiFmRds - FM/RDS transmitter for the Raspberry Pi 3 | Copyright (C) 2014 Christophe Jacquet, F8FTK 4 | 5 | See https://github.com/ChristopheJacquet/PiFmRds 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include "waveforms.h" 27 | 28 | #define RT_LENGTH 64 29 | #define PS_LENGTH 8 30 | #define GROUP_LENGTH 4 31 | 32 | struct { 33 | uint16_t pi; 34 | int ta; 35 | char ps[PS_LENGTH]; 36 | char rt[RT_LENGTH]; 37 | } rds_params = { 0 }; 38 | /* Here, the first member of the struct must be a scalar to avoid a 39 | warning on -Wmissing-braces with GCC < 4.8.3 40 | (bug: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119) 41 | */ 42 | 43 | /* The RDS error-detection code generator polynomial is 44 | x^10 + x^8 + x^7 + x^5 + x^4 + x^3 + x^0 45 | */ 46 | #define POLY 0x1B9 47 | #define POLY_DEG 10 48 | #define MSB_BIT 0x8000 49 | #define BLOCK_SIZE 16 50 | 51 | #define BITS_PER_GROUP (GROUP_LENGTH * (BLOCK_SIZE+POLY_DEG)) 52 | #define SAMPLES_PER_BIT 192 53 | #define FILTER_SIZE (sizeof(waveform_biphase)/sizeof(float)) 54 | #define SAMPLE_BUFFER_SIZE (SAMPLES_PER_BIT + FILTER_SIZE) 55 | 56 | 57 | uint16_t offset_words[] = {0x0FC, 0x198, 0x168, 0x1B4}; 58 | // We don't handle offset word C' here for the sake of simplicity 59 | 60 | /* Classical CRC computation */ 61 | uint16_t crc(uint16_t block) { 62 | uint16_t crc = 0; 63 | 64 | for(int j=0; j> (POLY_DEG-1)) & 1; 69 | crc <<= 1; 70 | if((msb ^ bit) != 0) { 71 | crc = crc ^ POLY; 72 | } 73 | } 74 | 75 | return crc; 76 | } 77 | 78 | /* Possibly generates a CT (clock time) group if the minute has just changed 79 | Returns 1 if the CT group was generated, 0 otherwise 80 | */ 81 | int get_rds_ct_group(uint16_t *blocks) { 82 | static int latest_minutes = -1; 83 | 84 | // Check time 85 | time_t now; 86 | struct tm *utc; 87 | 88 | now = time (NULL); 89 | utc = gmtime (&now); 90 | 91 | if(utc->tm_min != latest_minutes) { 92 | // Generate CT group 93 | latest_minutes = utc->tm_min; 94 | 95 | int l = utc->tm_mon <= 1 ? 1 : 0; 96 | int mjd = 14956 + utc->tm_mday + 97 | (int)((utc->tm_year - l) * 365.25) + 98 | (int)((utc->tm_mon + 2 + l*12) * 30.6001); 99 | 100 | blocks[1] = 0x4400 | (mjd>>15); 101 | blocks[2] = (mjd<<1) | (utc->tm_hour>>4); 102 | blocks[3] = (utc->tm_hour & 0xF)<<12 | utc->tm_min<<6; 103 | 104 | utc = localtime(&now); 105 | 106 | int offset = utc->tm_gmtoff / (30 * 60); 107 | blocks[3] |= abs(offset); 108 | if(offset < 0) blocks[3] |= 0x20; 109 | 110 | //printf("Generated CT: %04X %04X %04X\n", blocks[1], blocks[2], blocks[3]); 111 | return 1; 112 | } else return 0; 113 | } 114 | 115 | /* Creates an RDS group. This generates sequences of the form 0A, 0A, 0A, 0A, 2A, etc. 116 | The pattern is of length 5, the variable 'state' keeps track of where we are in the 117 | pattern. 'ps_state' and 'rt_state' keep track of where we are in the PS (0A) sequence 118 | or RT (2A) sequence, respectively. 119 | */ 120 | void get_rds_group(int *buffer) { 121 | static int state = 0; 122 | static int ps_state = 0; 123 | static int rt_state = 0; 124 | uint16_t blocks[GROUP_LENGTH] = {rds_params.pi, 0, 0, 0}; 125 | 126 | // Generate block content 127 | if(! get_rds_ct_group(blocks)) { // CT (clock time) has priority on other group types 128 | if(state < 4) { 129 | blocks[1] = 0x0400 | ps_state; 130 | if(rds_params.ta) blocks[1] |= 0x0010; 131 | blocks[2] = 0xCDCD; // no AF 132 | blocks[3] = rds_params.ps[ps_state*2]<<8 | rds_params.ps[ps_state*2+1]; 133 | ps_state++; 134 | if(ps_state >= 4) ps_state = 0; 135 | } else { // state == 5 136 | blocks[1] = 0x2400 | rt_state; 137 | blocks[2] = rds_params.rt[rt_state*4+0]<<8 | rds_params.rt[rt_state*4+1]; 138 | blocks[3] = rds_params.rt[rt_state*4+2]<<8 | rds_params.rt[rt_state*4+3]; 139 | rt_state++; 140 | if(rt_state >= 16) rt_state = 0; 141 | } 142 | 143 | state++; 144 | if(state >= 5) state = 0; 145 | } 146 | 147 | // Calculate the checkword for each block and emit the bits 148 | for(int i=0; i= SAMPLES_PER_BIT) { 184 | if(bit_pos >= BITS_PER_GROUP) { 185 | get_rds_group(bit_buffer); 186 | bit_pos = 0; 187 | } 188 | 189 | // do differential encoding 190 | cur_bit = bit_buffer[bit_pos]; 191 | prev_output = cur_output; 192 | cur_output = prev_output ^ cur_bit; 193 | 194 | inverting = (cur_output == 1); 195 | 196 | float *src = waveform_biphase; 197 | int idx = in_sample_index; 198 | 199 | for(int j=0; j= SAMPLE_BUFFER_SIZE) idx = 0; 204 | } 205 | 206 | in_sample_index += SAMPLES_PER_BIT; 207 | if(in_sample_index >= SAMPLE_BUFFER_SIZE) in_sample_index -= SAMPLE_BUFFER_SIZE; 208 | 209 | bit_pos++; 210 | sample_count = 0; 211 | } 212 | 213 | float sample = sample_buffer[out_sample_index]; 214 | sample_buffer[out_sample_index] = 0; 215 | out_sample_index++; 216 | if(out_sample_index >= SAMPLE_BUFFER_SIZE) out_sample_index = 0; 217 | 218 | 219 | // modulate at 57 kHz 220 | // use phase for this 221 | switch(phase) { 222 | case 0: 223 | case 2: sample = 0; break; 224 | case 1: break; 225 | case 3: sample = -sample; break; 226 | } 227 | phase++; 228 | if(phase >= 4) phase = 0; 229 | 230 | *buffer++ = sample; 231 | sample_count++; 232 | } 233 | } 234 | 235 | void set_rds_pi(uint16_t pi_code) { 236 | rds_params.pi = pi_code; 237 | } 238 | 239 | void set_rds_rt(char *rt) { 240 | strncpy(rds_params.rt, rt, 64); 241 | for(int i=0; i<64; i++) { 242 | if(rds_params.rt[i] == 0) rds_params.rt[i] = 32; 243 | } 244 | } 245 | 246 | void set_rds_ps(char *ps) { 247 | strncpy(rds_params.ps, ps, 8); 248 | for(int i=0; i<8; i++) { 249 | if(rds_params.ps[i] == 0) rds_params.ps[i] = 32; 250 | } 251 | } 252 | 253 | void set_rds_ta(int ta) { 254 | rds_params.ta = ta; 255 | } -------------------------------------------------------------------------------- /src/rds.h: -------------------------------------------------------------------------------- 1 | /* 2 | PiFmRds - FM/RDS transmitter for the Raspberry Pi 3 | Copyright (C) 2014 Christophe Jacquet, F8FTK 4 | 5 | See https://github.com/ChristopheJacquet/PiFmRds 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | #ifndef RDS_H 22 | #define RDS_H 23 | 24 | 25 | #include 26 | 27 | extern void get_rds_samples(float *buffer, int count); 28 | extern void set_rds_pi(uint16_t pi_code); 29 | extern void set_rds_rt(char *rt); 30 | extern void set_rds_ps(char *ps); 31 | extern void set_rds_ta(int ta); 32 | 33 | 34 | #endif /* RDS_H */ -------------------------------------------------------------------------------- /src/rds_wav.c: -------------------------------------------------------------------------------- 1 | /* 2 | PiFmRds - FM/RDS transmitter for the Raspberry Pi 3 | Copyright (C) 2014 Christophe Jacquet, F8FTK 4 | 5 | See https://github.com/ChristopheJacquet/PiFmRds 6 | 7 | rds_wav.c is a test program that writes a RDS baseband signal to a WAV 8 | file. It requires libsndfile. 9 | 10 | This program is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | This program is distributed in the hope that it will be useful, 16 | but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | GNU General Public License for more details. 19 | 20 | You should have received a copy of the GNU General Public License 21 | along with this program. If not, see . 22 | */ 23 | 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | 31 | #include "rds.h" 32 | #include "fm_mpx.h" 33 | 34 | 35 | #define LENGTH 114000 36 | 37 | 38 | /* Simple test program */ 39 | int main(int argc, char **argv) { 40 | if(argc < 4) { 41 | fprintf(stderr, "Error: missing argument.\n"); 42 | fprintf(stderr, "Syntax: rds_wav \n"); 43 | return EXIT_FAILURE; 44 | } 45 | 46 | set_rds_pi(0x1234); 47 | set_rds_ps(argv[3]); 48 | set_rds_rt(argv[3]); 49 | 50 | char *in_file = argv[1]; 51 | if(strcmp("NONE", argv[1]) == 0) in_file = NULL; 52 | 53 | if(fm_mpx_open(in_file, LENGTH) != 0) { 54 | printf("Could not setup FM mulitplex generator.\n"); 55 | return EXIT_FAILURE; 56 | } 57 | 58 | 59 | 60 | // Set the format of the output file 61 | SNDFILE *outf; 62 | SF_INFO sfinfo; 63 | 64 | sfinfo.frames = LENGTH; 65 | sfinfo.samplerate = 228000; 66 | sfinfo.channels = 1; 67 | sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16; 68 | sfinfo.sections = 1; 69 | sfinfo.seekable = 0; 70 | 71 | // Open the output file 72 | char *out_file = argv[2]; 73 | if (! (outf = sf_open(out_file, SFM_WRITE, &sfinfo))) { 74 | fprintf(stderr, "Error: could not open output file %s.\n", out_file); 75 | return EXIT_FAILURE; 76 | } 77 | 78 | float mpx_buffer[LENGTH]; 79 | 80 | for(int j=0; j<40; j++) { 81 | if( fm_mpx_get_samples(mpx_buffer) < 0 ) break; 82 | 83 | // scale samples 84 | for(int i=0; i