├── LICENSE ├── README.md ├── ac3_sink.c ├── ac3_sink.h ├── config.h ├── iec_61937.c ├── iec_61937.h ├── main.c ├── pcm_sink.c └── pcm_sink.h /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 | 635 | Copyright (C) 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 | Copyright (C) 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 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # audio_async_loopback 2 | Real-time S/PDIF PCM/AC3 capture and playback 3 | 4 | A simple program to play audio from an S/PDIF input, in real-time. 5 | 6 | Requires Pulseaudio, libavcodec, and libsamplerate. 7 | 8 | It supports uncompressed PCM as well as IEC 61937-3 (AC3) bitstreams. 9 | 10 | When an IEC 61937 AC3 bitstream is detected, it automatically begins 11 | decoding it into 5.1 channel audio. If there are no IEC 61937 data 12 | bursts found within a given time window, it switches back to PCM mode. 13 | 14 | Why not just use pacat and pipe it into ffplay/mpv/vlc/whatever? Or 15 | Pulseaudio's module_loopback? 16 | 17 | - module_loopback isn't capable of decoding compressed bitstreams. 18 | 19 | - Because pacat+ffplay cannot account for the case where the S/PDIF 20 | input is on a different clock domain than that of the output device. 21 | In other words, if you're using a USB S/PDIF input device and trying 22 | to play back audio through your soundcard, the input and output are 23 | on two different clock domains. Even if they're both set to the 24 | same sampling rate, there will always be a slight difference due to 25 | oscillator tolerances. So, what ends up happening is that your 26 | pipe buffer either ends up growing and growing (input faster than 27 | output), resulting in larger and larger latency, or you end up 28 | with occasional buffer underflows (output faster than input). 29 | 30 | To address this clock domain issue, the audio samples are passed 31 | through a resampler with a ratio that is dynamically adjusted to 32 | attempt to maintain a constant amount of data in the intermediate 33 | buffer at any given time. This compensates for any slight differences 34 | in sampling rate between the input and output. 35 | 36 | One of the goals was to maintain as low of a latency as possible, 37 | so a lot of the parameters are fairly aggressive, resulting in 38 | high CPU usage. These parameters can be tweaked (see config.h), 39 | and will probably need to be adjusted depending on your system. 40 | 41 | In my system, I typically see about ~15 milliseconds of latency with 42 | PCM audio, and ~45 with AC3 bitstreams. The reason AC3 bitstreams 43 | have more latency is because it's decoded on a per-frame basis, and 44 | each AC3 frame typically represents 1536 PCM samples (33 milliseconds 45 | at 48 kHz). 46 | 47 | In order for this program to work for AC3, it requires an S/PDIF 48 | input that is capable of capturing bit-perfect audio. Many S/PDIF 49 | inputs will do things like internal resampling, mixing, volume control, 50 | etc., which will break any compressed bitstream format. Other 51 | inputs will automatically mute the audio if the non-PCM IEC 60958 52 | channel status bit is set, which is also a problem. 53 | 54 | I was able to get this working using the miniDSP USBStreamer B with 55 | the stereo firmware loaded. Just make sure Pulseaudio is configured 56 | for 48 kHz and that the volume is set to 100%. 57 | 58 | - Compiling: 59 | 60 | You may need to install libsamplerate0-dev, libpulse-dev, libavcodec-dev first, then: 61 | Just do: gcc -o audio_async_loopback main.c iec_61937.c pcm_sink.c ac3_sink.c -lpulse-simple -lsamplerate -lpthread -lavutil -lavcodec -Wall -O3 -flto 62 | 63 | - Usage: 64 | 65 | Invoke the program with the argument being the name of your input. 66 | Use "pactl list sources" to get a list of inputs. 67 | 68 | If you encounter discontinuities in the audio, you can specify an 69 | optional third argument to the program, which will be the sink 70 | latency in microseconds. Try setting it to something like 50000. 71 | 72 | NOTE: There are a lot of loose ends in this program. I made it for 73 | my own personal use. I'm sure there are bugs, but it works 74 | fine for me. 75 | 76 | -------------------------------------------------------------------------------- /ac3_sink.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of audio_async_loopback 3 | * Copyright (c) 2020 Jacob Moroni. 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, version 3. 8 | * 9 | * This program is distributed in the hope that it will be useful, but 10 | * WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | /* 19 | * Main AC3 sink implementation. Accepts a pointer to a complete 20 | * AC3 frame, decodes it, resamples it, and then passes it to 21 | * the Pulseaudio sink. Like the PCM sink, this also tries to 22 | * maintain a consistent level in the buffer by dynamically 23 | * adjusting the sampling rate ratio. 24 | */ 25 | 26 | #include 27 | #include 28 | #include 29 | 30 | #include "ac3_sink.h" 31 | #include "config.h" 32 | 33 | /* Returns the number of space available, in samples. */ 34 | static uint32_t buffer_space_avail(struct ac3_sink *inst) 35 | { 36 | return (AC3_SINK_SAMPLE_BUFFER_SIZE - (inst->write_idx - inst->read_idx)); 37 | } 38 | 39 | /* Returns the current buffer utilization, in samples. */ 40 | static uint32_t buffer_used(struct ac3_sink *inst) 41 | { 42 | return (inst->write_idx - inst->read_idx); 43 | } 44 | 45 | /* Output thread. Writes data from the intermediate buffer into 46 | * the Pulseaudio stream in units of AC3_SINK_OUTPUT_CHUNK_SIZE 47 | * samples. 48 | */ 49 | static void *output_thread(void *arg) 50 | { 51 | int error; 52 | uint32_t i; 53 | float tmp[AC3_SINK_OUTPUT_CHUNK_SIZE]; 54 | struct ac3_sink *inst = (struct ac3_sink *)arg; 55 | 56 | while (1) { 57 | pthread_mutex_lock(&inst->lock); 58 | 59 | /* Wait for data. */ 60 | while ((buffer_used(inst) < AC3_SINK_OUTPUT_CHUNK_SIZE) && inst->thread_run) { 61 | pthread_cond_wait(&inst->cond, &inst->lock); 62 | } 63 | 64 | if (!inst->thread_run) { 65 | /* Terminate. */ 66 | pthread_mutex_unlock(&inst->lock); 67 | pthread_exit(NULL); 68 | } 69 | 70 | /* Copy out one chunk. */ 71 | for (i = 0; i < AC3_SINK_OUTPUT_CHUNK_SIZE; i++) { 72 | tmp[i] = inst->buffer[inst->read_idx & AC3_SINK_SAMPLE_BUFFER_SIZE_MASK]; 73 | inst->read_idx++; 74 | } 75 | 76 | pthread_mutex_unlock(&inst->lock); 77 | 78 | if (pa_simple_write(inst->pa_inst, tmp, sizeof(tmp), &error) < 0) { 79 | printf("Could not write chunk to output stream (error = %d)\n", error); 80 | } 81 | } 82 | 83 | /* Not reached. */ 84 | pthread_exit(NULL); 85 | } 86 | 87 | /* Calculate a new sampling rate ratio. This should be called 88 | * before adding a new chunk to the ring buffer, and must be 89 | * called with the lock held. 90 | */ 91 | static double calculate_rate_ratio(struct ac3_sink *inst) 92 | { 93 | size_t i; 94 | double accum; 95 | const int32_t tmp = buffer_used(inst); 96 | const double mult = AC3_SINK_LOOP_GAIN; 97 | int32_t offset = AC3_SINK_BUFFER_TARGET_SAMPLES - tmp; 98 | 99 | /* Clamp the max offset so that the max rate ratio is 100 | * purely limited by the gain. 101 | */ 102 | if (offset < -AC3_SINK_BUFFER_TARGET_SAMPLES) { 103 | offset = -AC3_SINK_BUFFER_TARGET_SAMPLES; 104 | } else if (offset > AC3_SINK_BUFFER_TARGET_SAMPLES) { 105 | offset = AC3_SINK_BUFFER_TARGET_SAMPLES; 106 | } 107 | 108 | inst->history[inst->histidx] = offset; 109 | inst->histidx++; 110 | inst->histidx &= (AC3_SINK_BUFFER_HIST_SIZE - 1u); 111 | 112 | accum = 0; 113 | for (i = 0; i < AC3_SINK_BUFFER_HIST_SIZE; i++) { 114 | accum += inst->history[i]; 115 | } 116 | accum /= AC3_SINK_BUFFER_HIST_SIZE; 117 | 118 | inst->average = accum; 119 | 120 | return ((mult * accum) + 1.0); 121 | } 122 | 123 | /* Get the Pulseaudio buffer size required to achieve the 124 | * requested latency. 125 | */ 126 | static uint32_t calculate_pa_buf_size(struct ac3_sink *inst, 127 | uint32_t latency_us) 128 | { 129 | const double latency_seconds = ((double)latency_us / 1000000.0); 130 | const double latency_samples = latency_seconds / (1.0 / 48000.0); 131 | /* Six channels, 4 byte samples. */ 132 | const uint32_t bytes = latency_samples * 4u * 6u; 133 | 134 | if (!latency_us || (bytes < AC3_SINK_PA_BUFFER_SIZE)) { 135 | printf("Using default sink buffer size of %d bytes\n", AC3_SINK_PA_BUFFER_SIZE); 136 | return AC3_SINK_PA_BUFFER_SIZE; 137 | } 138 | 139 | printf("PA buffer size = %d bytes\n", bytes); 140 | 141 | return bytes; 142 | } 143 | 144 | /* Open the ac3 sink. */ 145 | void ac3_sink_open(struct ac3_sink *inst, uint32_t latency_us) 146 | { 147 | size_t i; 148 | int error; 149 | uint32_t bufsize; 150 | pa_buffer_attr attr; 151 | 152 | static const pa_sample_spec pa_ss = { 153 | .format = PA_SAMPLE_FLOAT32LE, 154 | .rate = 48000, 155 | .channels = 6 156 | }; 157 | 158 | static const pa_channel_map channel_map = { 159 | .channels = 6, 160 | .map[0] = PA_CHANNEL_POSITION_FRONT_LEFT, 161 | .map[1] = PA_CHANNEL_POSITION_FRONT_RIGHT, 162 | .map[2] = PA_CHANNEL_POSITION_FRONT_CENTER, 163 | .map[3] = PA_CHANNEL_POSITION_LFE, 164 | #ifdef USE_AC3_SURROUND_MAPPING 165 | .map[4] = PA_CHANNEL_POSITION_SIDE_LEFT, 166 | .map[5] = PA_CHANNEL_POSITION_SIDE_RIGHT, 167 | #else 168 | .map[4] = PA_CHANNEL_POSITION_REAR_LEFT, 169 | .map[5] = PA_CHANNEL_POSITION_REAR_RIGHT, 170 | #endif 171 | }; 172 | 173 | memset(inst, 0, sizeof(struct ac3_sink)); 174 | 175 | /* Initialize buffer to be at the target. This provides a better starting point for the loop. */ 176 | inst->write_idx = AC3_SINK_BUFFER_TARGET_SAMPLES; 177 | 178 | pthread_mutex_init(&inst->lock, NULL); 179 | pthread_cond_init(&inst->cond, NULL); 180 | 181 | /* Open decoder context. */ 182 | #ifdef FFMPEG_OLD_AUDIO_API 183 | inst->packet = malloc(sizeof(AVPacket)); 184 | av_init_packet(inst->packet); 185 | #else 186 | inst->packet = av_packet_alloc(); 187 | #endif 188 | inst->frame = av_frame_alloc(); 189 | 190 | /* TODO - Handle all of these failure cases. */ 191 | 192 | inst->codec = avcodec_find_decoder(AV_CODEC_ID_AC3); 193 | if (!inst->codec) { 194 | printf("Can't find AC3 decoder\n"); 195 | } 196 | 197 | inst->cctx = avcodec_alloc_context3(inst->codec); 198 | if (!inst->cctx) { 199 | printf("Couldn't allocate codec context\n"); 200 | } 201 | 202 | if (avcodec_open2(inst->cctx, inst->codec, NULL) < 0) { 203 | printf("Couldn't open codec\n"); 204 | } 205 | 206 | /* Allocate a separate resampler for each channel. This is done 207 | * because the resampler expects the channels to be interleaved 208 | * into one array, but libavcodec gives it to us in separate arrays. 209 | */ 210 | for (i = 0; i < AC3_SINK_NUM_CHANNELS; i++) { 211 | inst->rate_converter[i] = src_new(SRC_SINC_BEST_QUALITY, 1, &error); 212 | if (!inst->rate_converter[i]) { 213 | printf("Could not create sample rate converter instance\n"); 214 | /* TODO - Handle failure. Program will crash if output is called... */ 215 | } 216 | } 217 | 218 | /* Configure buffer for low latency. */ 219 | bufsize = calculate_pa_buf_size(inst, latency_us); 220 | attr.maxlength = bufsize; 221 | attr.tlength = bufsize; 222 | attr.prebuf = bufsize; 223 | attr.minreq = 8; 224 | attr.fragsize = -1; 225 | 226 | 227 | /* Open simple pulseaudio context. */ 228 | inst->pa_inst = pa_simple_new(NULL, 229 | PROGRAM_NAME_STR, 230 | PA_STREAM_PLAYBACK, 231 | NULL, 232 | "Audio Async Loopback", 233 | &pa_ss, 234 | &channel_map, 235 | &attr, 236 | &error); 237 | if (!inst->pa_inst) { 238 | printf("Could not open Pulseaudio context (error = %d)\n", error); 239 | /* TODO - Handle failure. Program will crash if output is called... */ 240 | } 241 | 242 | /* Pre-set these fields as an optimization. Only the required 243 | * fields get updated in the process call. 244 | */ 245 | inst->src_data.output_frames = (sizeof(inst->tmp_output_buf[0]) / sizeof(float)); 246 | inst->src_data.end_of_input = 0; 247 | inst->src_data.src_ratio = 1.0; 248 | 249 | inst->thread_run = true; 250 | pthread_create(&inst->thread, NULL, output_thread, inst); 251 | /* TODO - Check return. */ 252 | } 253 | 254 | /* Close the ac3 sink. */ 255 | void ac3_sink_close(struct ac3_sink *inst) 256 | { 257 | size_t i; 258 | int error; 259 | 260 | /* Kill the thread. */ 261 | pthread_mutex_lock(&inst->lock); 262 | inst->thread_run = false; 263 | pthread_cond_broadcast(&inst->cond); 264 | pthread_mutex_unlock(&inst->lock); 265 | pthread_join(inst->thread, NULL); 266 | 267 | /* Kill Pulseaudio connection. */ 268 | pa_simple_flush(inst->pa_inst, &error); 269 | pa_simple_free(inst->pa_inst); 270 | 271 | /* Cleanup the rate converter. */ 272 | for (i = 0; i < AC3_SINK_NUM_CHANNELS; i++) { 273 | src_delete(inst->rate_converter[i]); 274 | } 275 | 276 | avcodec_close(inst->cctx); 277 | avcodec_free_context(&inst->cctx); 278 | av_frame_free(&inst->frame); 279 | } 280 | 281 | /* Send a chunk of interleaved left/right s16le ac3 samples 282 | * to the sink. There's no length argument because this sub-module 283 | * relies on the top level chunk size anyway... 284 | */ 285 | void ac3_sink_process(struct ac3_sink *inst, uint8_t *data, size_t len) 286 | { 287 | size_t i; 288 | int error; 289 | #ifdef FFMPEG_OLD_AUDIO_API 290 | int got_one; 291 | #endif 292 | uint32_t can_queue; 293 | 294 | inst->packet->data = data; 295 | inst->packet->size = len; 296 | 297 | #ifdef FFMPEG_OLD_AUDIO_API 298 | error = avcodec_decode_audio4(inst->cctx, inst->frame, &got_one, inst->packet); 299 | if (error < 0) { 300 | printf("Error decoding AC3 frame\n"); 301 | return; 302 | } 303 | 304 | if (!got_one) { 305 | printf("No AC3 frame was decoded\n"); 306 | return; 307 | } 308 | #else 309 | /* Submit. */ 310 | error = avcodec_send_packet(inst->cctx, inst->packet); 311 | if (error == AVERROR(EAGAIN)) { 312 | /* From the doc: Input is not accepted in the current state - user 313 | * must read output with avcodec_receive_frame(). 314 | */ 315 | printf("avcodec_send_packet returned EAGAIN - discarding frames...\n"); 316 | while (!avcodec_receive_frame(inst->cctx, inst->frame)) { 317 | /* Just drop all frames until the decoder is ready to accept new input. 318 | * We will pick back up on the next frame. 319 | */ 320 | } 321 | return; 322 | } else if (error < 0) { 323 | /* Decoding failed. */ 324 | printf("Error decoding AC3 frame\n"); 325 | return; 326 | } 327 | 328 | /* Pull out the decoded frame. */ 329 | error = avcodec_receive_frame(inst->cctx, inst->frame); 330 | if (error) { 331 | printf("No AC3 frame was decoded\n"); 332 | return; 333 | } 334 | #endif 335 | 336 | if (inst->frame->channels != 6) { 337 | /* Only 5.1 is supported for now. This is mainly because I don't 338 | * handle all of the other channel mappings yet. I suppose this 339 | * could be fixed by defining all of the possible mappings and 340 | * using a lookup table with different ring buffer write routines. 341 | */ 342 | printf("Only 5.1 is supported right now (channels = %d)\n", inst->frame->channels); 343 | return; 344 | } 345 | 346 | /* Resample each channel. */ 347 | for (i = 0; i < AC3_SINK_NUM_CHANNELS; i++) { 348 | inst->src_data.data_in = (float *)inst->frame->data[i]; 349 | inst->src_data.data_out = inst->tmp_output_buf[i]; 350 | inst->src_data.input_frames = inst->frame->nb_samples; 351 | 352 | /* Resample. */ 353 | if ((error = src_process(inst->rate_converter[i], &inst->src_data))) { 354 | printf("AC3 sink rate converter error %s\n", src_strerror(error)); 355 | } 356 | } 357 | 358 | /* NOTE: The resampler is being called with the same ratio for each channel, 359 | * so the number of output frames should be the same for all channels. 360 | */ 361 | 362 | pthread_mutex_lock(&inst->lock); 363 | 364 | inst->src_data.src_ratio = calculate_rate_ratio(inst); 365 | 366 | #if DEBUG 367 | printf("Buffer: %04d Ratio: %f Avg: %d\n", buffer_used(inst), inst->src_data.src_ratio, inst->average); 368 | #endif 369 | 370 | /* First, figure out how many samples we can queue. */ 371 | can_queue = buffer_space_avail(inst); 372 | 373 | if (can_queue < (inst->src_data.output_frames_gen * 6)) { 374 | printf("Can't fit entire frame, so dropping entire frame (%d < %lu)\n", 375 | can_queue, 376 | inst->src_data.output_frames_gen * 6); 377 | pthread_mutex_unlock(&inst->lock); 378 | return; 379 | } 380 | 381 | /* Copy into ring buffer, observing the channel mapping. */ 382 | for (i = 0; i < inst->src_data.output_frames_gen; i++) { 383 | 384 | /* Front left. */ 385 | inst->buffer[inst->write_idx & AC3_SINK_SAMPLE_BUFFER_SIZE_MASK] = inst->tmp_output_buf[0][i]; 386 | inst->write_idx++; 387 | 388 | /* Front right. */ 389 | inst->buffer[inst->write_idx & AC3_SINK_SAMPLE_BUFFER_SIZE_MASK] = inst->tmp_output_buf[1][i]; 390 | inst->write_idx++; 391 | 392 | /* Center. */ 393 | inst->buffer[inst->write_idx & AC3_SINK_SAMPLE_BUFFER_SIZE_MASK] = inst->tmp_output_buf[2][i]; 394 | inst->write_idx++; 395 | 396 | /* LFE. */ 397 | inst->buffer[inst->write_idx & AC3_SINK_SAMPLE_BUFFER_SIZE_MASK] = inst->tmp_output_buf[3][i]; 398 | inst->write_idx++; 399 | 400 | /* Rear left. */ 401 | inst->buffer[inst->write_idx & AC3_SINK_SAMPLE_BUFFER_SIZE_MASK] = inst->tmp_output_buf[4][i]; 402 | inst->write_idx++; 403 | 404 | /* Rear right. */ 405 | inst->buffer[inst->write_idx & AC3_SINK_SAMPLE_BUFFER_SIZE_MASK] = inst->tmp_output_buf[5][i]; 406 | inst->write_idx++; 407 | } 408 | 409 | pthread_mutex_unlock(&inst->lock); 410 | pthread_cond_broadcast(&inst->cond); 411 | } 412 | -------------------------------------------------------------------------------- /ac3_sink.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of audio_async_loopback 3 | * Copyright (c) 2020 Jacob Moroni. 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, version 3. 8 | * 9 | * This program is distributed in the hope that it will be useful, but 10 | * WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | #ifndef _AC3_SINK_H_ 19 | #define _AC3_SINK_H_ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | #include "config.h" 30 | 31 | #define AC3_SINK_NUM_CHANNELS 6 32 | 33 | struct ac3_sink { 34 | pthread_mutex_t lock; 35 | pthread_t thread; 36 | pthread_cond_t cond; 37 | bool thread_run; 38 | 39 | SRC_STATE *rate_converter[AC3_SINK_NUM_CHANNELS]; 40 | pa_simple *pa_inst; 41 | 42 | /* This needs to be large enough to store an entire AC3 frame worth of 43 | * samples _after_ resampling. The AC3 frames are typically 1536 samples, 44 | * so add some padding to account for a ratio > 1. 45 | */ 46 | float tmp_output_buf[AC3_SINK_NUM_CHANNELS][4096]; 47 | 48 | 49 | float buffer[AC3_SINK_SAMPLE_BUFFER_SIZE]; 50 | uint32_t read_idx; 51 | uint32_t write_idx; 52 | 53 | SRC_DATA src_data; 54 | 55 | const AVCodec *codec; 56 | AVCodecContext *cctx; 57 | AVPacket *packet; 58 | AVFrame *frame; 59 | 60 | int32_t history[AC3_SINK_BUFFER_HIST_SIZE]; 61 | uint32_t histidx; 62 | int32_t average; /* Informational only */ 63 | }; 64 | 65 | void ac3_sink_open(struct ac3_sink *inst, uint32_t latency_us); 66 | 67 | void ac3_sink_close(struct ac3_sink *inst); 68 | 69 | /* Data is a pointer to a complete AC3 frame. */ 70 | void ac3_sink_process(struct ac3_sink *inst, uint8_t *data, size_t len); 71 | 72 | 73 | #endif /* _AC3_SINK_H_ */ 74 | -------------------------------------------------------------------------------- /config.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of audio_async_loopback 3 | * Copyright (c) 2020 Jacob Moroni. 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, version 3. 8 | * 9 | * This program is distributed in the hope that it will be useful, but 10 | * WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | #ifndef _CONFIG_H_ 19 | #define _CONFIG_H_ 20 | 21 | #define PROGRAM_NAME_STR "audio_async_loopback" 22 | //#define DEBUG 1 23 | 24 | /* Use the old FFMPEG AC3 decoding API (for Ubuntu 16.04). */ 25 | /* #define FFMPEG_OLD_AUDIO_API 1 */ 26 | 27 | /* When Pulseaudio is configured for 4 channels (surround 4.0), the 28 | * sink ends up with Front Left, Front Right, Rear Left, Rear Right. 29 | * However, AC3 considers the rear channels "side". If the AC3 mapping 30 | * is used, no audio will come from the rear channels. 31 | * So, when this is undefined, the AC3 "side" channels get mapped 32 | * to the sink "rear" channels. 33 | * I don't think this should ever be defined, but it's here just 34 | * in case. 35 | */ 36 | #undef USE_AC3_SURROUND_MAPPING 37 | 38 | /* Input data is read out in chunks of this size (in bytes). */ 39 | #define INPUT_CHUNK_SIZE 512u /* 2.6 millisecond chunks */ 40 | 41 | /* Number of input chunks that must pass without receiving a single 42 | * IEC 61937 data burst before considering the input to be a PCM 43 | * stream. 44 | */ 45 | #define IEC_61937_DETECTION_WINDOW 64u 46 | 47 | /* Buffer level measurement averaging depth. 48 | * This is used to smooth out some of the jitter that 49 | * occurs when the buffer utilization is measured. 50 | * This also has side effects on overall loop stability, 51 | * so proceed with caution. 52 | * Must be a power of 2. 53 | */ 54 | #define PCM_SINK_BUFFER_HIST_SIZE 512u 55 | 56 | /* Proportional gain for PCM sink buffer utilization 57 | * control loop. The max sampling rate ratio is: 58 | * (PCM_SINK_BUFFER_TARGET_SAMPLES * PCM_SINK_LOOP_GAIN) + 1. 59 | * This is kept low enough to limit the max ratio to something 60 | * that won't result in audible pitch changes. 61 | */ 62 | #define PCM_SINK_LOOP_GAIN 0.000002 63 | 64 | /* Number of samples to aim to keep in the buffer right before 65 | * the next chunk is added (so, the minimim utilization). 66 | * This should be as low as possible while still being able to 67 | * get a reasonable measurement. If it's too low, then jitter 68 | * may cause larger buffer depletions to not be accounted for. 69 | * In other words, if your jitter is +- 64 samples, then this 70 | * should at least be 128. 71 | */ 72 | #define PCM_SINK_BUFFER_TARGET_SAMPLES 128 73 | 74 | /* PCM sink ring buffer size. Large enough to handle some 75 | * backups, but not so large that it takes forever to each 76 | * the target utilization level. 77 | */ 78 | #define PCM_SINK_SAMPLE_BUFFER_SIZE 2048u 79 | #define PCM_SINK_SAMPLE_BUFFER_SIZE_MASK (PCM_SINK_SAMPLE_BUFFER_SIZE - 1u) 80 | 81 | /* Minimum amount of samples that we will attempt to write 82 | * to the PCM sink output stream. Note that this is SAMPLES 83 | * and not L/R frames or bytes. 84 | * NOTE: This must be a multiple of 2 otherwise the Pulseaudio 85 | * sink can become out of sync w.r.t left/right. 86 | */ 87 | #define PCM_SINK_OUTPUT_CHUNK_SIZE 32u 88 | 89 | /* PCM sink Pulseaudio output buffer. This directly impacts 90 | * the overall latency, so keep it small, but not so small 91 | * that there are a lot of underruns. 92 | * Even though the sampling rate is being adjusted dynamically 93 | * to maintain a buffer level, systems with high scheduling 94 | * jitter can still underrun/overflow the buffer. 95 | */ 96 | #define PCM_SINK_PA_BUFFER_SIZE 2048u /* 5.3 milliseconds */ 97 | 98 | /* See comment above about the PCM sink. Note that this is 99 | * 6 times larger than the PCM value divided by two. 100 | * For the PCM sink we write 16 samples per channel, so 32 total, 101 | * so here we write 96. 102 | */ 103 | #define AC3_SINK_OUTPUT_CHUNK_SIZE 96u 104 | 105 | /* Same as PCM sink, but adjusted for 6 channels. */ 106 | #define AC3_SINK_PA_BUFFER_SIZE 6144u 107 | 108 | /* See comment above regarding PCM. Note that this is 109 | * much smaller because AC3 frames arrive at a much lower 110 | * rate than PCM chunks, so in order to keep the loop 111 | * characteristics similar, this had to be reduced. 112 | */ 113 | #define AC3_SINK_BUFFER_HIST_SIZE 128u 114 | 115 | /* This is just like the PCM sink, but scaled to compensate 116 | * for 6 channels worth of samples. 117 | */ 118 | #define AC3_SINK_LOOP_GAIN 0.0000006666666666666 119 | 120 | /* See PCM comments above. */ 121 | #define AC3_SINK_BUFFER_TARGET_SAMPLES 384 122 | 123 | /* See PCM comments above. */ 124 | #define AC3_SINK_SAMPLE_BUFFER_SIZE 32768u 125 | #define AC3_SINK_SAMPLE_BUFFER_SIZE_MASK (AC3_SINK_SAMPLE_BUFFER_SIZE - 1u) 126 | 127 | 128 | #endif /* _CONFIG_H_ */ 129 | -------------------------------------------------------------------------------- /iec_61937.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of audio_async_loopback 3 | * Copyright (c) 2020 Jacob Moroni. 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, version 3. 8 | * 9 | * This program is distributed in the hope that it will be useful, but 10 | * WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | /* 19 | * IEC 61937 state machine. This processes a stream of samples and 20 | * extracts the data bursts from an IEC 61937 stream. Once a full 21 | * burst is acquired, it sends it to the output by calling the 22 | * callback that was passed during initialization. 23 | * For now, this only supports AC3 frames because the length field 24 | * is dependent on the data type. Sometimes it's bits, sometimes it's 25 | * bytes... 26 | */ 27 | 28 | #include 29 | 30 | #include "iec_61937.h" 31 | 32 | /* Burst header sync words. */ 33 | #define IEC_61937_SYNC_WORD_0 0xF872 34 | #define IEC_61937_SYNC_WORD_1 0x4E1F 35 | #define IEC_61937_DATA_TYPE_MASK 0x3F 36 | 37 | /* Initialize the state machine. */ 38 | void iec_61937_fsm_init(struct iec_61937_fsm *inst, 39 | iec_61937_packet_cb packet_cb, 40 | void *cb_data) 41 | { 42 | memset(inst, 0, sizeof(struct iec_61937_fsm)); 43 | 44 | inst->state = IEC_61937_STATE_FIRST_0; 45 | inst->packet_cb = packet_cb; 46 | inst->cb_data = cb_data; 47 | 48 | return; 49 | } 50 | 51 | /* Process a single sample. Returns true if locked on to a valid 61937 stream. */ 52 | bool iec_61937_fsm_run(struct iec_61937_fsm *inst, uint16_t s16le_sample) 53 | { 54 | bool ret; 55 | uint16_t sample; 56 | 57 | ret = false; 58 | sample = __builtin_bswap16(s16le_sample); 59 | 60 | switch (inst->state) { 61 | case IEC_61937_STATE_FIRST_0: 62 | if (sample == 0x0000) { 63 | inst->state = IEC_61937_STATE_SECOND_0; 64 | } 65 | break; 66 | case IEC_61937_STATE_SECOND_0: 67 | if (sample == 0x0000) { 68 | inst->state = IEC_61937_STATE_THIRD_0;; 69 | } else { 70 | inst->state = IEC_61937_STATE_FIRST_0; 71 | } 72 | break; 73 | case IEC_61937_STATE_THIRD_0: 74 | if (sample == 0x0000) { 75 | inst->state = IEC_61937_STATE_FOURTH_0; 76 | } else { 77 | inst->state = IEC_61937_STATE_FIRST_0; 78 | } 79 | break; 80 | case IEC_61937_STATE_FOURTH_0: 81 | if (sample == 0x0000) { 82 | inst->state = IEC_61937_STATE_SYNC_0; 83 | } else { 84 | inst->state = IEC_61937_STATE_FIRST_0; 85 | } 86 | break; 87 | case IEC_61937_STATE_SYNC_0: 88 | if (sample == 0x0000) { 89 | /* Do nothing - might be receiving a stream of 0's. */ 90 | } else if (sample == IEC_61937_SYNC_WORD_0) { 91 | inst->state = IEC_61937_STATE_SYNC_1; 92 | } else { 93 | inst->state = IEC_61937_STATE_FIRST_0; 94 | } 95 | break; 96 | case IEC_61937_STATE_SYNC_1: 97 | if (sample == IEC_61937_SYNC_WORD_1) { 98 | inst->state = IEC_61937_STATE_DATA_TYPE; 99 | } else { 100 | inst->state = IEC_61937_STATE_FIRST_0; 101 | } 102 | break; 103 | case IEC_61937_STATE_DATA_TYPE: 104 | inst->data_type = sample & IEC_61937_DATA_TYPE_MASK; 105 | inst->state = IEC_61937_STATE_LENGTH; 106 | if (inst->data_type == IEC_61937_DATA_TYPE_EXTENDED) { 107 | /* We don't support the extended headers yet. */ 108 | inst->state = IEC_61937_STATE_FIRST_0; 109 | } 110 | break; 111 | case IEC_61937_STATE_LENGTH: 112 | if (inst->data_type == IEC_61937_DATA_TYPE_AC3) { 113 | inst->bytes_received = 0; 114 | inst->payload_len = sample / 8u; 115 | 116 | /* NOTE: It's possible for payload len to be odd, but since we 117 | * process 16 bit samples at a time, the pad byte just gets 118 | * thrown away. 119 | */ 120 | inst->state = IEC_61937_STATE_PAYLOAD; 121 | } else { 122 | /* The length field units depend on the data type. For AC3, it's bits 123 | * but there's no default, so bail. 124 | */ 125 | inst->state = IEC_61937_STATE_FIRST_0; 126 | } 127 | break; 128 | case IEC_61937_STATE_PAYLOAD: 129 | if ((inst->payload_len - inst->bytes_received) >= 2u) { 130 | /* Copy whole sample. */ 131 | inst->payload[inst->bytes_received] = (sample >> 8u); 132 | inst->bytes_received++; 133 | inst->payload[inst->bytes_received] = sample; 134 | inst->bytes_received++; 135 | } else { 136 | /* Only need one more byte. */ 137 | inst->payload[inst->bytes_received] = (sample >> 8u); 138 | inst->bytes_received++; 139 | } 140 | 141 | if (inst->payload_len == inst->bytes_received) { 142 | /* Send it. */ 143 | inst->packet_cb(inst->data_type, inst->bytes_received, inst->payload, inst->cb_data); 144 | inst->state = IEC_61937_STATE_FIRST_0; 145 | } 146 | break; 147 | } 148 | 149 | if (inst->state > IEC_61937_STATE_SYNC_1) { 150 | /* Declare lock if the second sync word has been received. */ 151 | ret = true; 152 | } 153 | 154 | return ret; 155 | } -------------------------------------------------------------------------------- /iec_61937.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of audio_async_loopback 3 | * Copyright (c) 2020 Jacob Moroni. 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, version 3. 8 | * 9 | * This program is distributed in the hope that it will be useful, but 10 | * WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | #ifndef _IEC_61937_H_ 19 | #define _IEC_61937_H_ 20 | 21 | #include 22 | #include 23 | #include 24 | 25 | /* Max burst payload length (assuming the length is in bytes). */ 26 | #define IEC_61937_MAX_BURST_PAYLOAD 0x10000 27 | 28 | enum iec_61937_data_type { 29 | IEC_61937_DATA_TYPE_AC3 = 0x01, 30 | IEC_61937_DATA_TYPE_EXTENDED = 0x1F, 31 | }; 32 | 33 | enum iec_61937_state { 34 | /* IEC 61937 states that there should always be four 16 bit samples 35 | * before every burst header. This is supposed to make it easier to 36 | * identify IEC 61937 streams by effectively increasing the sync word 37 | * to 96 bits. 38 | */ 39 | IEC_61937_STATE_FIRST_0, 40 | IEC_61937_STATE_SECOND_0, 41 | IEC_61937_STATE_THIRD_0, 42 | IEC_61937_STATE_FOURTH_0, 43 | IEC_61937_STATE_SYNC_0, 44 | IEC_61937_STATE_SYNC_1, 45 | IEC_61937_STATE_DATA_TYPE, 46 | IEC_61937_STATE_LENGTH, 47 | IEC_61937_STATE_PAYLOAD, 48 | }; 49 | 50 | typedef void (*iec_61937_packet_cb)(uint8_t data_type, 51 | size_t len, 52 | uint8_t *payload, 53 | void *handle); 54 | 55 | struct iec_61937_fsm { 56 | enum iec_61937_state state; 57 | iec_61937_packet_cb packet_cb; 58 | void *cb_data; 59 | uint8_t data_type; 60 | size_t payload_len; 61 | size_t bytes_received; 62 | uint8_t payload[IEC_61937_MAX_BURST_PAYLOAD]; 63 | }; 64 | 65 | void iec_61937_fsm_init(struct iec_61937_fsm *inst, 66 | iec_61937_packet_cb packet_cb, 67 | void *cb_data); 68 | 69 | bool iec_61937_fsm_run(struct iec_61937_fsm *inst, uint16_t s16le_sample); 70 | 71 | 72 | #endif /* _IEC_61937_H_ */ 73 | -------------------------------------------------------------------------------- /main.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of audio_async_loopback 3 | * Copyright (c) 2020 Jacob Moroni. 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, version 3. 8 | * 9 | * This program is distributed in the hope that it will be useful, but 10 | * WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | /* 19 | * audio_async_loopback main. Reads from the input and automatically 20 | * determines whether the incoming audio is PCM or an IEC 61937 bitstream 21 | * and sends the data to the appropriate sink for decoding and playback. 22 | * As of now, the only IEC 61937 format supported is 5.1 Channel AC3. 23 | * Other format support could easily be added later if necessary. 24 | */ 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | 37 | #include "config.h" 38 | #include "iec_61937.h" 39 | #include "pcm_sink.h" 40 | #include "ac3_sink.h" 41 | 42 | enum iec_60958_state { 43 | IEC_60958_STATE_UNKNOWN, 44 | IEC_60958_STATE_PCM, 45 | /* Only AC3 is supported for now, with non-AC3 packets getting dropped 46 | * in the output handler. If more formats are added, the 61937 state 47 | * should be split into unique states for each format since they will 48 | * each require different sink implementations. 49 | */ 50 | IEC_60958_STATE_61937, 51 | }; 52 | 53 | struct iec_60958 { 54 | enum iec_60958_state state; 55 | struct iec_61937_fsm iec_61937_fsm_inst; 56 | size_t non_61937_chunks; 57 | struct pcm_sink pcm_sink; 58 | struct ac3_sink ac3_sink; 59 | uint32_t sink_latency_us; 60 | }; 61 | 62 | /* Callback that is called from the IEC 61937 state machine 63 | * for every data burst received. 64 | */ 65 | static void iec_61937_packet_handler(uint8_t data_type, 66 | size_t len, 67 | uint8_t *payload, 68 | void *handle) 69 | { 70 | struct iec_60958 *inst = (struct iec_60958 *)handle; 71 | 72 | if (inst->state != IEC_60958_STATE_61937) { 73 | /* We may still be in the "UNKNOWN" state... */ 74 | return; 75 | } 76 | 77 | if (data_type != IEC_61937_DATA_TYPE_AC3) { 78 | /* Discard non-AC3 data. This also discards pause data bursts 79 | * (if they're actually present in the stream). 80 | */ 81 | return; 82 | } 83 | 84 | ac3_sink_process(&inst->ac3_sink, payload, len); 85 | } 86 | 87 | /* Passes a chunk to the IEC 61937 state machine and 88 | * returns true of an IEC 61937 stream was detected 89 | * within the chunk. 90 | * NOTE: Chunk size must be a multiple of 2. 91 | * TODO: Instead of passing around byte arrays, maybe pass around s16 arrays. 92 | */ 93 | static bool process_chunk_iec_61937(struct iec_61937_fsm *inst, 94 | uint8_t *chunk, 95 | size_t chunk_size) 96 | { 97 | bool ret; 98 | size_t i; 99 | uint16_t sample; 100 | 101 | ret = false; 102 | 103 | for (i = 0; i < chunk_size; i += 2) { 104 | sample = chunk[i]; 105 | sample <<= 8u; 106 | sample |= chunk[i + 1]; 107 | 108 | if (iec_61937_fsm_run(inst, sample)) { 109 | ret = true; 110 | } 111 | } 112 | 113 | return ret; 114 | } 115 | 116 | /* Initializes an IEC 60958 context. */ 117 | static void iec_60958_init(struct iec_60958 *inst) 118 | { 119 | memset(inst, 0, sizeof(struct iec_60958)); 120 | 121 | inst->state = IEC_60958_STATE_UNKNOWN; 122 | iec_61937_fsm_init(&inst->iec_61937_fsm_inst, iec_61937_packet_handler, inst); 123 | } 124 | 125 | /* Processes a chunk of samples. 126 | * It is assumed that the array of bytes contains packed 127 | * 16 bit little endian samples. 128 | */ 129 | static void iec_60958_process(struct iec_60958 *inst, 130 | uint8_t *chunk, 131 | size_t chunk_size) 132 | { 133 | switch (inst->state) { 134 | case IEC_60958_STATE_UNKNOWN: 135 | if (process_chunk_iec_61937(&inst->iec_61937_fsm_inst, chunk, chunk_size)) { 136 | /* Found an IEC 61937 stream. 137 | * NOTE: The call above may have caused some complete data burst 138 | * packets to be sent to the callback, but they will have 139 | * been dropped since the 61937 sink isn't actually open yet. 140 | */ 141 | printf("INIT: Found an IEC 61937 stream\n"); 142 | 143 | inst->non_61937_chunks = 0; 144 | inst->state = IEC_60958_STATE_61937; 145 | 146 | ac3_sink_open(&inst->ac3_sink, inst->sink_latency_us); 147 | } else { 148 | inst->non_61937_chunks++; 149 | if (inst->non_61937_chunks >= IEC_61937_DETECTION_WINDOW) { 150 | printf("INIT: Received %d chunks without a single IEC 61937 data burst; assuming PCM\n", 151 | IEC_61937_DETECTION_WINDOW); 152 | inst->state = IEC_60958_STATE_PCM; 153 | 154 | pcm_sink_open(&inst->pcm_sink, inst->sink_latency_us); 155 | } 156 | } 157 | break; 158 | case IEC_60958_STATE_PCM: 159 | /* Always check for IEC 61937 streams even while receiving PCM. */ 160 | if (process_chunk_iec_61937(&inst->iec_61937_fsm_inst, chunk, chunk_size)) { 161 | /* Going from PCM->61937... */ 162 | printf("Found IEC 61937 stream; switching from PCM\n"); 163 | 164 | pcm_sink_close(&inst->pcm_sink); 165 | 166 | inst->non_61937_chunks = 0; 167 | inst->state = IEC_60958_STATE_61937; 168 | 169 | ac3_sink_open(&inst->ac3_sink, inst->sink_latency_us); 170 | } else { 171 | pcm_sink_process(&inst->pcm_sink, chunk); 172 | } 173 | break; 174 | case IEC_60958_STATE_61937: 175 | if (process_chunk_iec_61937(&inst->iec_61937_fsm_inst, chunk, chunk_size)) { 176 | /* Got IEC 61937 data so reset counter. */ 177 | inst->non_61937_chunks = 0; 178 | } else { 179 | inst->non_61937_chunks++; 180 | if (inst->non_61937_chunks >= IEC_61937_DETECTION_WINDOW) { 181 | printf("Received %d chunks without a single IEC 61937 data burst; switching to PCM\n", 182 | IEC_61937_DETECTION_WINDOW); 183 | inst->state = IEC_60958_STATE_PCM; 184 | 185 | ac3_sink_close(&inst->ac3_sink); 186 | pcm_sink_open(&inst->pcm_sink, inst->sink_latency_us); 187 | } 188 | } 189 | break; 190 | default: 191 | printf("Unhandled state %d in 60958 FSM\n", inst->state); 192 | break; 193 | } 194 | } 195 | 196 | int main(int argc, char*argv[]) 197 | { 198 | int error; 199 | pa_simple *pa_inst; 200 | struct iec_60958 iec_60958_inst; 201 | pa_buffer_attr attr; 202 | /* Keep the buffer in the BSS. */ 203 | static uint8_t buffer[INPUT_CHUNK_SIZE]; 204 | 205 | /* Assume that the S/PDIF interface is always running at a 48 kHz sampling rate */ 206 | static const pa_sample_spec pa_ss = { 207 | .format = PA_SAMPLE_S16LE, 208 | .rate = 48000, 209 | .channels = 2 210 | }; 211 | 212 | static const pa_channel_map channel_map = { 213 | .channels = 2, 214 | .map[0] = PA_CHANNEL_POSITION_FRONT_LEFT, 215 | .map[1] = PA_CHANNEL_POSITION_FRONT_RIGHT, 216 | }; 217 | 218 | if (argc < 2) { 219 | printf("Usage: audio_async_loopback [input name] [latency microsec]\n"); 220 | printf(" Get input name via: pactl list sources\n"); 221 | printf(" Latency is optional\n"); 222 | return EXIT_FAILURE; 223 | } 224 | 225 | #ifdef FFMPEG_OLD_AUDIO_API 226 | 227 | /* Initialize libavcodec. */ 228 | avcodec_register_all(); 229 | 230 | #endif 231 | 232 | /* Configure input buffer for low latency. */ 233 | attr.maxlength = -1; 234 | attr.tlength = -1; 235 | attr.prebuf = -1; 236 | attr.minreq = -1; 237 | attr.fragsize = INPUT_CHUNK_SIZE; 238 | 239 | /* Open simple pulseaudio context. */ 240 | pa_inst = pa_simple_new(NULL, 241 | PROGRAM_NAME_STR, 242 | PA_STREAM_RECORD, 243 | argv[1], 244 | "Audio Async Loopback", 245 | &pa_ss, 246 | &channel_map, 247 | &attr, 248 | &error); 249 | if (!pa_inst) { 250 | printf("Could not open pulseaudio context (error = %d)\n", error); 251 | return EXIT_FAILURE; 252 | } 253 | 254 | /* Open IEC 60958 handler. */ 255 | iec_60958_init(&iec_60958_inst); 256 | 257 | iec_60958_inst.sink_latency_us = 0; 258 | if (argc == 3) { 259 | iec_60958_inst.sink_latency_us = atoi(argv[2]); 260 | if (iec_60958_inst.sink_latency_us == 0) { 261 | printf("Invalid sink latency, using default\n"); 262 | } 263 | } 264 | 265 | /* Get sample chunks and process. */ 266 | while (1) { 267 | if (pa_simple_read(pa_inst, buffer, sizeof(buffer), &error) < 0) { 268 | printf("Could not read sample chunk (error = %d)\n", error); 269 | return EXIT_FAILURE; 270 | } 271 | iec_60958_process(&iec_60958_inst, buffer, sizeof(buffer)); 272 | } 273 | 274 | return EXIT_SUCCESS; 275 | } 276 | -------------------------------------------------------------------------------- /pcm_sink.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of audio_async_loopback 3 | * Copyright (c) 2020 Jacob Moroni. 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, version 3. 8 | * 9 | * This program is distributed in the hope that it will be useful, but 10 | * WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | /* 19 | * Main PCM sink implementation. Accepts an array of interleaved 20 | * left/right s16le samples, converts them to float, passes them 21 | * through the resampler, the finally to the Pulseaudio output. 22 | * The sampling rate ratio is dynamically adjusted to attempt to 23 | * maintain a constant amount of data in the intermediate buffer. 24 | * This is intended to compensate for the fact that the data may 25 | * be coming in and leaving from two different clock domains, like 26 | * if you're capturing from a USB interface and playing back via 27 | * a PCI soundcard. 28 | */ 29 | 30 | #include 31 | #include 32 | #include 33 | 34 | #include "pcm_sink.h" 35 | #include "config.h" 36 | 37 | /* Returns the number of space available, in samples. */ 38 | static uint32_t buffer_space_avail(struct pcm_sink *inst) 39 | { 40 | return (PCM_SINK_SAMPLE_BUFFER_SIZE - (inst->write_idx - inst->read_idx)); 41 | } 42 | 43 | /* Returns the current buffer utilization, in samples. */ 44 | static uint32_t buffer_used(struct pcm_sink *inst) 45 | { 46 | return (inst->write_idx - inst->read_idx); 47 | } 48 | 49 | /* Output thread. Writes data from the intermediate buffer into 50 | * the Pulseaudio stream in units of PCM_SINK_OUTPUT_CHUNK_SIZE 51 | * samples. 52 | */ 53 | static void *output_thread(void *arg) 54 | { 55 | int error; 56 | uint32_t i; 57 | float tmp[PCM_SINK_OUTPUT_CHUNK_SIZE]; 58 | struct pcm_sink *inst = (struct pcm_sink *)arg; 59 | 60 | while (1) { 61 | pthread_mutex_lock(&inst->lock); 62 | 63 | /* Wait for data. */ 64 | while ((buffer_used(inst) < PCM_SINK_OUTPUT_CHUNK_SIZE) && inst->thread_run) { 65 | pthread_cond_wait(&inst->cond, &inst->lock); 66 | } 67 | 68 | if (!inst->thread_run) { 69 | /* Terminate. */ 70 | pthread_mutex_unlock(&inst->lock); 71 | pthread_exit(NULL); 72 | } 73 | 74 | /* Copy out one chunk. */ 75 | for (i = 0; i < PCM_SINK_OUTPUT_CHUNK_SIZE; i++) { 76 | tmp[i] = inst->buffer[inst->read_idx & PCM_SINK_SAMPLE_BUFFER_SIZE_MASK]; 77 | inst->read_idx++; 78 | } 79 | 80 | pthread_mutex_unlock(&inst->lock); 81 | 82 | if (pa_simple_write(inst->pa_inst, tmp, sizeof(tmp), &error) < 0) { 83 | printf("Could not write chunk to output stream (error = %d)\n", error); 84 | } 85 | } 86 | 87 | /* Not reached. */ 88 | pthread_exit(NULL); 89 | } 90 | 91 | /* Calculate a new sampling rate ratio. This should be called 92 | * before adding a new chunk to the ring buffer, and must be 93 | * called with the lock held. 94 | */ 95 | static double calculate_rate_ratio(struct pcm_sink *inst) 96 | { 97 | size_t i; 98 | double accum; 99 | const int32_t tmp = buffer_used(inst); 100 | const double mult = PCM_SINK_LOOP_GAIN; 101 | int32_t offset = PCM_SINK_BUFFER_TARGET_SAMPLES - tmp; 102 | 103 | /* Clamp the max offset so that the max rate ratio is 104 | * purely limited by the gain. 105 | */ 106 | if (offset < -PCM_SINK_BUFFER_TARGET_SAMPLES) { 107 | offset = -PCM_SINK_BUFFER_TARGET_SAMPLES; 108 | } else if (offset > PCM_SINK_BUFFER_TARGET_SAMPLES) { 109 | offset = PCM_SINK_BUFFER_TARGET_SAMPLES; 110 | } 111 | 112 | inst->history[inst->histidx] = offset; 113 | inst->histidx++; 114 | inst->histidx &= (PCM_SINK_BUFFER_HIST_SIZE - 1u); 115 | 116 | accum = 0; 117 | for (i = 0; i < PCM_SINK_BUFFER_HIST_SIZE; i++) { 118 | accum += inst->history[i]; 119 | } 120 | accum /= PCM_SINK_BUFFER_HIST_SIZE; 121 | 122 | inst->average = accum; 123 | 124 | return ((mult * accum) + 1.0); 125 | } 126 | 127 | /* Get the Pulseaudio buffer size required to achieve the 128 | * requested latency. 129 | */ 130 | static uint32_t calculate_pa_buf_size(struct pcm_sink *inst, 131 | uint32_t latency_us) 132 | { 133 | const double latency_seconds = ((double)latency_us / 1000000.0); 134 | const double latency_samples = latency_seconds / (1.0 / 48000.0); 135 | /* Two channels, 4 byte samples. */ 136 | const uint32_t bytes = latency_samples * 4u * 2u; 137 | 138 | if (!latency_us || (bytes < PCM_SINK_PA_BUFFER_SIZE)) { 139 | printf("Using default sink buffer size of %d bytes\n", PCM_SINK_PA_BUFFER_SIZE); 140 | return PCM_SINK_PA_BUFFER_SIZE; 141 | } 142 | 143 | printf("PA buffer size = %d bytes\n", bytes); 144 | 145 | return bytes; 146 | } 147 | 148 | /* Open the PCM sink. */ 149 | void pcm_sink_open(struct pcm_sink *inst, uint32_t latency_us) 150 | { 151 | int error; 152 | uint32_t bufsize; 153 | pa_buffer_attr attr; 154 | 155 | static const pa_sample_spec pa_ss = { 156 | .format = PA_SAMPLE_FLOAT32LE, 157 | .rate = 48000, 158 | .channels = 2 159 | }; 160 | 161 | static const pa_channel_map channel_map = { 162 | .channels = 2, 163 | .map[0] = PA_CHANNEL_POSITION_FRONT_LEFT, 164 | .map[1] = PA_CHANNEL_POSITION_FRONT_RIGHT, 165 | }; 166 | 167 | memset(inst, 0, sizeof(struct pcm_sink)); 168 | 169 | /* Initialize buffer to be at the target. This provides a better starting point for the loop. */ 170 | inst->write_idx = PCM_SINK_BUFFER_TARGET_SAMPLES; 171 | 172 | pthread_mutex_init(&inst->lock, NULL); 173 | pthread_cond_init(&inst->cond, NULL); 174 | 175 | inst->rate_converter = src_new(SRC_SINC_BEST_QUALITY, 2, &error); 176 | if (!inst->rate_converter) { 177 | printf("Could not create sample rate converter instance\n"); 178 | /* TODO - Handle failure. Program will crash if output is called... */ 179 | } 180 | 181 | /* Configure buffer for low latency. */ 182 | bufsize = calculate_pa_buf_size(inst, latency_us); 183 | attr.maxlength = bufsize; 184 | attr.tlength = bufsize; 185 | attr.prebuf = bufsize; 186 | attr.minreq = 8; 187 | attr.fragsize = -1; 188 | 189 | /* Open simple pulseaudio context. */ 190 | inst->pa_inst = pa_simple_new(NULL, 191 | PROGRAM_NAME_STR, 192 | PA_STREAM_PLAYBACK, 193 | NULL, 194 | "Audio Async Loopback", 195 | &pa_ss, 196 | &channel_map, 197 | &attr, 198 | &error); 199 | if (!inst->pa_inst) { 200 | printf("Could not open Pulseaudio context (error = %d)\n", error); 201 | /* TODO - Handle failure. Program will crash if output is called... */ 202 | } 203 | 204 | /* Pre-set these fields as an optimization. Only the required 205 | * fields get updated in the process call. 206 | */ 207 | inst->src_data.data_in = inst->tmp_input_buf; 208 | inst->src_data.data_out = inst->tmp_output_buf; 209 | /* One frame == one left right sample pair. */ 210 | inst->src_data.input_frames = (sizeof(inst->tmp_input_buf) / sizeof(float)) / 2u; 211 | inst->src_data.output_frames = (sizeof(inst->tmp_output_buf) / sizeof(float)) / 2u; 212 | inst->src_data.end_of_input = 0; 213 | inst->src_data.src_ratio = 1.0; 214 | 215 | inst->thread_run = true; 216 | pthread_create(&inst->thread, NULL, output_thread, inst); 217 | /* TODO - Check return. */ 218 | } 219 | 220 | /* Close the PCM sink. */ 221 | void pcm_sink_close(struct pcm_sink *inst) 222 | { 223 | int error; 224 | 225 | /* Kill the thread. */ 226 | pthread_mutex_lock(&inst->lock); 227 | inst->thread_run = false; 228 | pthread_cond_broadcast(&inst->cond); 229 | pthread_mutex_unlock(&inst->lock); 230 | pthread_join(inst->thread, NULL); 231 | 232 | /* Kill Pulseaudio connection. */ 233 | pa_simple_flush(inst->pa_inst, &error); 234 | pa_simple_free(inst->pa_inst); 235 | 236 | /* Cleanup the rate converter. */ 237 | src_delete(inst->rate_converter); 238 | } 239 | 240 | /* Send a chunk of interleaved left/right s16le PCM samples 241 | * to the sink. There's no length argument because this sub-module 242 | * relies on the top level chunk size anyway... 243 | */ 244 | void pcm_sink_process(struct pcm_sink *inst, uint8_t *data) 245 | { 246 | int error; 247 | uint32_t can_queue; 248 | uint32_t will_queue; 249 | uint32_t i; 250 | const uint32_t nr_samples = INPUT_CHUNK_SIZE / 2u; 251 | 252 | /* We should be getting left/right pairs... */ 253 | if (nr_samples & 0x1) { 254 | printf("Program error - odd number of samples\n"); 255 | exit(1); 256 | } 257 | 258 | /* First, run the data through the resampler. All input 259 | * data must pass through the resampler even if it ends 260 | * up getting dropped. 261 | */ 262 | 263 | /* Convert array of int16le to float. */ 264 | for (i = 0; i < nr_samples; i++) { 265 | uint16_t tmp; 266 | int16_t s16le_sample; 267 | 268 | tmp = data[(i * 2u) + 1u]; 269 | tmp <<= 8u; 270 | tmp |= data[i * 2u]; 271 | 272 | s16le_sample = tmp; 273 | 274 | /* Same conversion used by Pulseaudio. */ 275 | inst->tmp_input_buf[i] = s16le_sample * (1.0f / (1u << 15u)); 276 | } 277 | 278 | /* Resample. */ 279 | if ((error = src_process(inst->rate_converter, &inst->src_data))) { 280 | printf("PCM sink rate converter error %s\n", src_strerror(error)); 281 | } 282 | 283 | pthread_mutex_lock(&inst->lock); 284 | 285 | inst->src_data.src_ratio = calculate_rate_ratio(inst); 286 | 287 | #ifdef DEBUG 288 | printf("Buffer: %04d Ratio: %f Avg: %d\n", buffer_used(inst), inst->src_data.src_ratio, inst->average); 289 | #endif 290 | 291 | /* First, figure out how many samples we can queue. 292 | * NOTE: This relies on the fact that the data is drained 293 | * in pairs of samples. If for example only one sample 294 | * is drained, then our Pulseaudio sink might get out 295 | * of sync w.r.t left/right. 296 | */ 297 | can_queue = buffer_space_avail(inst); 298 | 299 | /* MIN */ 300 | if (can_queue < (inst->src_data.output_frames_gen * 2u)) { 301 | will_queue = can_queue; 302 | } else { 303 | will_queue = (inst->src_data.output_frames_gen * 2u); 304 | } 305 | 306 | for (i = 0; i < will_queue; i++) { 307 | inst->buffer[inst->write_idx & PCM_SINK_SAMPLE_BUFFER_SIZE_MASK] = inst->tmp_output_buf[i]; 308 | inst->write_idx++; 309 | } 310 | 311 | pthread_mutex_unlock(&inst->lock); 312 | pthread_cond_broadcast(&inst->cond); 313 | } 314 | -------------------------------------------------------------------------------- /pcm_sink.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of audio_async_loopback 3 | * Copyright (c) 2020 Jacob Moroni. 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, version 3. 8 | * 9 | * This program is distributed in the hope that it will be useful, but 10 | * WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see . 16 | */ 17 | 18 | #ifndef _PCM_SINK_H_ 19 | #define _PCM_SINK_H_ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | #include "config.h" 29 | 30 | struct pcm_sink { 31 | pthread_mutex_t lock; 32 | pthread_t thread; 33 | pthread_cond_t cond; 34 | bool thread_run; 35 | 36 | SRC_STATE *rate_converter; 37 | pa_simple *pa_inst; 38 | 39 | /* The input buffer is basically a chunk but converted from 40 | * int16_t to float. So, chunk size is 128 bytes, which is 64 samples, 41 | * so we need 64 floats. 42 | */ 43 | float tmp_input_buf[INPUT_CHUNK_SIZE / 2]; 44 | 45 | /* The output can actually be larger than the input. For example, 46 | * if the ratio is >2. Our ratio is limited to like 1.1, but let's 47 | * just use double the buffer. This would leave room for something like 48 | * 48k in and 96k out. 49 | */ 50 | float tmp_output_buf[INPUT_CHUNK_SIZE]; 51 | 52 | float buffer[PCM_SINK_SAMPLE_BUFFER_SIZE]; 53 | uint32_t read_idx; 54 | uint32_t write_idx; 55 | 56 | SRC_DATA src_data; 57 | 58 | int32_t history[PCM_SINK_BUFFER_HIST_SIZE]; 59 | uint32_t histidx; 60 | int32_t average; /* Informational only */ 61 | }; 62 | 63 | void pcm_sink_open(struct pcm_sink *inst, uint32_t latency_us); 64 | 65 | void pcm_sink_close(struct pcm_sink *inst); 66 | 67 | /* Data is a pointer to interleaved left/right 16 bit samples. */ 68 | void pcm_sink_process(struct pcm_sink *inst, uint8_t *data); 69 | 70 | 71 | #endif /* _PCM_SINK_H_ */ 72 | --------------------------------------------------------------------------------