├── .dockerignore ├── .gitignore ├── CMakeLists.txt ├── Dockerfile ├── LICENSE ├── README.md ├── cmake └── Findudev.cmake ├── conf └── codecserver.conf ├── debian ├── changelog ├── codecserver-driver-ambe3k.install ├── codecserver.install ├── codecserver.postinst ├── compat ├── control ├── copyright ├── libcodecserver-dev.install ├── libcodecserver.install ├── rules └── source │ └── format ├── docker.sh ├── include ├── config.hpp ├── connection.hpp ├── device.hpp ├── driver.hpp ├── protocol.hpp ├── registry.hpp └── session.hpp ├── src ├── lib │ ├── CMakeLists.txt │ ├── Config.cmake.in │ ├── codecserver.pc.in │ ├── config.cpp │ ├── connection.cpp │ ├── device.cpp │ ├── proto │ │ ├── CMakeLists.txt │ │ ├── check.proto │ │ ├── data.proto │ │ ├── framing.proto │ │ ├── handshake.proto │ │ ├── request.proto │ │ └── response.proto │ └── registry.cpp ├── modules │ ├── CMakeLists.txt │ └── ambe3k │ │ ├── CMakeLists.txt │ │ ├── ambe3kdevice.cpp │ │ ├── ambe3kdevice.hpp │ │ ├── ambe3kdriver.cpp │ │ ├── ambe3kdriver.hpp │ │ ├── ambe3kregistry.cpp │ │ ├── ambe3kregistry.hpp │ │ ├── ambe3ksession.cpp │ │ ├── ambe3ksession.hpp │ │ ├── blockingqueue.cpp │ │ ├── blockingqueue.hpp │ │ ├── channel.cpp │ │ ├── channel.hpp │ │ ├── protocol.cpp │ │ ├── protocol.hpp │ │ ├── queueworker.cpp │ │ ├── queueworker.hpp │ │ ├── udevmonitor.cpp │ │ └── udevmonitor.hpp └── server │ ├── CMakeLists.txt │ ├── clientconnection.cpp │ ├── clientconnection.hpp │ ├── codecserver.cpp │ ├── codecserver.service.in │ ├── scanner.cpp │ ├── scanner.hpp │ ├── server.cpp │ ├── server.hpp │ ├── serverconfig.cpp │ ├── serverconfig.hpp │ ├── socketserver.cpp │ ├── socketserver.hpp │ ├── tcpserver.cpp │ ├── tcpserver.hpp │ ├── unixdomainsocketserver.cpp │ └── unixdomainsocketserver.hpp └── systemd └── codecserver.service /.dockerignore: -------------------------------------------------------------------------------- 1 | build 2 | .git -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | build 3 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required (VERSION 3.6) 2 | 3 | if(NOT CMAKE_BUILD_TYPE) 4 | set(CMAKE_BUILD_TYPE Release) 5 | endif() 6 | 7 | project (codecserver VERSION 0.3.0) 8 | add_definitions(-DVERSION="${PROJECT_VERSION}-dev") 9 | 10 | enable_language(CXX) 11 | set(CMAKE_CXX_STANDARD 17) 12 | 13 | SET(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${PROJECT_SOURCE_DIR}/cmake/") 14 | 15 | include(GNUInstallDirs) 16 | 17 | find_package(Threads REQUIRED) 18 | find_package(protobuf CONFIG) 19 | if (NOT protobuf_FOUND) 20 | include(FindProtobuf) 21 | find_package(Protobuf REQUIRED) 22 | endif() 23 | find_package(udev REQUIRED) 24 | 25 | SET(CMAKE_CXX_FLAGS_DEBUG "-g -O3 -rdynamic") 26 | SET(CMAKE_C_FLAGS_DEBUG "-g -O3") 27 | SET(CMAKE_CXX_FLAGS_RELEASE "-O3 -rdynamic") 28 | SET(CMAKE_C_FLAGS_RELEASE "-O3") 29 | 30 | include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) 31 | 32 | add_subdirectory(src/lib) 33 | add_subdirectory(src/server) 34 | add_subdirectory(src/modules) -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:bullseye-slim 2 | 3 | COPY . /tmp/codecserver 4 | 5 | RUN apt-get update && \ 6 | apt-get -y install --no-install-recommends cmake libprotobuf23 libprotobuf-dev protobuf-compiler libudev-dev make gcc g++ && \ 7 | mkdir -p /tmp/codecserver/build && \ 8 | cd /tmp/codecserver/build && \ 9 | cmake -DCMAKE_INSTALL_PREFIX=/usr .. && \ 10 | make && \ 11 | make install && \ 12 | mkdir -p /etc/codecserver && \ 13 | cp ../conf/codecserver.conf /etc/codecserver && \ 14 | cd && \ 15 | apt-get -y purge --autoremove cmake libprotobuf-dev protobuf-compiler make gcc g++ && \ 16 | apt-get clean && \ 17 | rm -rf /var/lib/apt/lists/* && \ 18 | rm -rf /tmp/codecserver 19 | 20 | EXPOSE 1073 21 | 22 | VOLUME /etc/codecserver 23 | 24 | CMD [ "/usr/bin/codecserver" ] -------------------------------------------------------------------------------- /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 | # Codec Server 2 | 3 | The Codec Server will coordinate central dispatching and coordination of (hardware or software) codecs over the network. 4 | 5 | The network stack is connection-oriented, and runs on Unix domain sockets or TCP over IPv4 or IPv6. 6 | 7 | It uses a protocol based on [protocol buffers](https://developers.google.com/protocol-buffers) (or protobuf for short) to communicate, exchanging length-delimited Any-encapsulated messages on the sockets. 8 | 9 | The codec system is modular, and can be extended with custom drivers and modules. The base package comes with the `ambe3k` driver to interface with AMBE-3000 devices over a serial interface. 10 | 11 | The primary use case for this application is to allow decoding of AMBE-based digital voice modes in the [OpenWebRX](https://www.openwebrx.de) project, but the basic design has been kept neutral so it can be used in other applications as well. 12 | 13 | # Installation 14 | 15 | The OpenWebRX project is hosting codecserver packages in their repositories. Please click the respective link for [Debian](https://www.openwebrx.de/download/debian.php) or [Ubuntu](https://www.openwebrx.de/download/ubuntu.php). 16 | 17 | # Compiling from sources 18 | 19 | Before compiling, please make sure you have the necessary dependencies installed. Most distributions will ship separate development packages for the development files. 20 | 21 | For example, on Debian distributions you will need to install these packages: 22 | 23 | ``` 24 | apt-get install libprotobuf-dev protobuf-compiler libudev-dev 25 | ``` 26 | 27 | This project comes with a cmake build. It is recommended to build in a separate directory. 28 | 29 | ``` 30 | mkdir build 31 | cd build 32 | cmake .. 33 | make 34 | sudo make install 35 | sudo ldconfig 36 | ``` 37 | 38 | A sample configuration is available in the `conf` directory. It needs to be installed manually before the program can run. 39 | 40 | # Configuration 41 | 42 | The configuration file is `/etc/codecserver/codecserver.conf` or `/usr/local/etc/codecserver/codecserver.conf`, depending on your installation. 43 | 44 | The config file uses an INI-style syntax. The section headers use prefixes to specify what part of the system the configuration applies to: 45 | 46 | * `[server:{type}]` sections specify the connectivity that codecserver will make available. The available types are `tcp`, `tcp4` and `unixdomainsockets`. Only the specified servers will be started. 47 | * `[driver:{id}]` sections can be used to specify options that apply to the driver, or all devices of that driver. `id` must match the identification of the driver when registering. Fields of these sections are driver-specific. 48 | * `[device:{name}]` sections allow you to add manually-configured devices. `name` can be freely selected, but must be unique within your configuration. Sections of this kind must have a `type={id}` declaration to specify what driver this config should use. Other fields are driver-specific. 49 | 50 | # systemd integration 51 | 52 | Since most current linux distributions have adopted systemd by now, codecserver will try to register itself as a systemd service during installation. When manually compiling, you will need to run `systemctl daemon-reload` on initial installation. After that, you should be able to control the codecserver service just like any other service unit. 53 | 54 | Examples: 55 | 56 | ``` 57 | systemctl start codecserver 58 | systemctl stop codecserver 59 | systemctl restart codecserver 60 | systemctl enable codecserver 61 | systemctl disable codecserver 62 | journalctl -u codecserver 63 | ``` 64 | 65 | # Docker 66 | 67 | You can find [codecserver Docker images on the Docker hub](https://hub.docker.com/r/jketterl/codecserver). Please have a look at [the wiki](https://github.com/jketterl/codecserver/wiki/Docker) for more information. -------------------------------------------------------------------------------- /cmake/Findudev.cmake: -------------------------------------------------------------------------------- 1 | # - try to find the udev library 2 | # 3 | # Cache Variables: (probably not for direct use in your scripts) 4 | # UDEV_INCLUDE_DIR 5 | # UDEV_SOURCE_DIR 6 | # UDEV_LIBRARY 7 | # 8 | # Non-cache variables you might use in your CMakeLists.txt: 9 | # UDEV_FOUND 10 | # UDEV_INCLUDE_DIRS 11 | # UDEV_LIBRARIES 12 | # 13 | # Requires these CMake modules: 14 | # FindPackageHandleStandardArgs (known included with CMake >=2.6.2) 15 | # 16 | # Original Author: 17 | # Copyright 2014 Kevin M. Godby 18 | # SPDX-License-Identifier: BSL-1.0 19 | # 20 | # Distributed under the Boost Software License, Version 1.0. 21 | # (See accompanying file LICENSE_1_0.txt or copy at 22 | # http://www.boost.org/LICENSE_1_0.txt) 23 | 24 | set(UDEV_ROOT_DIR 25 | "${UDEV_ROOT_DIR}" 26 | CACHE 27 | PATH 28 | "Directory to search for udev") 29 | 30 | find_package(PkgConfig QUIET) 31 | if(PKG_CONFIG_FOUND) 32 | pkg_check_modules(PC_LIBUDEV libudev) 33 | endif() 34 | 35 | find_library(UDEV_LIBRARY 36 | NAMES 37 | udev 38 | PATHS 39 | ${PC_LIBUDEV_LIBRARY_DIRS} 40 | ${PC_LIBUDEV_LIBDIR} 41 | HINTS 42 | "${UDEV_ROOT_DIR}" 43 | PATH_SUFFIXES 44 | lib 45 | ) 46 | 47 | get_filename_component(_libdir "${UDEV_LIBRARY}" PATH) 48 | 49 | find_path(UDEV_INCLUDE_DIR 50 | NAMES 51 | libudev.h 52 | PATHS 53 | ${PC_LIBUDEV_INCLUDE_DIRS} 54 | ${PC_LIBUDEV_INCLUDEDIR} 55 | HINTS 56 | "${_libdir}" 57 | "${_libdir}/.." 58 | "${UDEV_ROOT_DIR}" 59 | PATH_SUFFIXES 60 | include 61 | ) 62 | 63 | include(FindPackageHandleStandardArgs) 64 | find_package_handle_standard_args(udev 65 | DEFAULT_MSG 66 | UDEV_LIBRARY 67 | UDEV_INCLUDE_DIR 68 | ) 69 | 70 | if(UDEV_FOUND) 71 | list(APPEND UDEV_LIBRARIES ${UDEV_LIBRARY}) 72 | list(APPEND UDEV_INCLUDE_DIRS ${UDEV_INCLUDE_DIR}) 73 | mark_as_advanced(UDEV_ROOT_DIR) 74 | endif() 75 | 76 | mark_as_advanced(UDEV_INCLUDE_DIR 77 | UDEV_LIBRARY) 78 | -------------------------------------------------------------------------------- /conf/codecserver.conf: -------------------------------------------------------------------------------- 1 | # unix domain socket server for local use 2 | [server:unixdomainsockets] 3 | #socket=/tmp/codecserver.sock 4 | 5 | # tcp server for use over network 6 | [server:tcp] 7 | #port=1073 8 | #bind=:: 9 | 10 | # example config for an USB-3000 or similar device 11 | #[device:dv3k] 12 | #driver=ambe3k 13 | #tty=/dev/ttyUSB0 14 | #baudrate=921600 15 | -------------------------------------------------------------------------------- /debian/changelog: -------------------------------------------------------------------------------- 1 | codecserver (0.3.0) UNRELEASED; urgency=low 2 | 3 | * Introduce a protocol version field in the handshake 4 | * Fixes handling of channel data, thus allowing to encode voice data 5 | 6 | -- Jakob Ketterl Thu, 16 Jun 2022 17:50:00 +0000 7 | 8 | codecserver (0.2.0) bullseye jammy; urgency=low 9 | 10 | * Rework protocol to fix problems with AMBE-3000 (single channel) devices 11 | * Added udev integration to process USB hotplug events (including the ones 12 | during boot) 13 | 14 | -- Jakob Ketterl Tue, 14 Jun 2022 20:48:00 +0000 15 | 16 | codecserver (0.1.0) buster hirsute; urgency=low 17 | 18 | * First release 19 | 20 | -- Jakob Ketterl Mon, 02 Aug 2021 14:56:00 +0000 21 | -------------------------------------------------------------------------------- /debian/codecserver-driver-ambe3k.install: -------------------------------------------------------------------------------- 1 | usr/lib/*/codecserver/libambe3k.so -------------------------------------------------------------------------------- /debian/codecserver.install: -------------------------------------------------------------------------------- 1 | usr/bin/codecserver 2 | lib/systemd/system 3 | conf/codecserver.conf etc/codecserver -------------------------------------------------------------------------------- /debian/codecserver.postinst: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | 4 | CODECSERVER_USER="codecserver" 5 | 6 | case "$1" in 7 | configure|reconfigure) 8 | adduser --system --group --no-create-home --home /nonexistent --quiet "${CODECSERVER_USER}" 9 | usermod -aG dialout "${CODECSERVER_USER}" 10 | ;; 11 | *) 12 | echo "postinst called with unknown argument '$1'" 1>&2 13 | exit 1 14 | ;; 15 | esac 16 | 17 | #DEBHELPER# 18 | -------------------------------------------------------------------------------- /debian/compat: -------------------------------------------------------------------------------- 1 | 10 -------------------------------------------------------------------------------- /debian/control: -------------------------------------------------------------------------------- 1 | Source: codecserver 2 | Maintainer: Jakob Ketterl 3 | Section: hamradio 4 | Priority: optional 5 | Standards-Version: 4.2.0 6 | Build-Depends: debhelper (>= 11), cmake (>= 3), libprotobuf-dev (>= 3), protobuf-compiler (>= 3), libudev-dev 7 | Vcs-Browser: https://github.com/jketterl/codecserver 8 | Vcs-Git: https://github.com/jketterl/codecserver.git 9 | 10 | Package: libcodecserver 11 | Architecture: any 12 | Depends: ${shlibs:Depends}, ${misc:Depends} 13 | Description: Codecserver base library 14 | Contains basic connection and messaging functionality 15 | 16 | Package: libcodecserver-dev 17 | Architecture: any 18 | Depends: libcodecserver (=${binary:Version}), libprotobuf-dev (>= 3), ${shlibs:Depends}, ${misc:Depends} 19 | Description: Codecserver base library - development files 20 | Provides includes and protobuf templates to facilitate codecserver integration 21 | 22 | Package: codecserver 23 | Architecture: any 24 | Depends: adduser, libcodecserver (=${binary:Version}), ${shlibs:Depends}, ${misc:Depends} 25 | Recommends: codecserver-driver-all (=${binary:Version}) 26 | Description: Modular network codec dispatching system 27 | Provides a modular server that can take over audio encoding and decoding over 28 | the network 29 | 30 | Package: codecserver-driver-ambe3k 31 | Architecture: any 32 | Depends: libcodecserver (=${binary:Version}), ${shlibs:Depends}, ${misc:Depends} 33 | Description: Codecserver driver for AMBE-3000 devices 34 | Adds support for AMBE-3000 devices over serial to Codecserver 35 | 36 | Package: codecserver-driver-all 37 | Architecture: any 38 | Depends: codecserver-driver-ambe3k (=${binary:Version}), ${misc:Depends} 39 | Description: Virtual codecserver driver bundle dependency package 40 | This package installs all available codecserver drivers 41 | -------------------------------------------------------------------------------- /debian/copyright: -------------------------------------------------------------------------------- 1 | Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ 2 | 3 | Files: * 4 | License: GPL-3+ 5 | Copyright: 2020-2021 Jakob Ketterl 6 | 7 | Files: LICENSE 8 | Copyright: 2007, Free Software Foundation, Inc. 9 | License: GPL-3+ 10 | 11 | License: GPL-3+ 12 | This program is free software; you can redistribute it and/or modify it under 13 | the terms of the GNU General Public License as published by the Free Software 14 | Foundation; either version 3 of the License, or (at your option) any later 15 | version. 16 | . 17 | This program is distributed in the hope that it will be useful, but WITHOUT 18 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 19 | FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 20 | details. 21 | . 22 | You should have received a copy of the GNU General Public License along with 23 | this package; if not, write to the Free Software Foundation, Inc., 51 Franklin 24 | St, Fifth Floor, Boston, MA 02110-1301 USA 25 | . 26 | On Debian systems, the full text of the GNU General Public License version 3 27 | can be found in the file `/usr/share/common-licenses/GPL-3'. 28 | 29 | License: LGPL-3+ 30 | This program is free software: you can redistribute it and/or modify it under 31 | the terms of the GNU Lesser General Public License as published by the Free 32 | Software Foundation, either version 3 of the License, or (at your option) any 33 | later version. 34 | . 35 | This program is distributed in the hope that it will be useful, but WITHOUT 36 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 37 | FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more 38 | details. 39 | . 40 | You should have received a copy of the GNU General Public License along with 41 | this package; if not, write to the Free Software Foundation, Inc., 51 Franklin 42 | St, Fifth Floor, Boston, MA 02110-1301 USA 43 | . 44 | On Debian systems, the full text of the GNU Lesser General Public License 45 | version 3 can be found in the file `/usr/share/common-licenses/LGPL-3'. 46 | -------------------------------------------------------------------------------- /debian/libcodecserver-dev.install: -------------------------------------------------------------------------------- 1 | usr/include 2 | usr/lib/*/pkgconfig 3 | usr/lib/*/libcodecserver.so 4 | usr/lib/*/cmake -------------------------------------------------------------------------------- /debian/libcodecserver.install: -------------------------------------------------------------------------------- 1 | usr/lib/*/libcodecserver.so.* -------------------------------------------------------------------------------- /debian/rules: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | %: 3 | dh $@ 4 | 5 | override_dh_makeshlibs: 6 | dh_makeshlibs -Xlibambe3k.so 7 | -------------------------------------------------------------------------------- /debian/source/format: -------------------------------------------------------------------------------- 1 | 3.0 (native) -------------------------------------------------------------------------------- /docker.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | ARCH=$(uname -m) 5 | ALL_ARCHS="x86_64 armv7l aarch64" 6 | TAG=${TAG:-"latest"} 7 | ARCHTAG="${TAG}-${ARCH}" 8 | 9 | usage () { 10 | echo "Usage: ${0} [command]" 11 | echo "Available commands:" 12 | echo " help Show this usage information" 13 | echo " build Build docker image" 14 | echo " push Push built docker image to the docker hub" 15 | echo " manifest Compile the docker hub manifest (combines arm and x86 tags into one)" 16 | echo " tag Tag a release" 17 | } 18 | 19 | build () { 20 | docker build --pull -t jketterl/codecserver:${ARCHTAG} . 21 | } 22 | 23 | push () { 24 | docker push jketterl/codecserver:${ARCHTAG} 25 | } 26 | 27 | manifest () { 28 | # there's no docker manifest rm command, and the create --amend does not work, so we have to clean up manually 29 | rm -rf "${HOME}/.docker/manifests/docker.io_jketterl_codecserver-${TAG}" 30 | IMAGE_LIST="" 31 | for a in ${ALL_ARCHS}; do 32 | IMAGE_LIST="${IMAGE_LIST} jketterl/codecserver:${TAG}-${a}" 33 | done 34 | docker manifest create jketterl/codecserver:${TAG} ${IMAGE_LIST} 35 | docker manifest push --purge jketterl/codecserver:${TAG} 36 | } 37 | 38 | tag () { 39 | if [[ -x ${1:-} || -z ${2:-} ]] ; then 40 | echo "Usage: ${0} tag [SRC_TAG] [TARGET_TAG]" 41 | return 42 | fi 43 | 44 | local SRC_TAG=${1} 45 | local TARGET_TAG=${2} 46 | 47 | # there's no docker manifest rm command, and the create --amend does not work, so we have to clean up manually 48 | rm -rf "${HOME}/.docker/manifests/docker.io_jketterl_codecserver-${TARGET_TAG}" 49 | IMAGE_LIST="" 50 | for a in ${ALL_ARCHS}; do 51 | docker pull jketterl/codecserver:${SRC_TAG}-${a} 52 | docker tag jketterl/codecserver:${SRC_TAG}-${a} jketterl/codecserver:${TARGET_TAG}-${a} 53 | docker push jketterl/codecserver:${TARGET_TAG}-${a} 54 | IMAGE_LIST="${IMAGE_LIST} jketterl/codecserver:${TARGET_TAG}-${a}" 55 | done 56 | docker manifest create jketterl/codecserver:${TARGET_TAG} ${IMAGE_LIST} 57 | docker manifest push --purge jketterl/codecserver:${TARGET_TAG} 58 | docker pull jketterl/codecserver:${TARGET_TAG} 59 | } 60 | 61 | case ${1:-} in 62 | build) 63 | build 64 | ;; 65 | push) 66 | push 67 | ;; 68 | manifest) 69 | manifest 70 | ;; 71 | tag) 72 | tag ${@:2} 73 | ;; 74 | *) 75 | usage 76 | ;; 77 | esac -------------------------------------------------------------------------------- /include/config.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | namespace CodecServer { 10 | 11 | class ConfigException: public std::runtime_error { 12 | public: 13 | ConfigException(const char* msg): std::runtime_error(msg) {} 14 | }; 15 | 16 | class Config { 17 | public: 18 | Config(std::string path); 19 | std::vector getServers(); 20 | std::map getServerConfig(std::string key); 21 | protected: 22 | void read(std::ifstream& input); 23 | std::map> sections; 24 | std::vector getSections(std::string type); 25 | std::map getSection(std::string name); 26 | }; 27 | 28 | } -------------------------------------------------------------------------------- /include/connection.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace google::protobuf::io; 9 | 10 | namespace CodecServer { 11 | 12 | class Connection { 13 | public: 14 | explicit Connection(int sock); 15 | virtual ~Connection(); 16 | bool sendMessage(google::protobuf::Message* message); 17 | google::protobuf::Any* receiveMessage(); 18 | bool sendChannelData(char* buffer, size_t size); 19 | bool sendSpeechData(char* buffer, size_t size); 20 | bool isCompatible(uint32_t protocolVersion); 21 | // use to unblock potentially blocking calls before ~Connection() 22 | void close(); 23 | private: 24 | int sock = -1; 25 | FileInputStream* inStream; 26 | }; 27 | 28 | class ConnectionException: public std::runtime_error { 29 | public: 30 | explicit ConnectionException(const std::string msg): std::runtime_error(msg) {} 31 | }; 32 | 33 | class HandshakeException: public ConnectionException { 34 | public: 35 | explicit HandshakeException(const std::string msg): ConnectionException(msg) {} 36 | }; 37 | 38 | } -------------------------------------------------------------------------------- /include/device.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "proto/request.pb.h" 4 | #include "session.hpp" 5 | #include 6 | #include 7 | 8 | using namespace CodecServer::proto; 9 | 10 | namespace CodecServer { 11 | class DeviceException: public std::runtime_error { 12 | public: 13 | DeviceException(std::string message); 14 | DeviceException(std::string message, int err); 15 | }; 16 | 17 | class Device { 18 | public: 19 | virtual ~Device() = default; 20 | virtual std::vector getCodecs() = 0; 21 | virtual Session* startSession(Request* request) = 0; 22 | }; 23 | } -------------------------------------------------------------------------------- /include/driver.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "device.hpp" 4 | #include 5 | #include 6 | #include 7 | 8 | namespace CodecServer { 9 | 10 | class Driver { 11 | public: 12 | virtual std::string getIdentifier() = 0; 13 | // default implementation is a NOOP 14 | virtual std::vector scanForDevices() { return {}; }; 15 | virtual Device* buildFromConfiguration(std::map config) = 0; 16 | virtual void configure(std::map config) {}; 17 | }; 18 | 19 | } -------------------------------------------------------------------------------- /include/protocol.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #define PROTOCOL_VERSION 1 -------------------------------------------------------------------------------- /include/registry.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "device.hpp" 4 | #include "driver.hpp" 5 | #include 6 | #include 7 | 8 | namespace CodecServer { 9 | 10 | class Registry { 11 | public: 12 | static Registry* get(); 13 | static int registerDriver(Driver* driver); 14 | void configureDriver(std::string driver, std::map config); 15 | void loadDeviceFromConfig(std::map config); 16 | void autoDetectDevices(); 17 | std::vector findDevices(std::string identifier); 18 | void unregisterDevice(Device* device); 19 | private: 20 | std::map drivers; 21 | std::map> devices; 22 | int _registerDriver(Driver* driver); 23 | void registerDevice(Device* device); 24 | }; 25 | 26 | static Registry* sharedRegistry = nullptr; 27 | } -------------------------------------------------------------------------------- /include/session.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include "proto/framing.pb.h" 5 | #include "proto/request.pb.h" 6 | 7 | using namespace CodecServer::proto; 8 | 9 | namespace CodecServer { 10 | 11 | class Session { 12 | public: 13 | virtual ~Session() = default; 14 | virtual void start() {}; 15 | virtual void decode(char* input, size_t size) = 0; 16 | virtual void encode(char* input, size_t size) = 0; 17 | virtual size_t read(char* output) = 0; 18 | virtual void end() {}; 19 | virtual FramingHint* getFraming() { return nullptr; } 20 | virtual void renegotiate(Settings settings) {}; 21 | }; 22 | 23 | } -------------------------------------------------------------------------------- /src/lib/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(CMAKE_POSITION_INDEPENDENT_CODE On) 2 | 3 | add_subdirectory(proto) 4 | 5 | add_library(codecserver SHARED connection.cpp config.cpp registry.cpp device.cpp $) 6 | target_link_libraries(codecserver PUBLIC protobuf::libprotobuf) 7 | set_target_properties(codecserver PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}") 8 | file(GLOB CODECSERVER_HEADERS "${PROJECT_SOURCE_DIR}/include/*.hpp") 9 | set_target_properties(codecserver PROPERTIES PUBLIC_HEADER "${CODECSERVER_HEADERS}") 10 | 11 | # for the protobuf includes 12 | target_include_directories(codecserver PUBLIC $ $) 13 | 14 | install(TARGETS codecserver 15 | EXPORT CodecServerTargets 16 | LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} 17 | PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/codecserver 18 | ) 19 | 20 | configure_file(codecserver.pc.in codecserver.pc @ONLY) 21 | install(FILES ${CMAKE_CURRENT_BINARY_DIR}/codecserver.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) 22 | 23 | install(EXPORT CodecServerTargets 24 | FILE CodecServerTargets.cmake 25 | NAMESPACE CodecServer:: 26 | DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/CodecServer 27 | ) 28 | 29 | include(CMakePackageConfigHelpers) 30 | 31 | configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in 32 | "${CMAKE_CURRENT_BINARY_DIR}/CodecServerConfig.cmake" 33 | INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/CodecServer 34 | ) 35 | 36 | write_basic_package_version_file( 37 | "${CMAKE_CURRENT_BINARY_DIR}/CodecServerConfigVersion.cmake" 38 | VERSION ${PROJECT_VERSION} 39 | COMPATIBILITY AnyNewerVersion 40 | ) 41 | 42 | install(FILES 43 | "${CMAKE_CURRENT_BINARY_DIR}/CodecServerConfig.cmake" 44 | "${CMAKE_CURRENT_BINARY_DIR}/CodecServerConfigVersion.cmake" 45 | DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/CodecServer 46 | ) 47 | -------------------------------------------------------------------------------- /src/lib/Config.cmake.in: -------------------------------------------------------------------------------- 1 | @PACKAGE_INIT@ 2 | 3 | include("${CMAKE_CURRENT_LIST_DIR}/CodecServerTargets.cmake") 4 | 5 | include(CMakeFindDependencyMacro) 6 | if (@protobuf_FOUND@) 7 | find_dependency(protobuf CONFIG) 8 | else() 9 | find_dependency(Protobuf) 10 | endif() 11 | 12 | check_required_components(CodecServer) -------------------------------------------------------------------------------- /src/lib/codecserver.pc.in: -------------------------------------------------------------------------------- 1 | prefix=@CMAKE_INSTALL_PREFIX@ 2 | exec_prefix=@CMAKE_INSTALL_PREFIX@ 3 | libdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@ 4 | includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@ 5 | 6 | Name: @PROJECT_NAME@ 7 | Description: @PROJECT_DESCRIPTION@ 8 | URL: https://github.com/jketterl/owrx_connector 9 | Version: @PROJECT_VERSION@ 10 | 11 | Requires: protobuf 12 | Libs: -L${libdir} -lcodecserver 13 | Cflags: -I${includedir} -------------------------------------------------------------------------------- /src/lib/config.cpp: -------------------------------------------------------------------------------- 1 | #include "config.hpp" 2 | #include 3 | #include 4 | 5 | using namespace CodecServer; 6 | 7 | Config::Config(std::string path) { 8 | std::ifstream input(path); 9 | if (input.fail()) { 10 | throw ConfigException("error opening config file"); 11 | } 12 | read(input); 13 | } 14 | 15 | void Config::read(std::ifstream& input) { 16 | std::string line; 17 | std::set commentChars({';', '#'}); 18 | 19 | std::map current_map; 20 | std::string current_name; 21 | while (getline(input, line)) { 22 | // ignore empty lines 23 | if (line.length() == 0) { 24 | continue; 25 | } 26 | 27 | // ignore comments 28 | if (commentChars.find(line.at(0)) != commentChars.end()) { 29 | continue; 30 | } 31 | 32 | if (line.at(0) == '[' && line.at(line.length() -1) == ']') { 33 | if (current_name != "") { 34 | sections[current_name] = current_map; 35 | } 36 | current_name = line.substr(1, line.length() - 2); 37 | current_map = std::map(); 38 | continue; 39 | } 40 | 41 | size_t pos = line.find("="); 42 | if (pos != std::string::npos) { 43 | std::string key = line.substr(0, pos); 44 | std::string value = line.substr(pos + 1); 45 | current_map[key] = value; 46 | continue; 47 | } 48 | 49 | std::cerr << "invalid line in config: " << line << "\n"; 50 | } 51 | 52 | if (current_name != "") { 53 | sections[current_name] = current_map; 54 | } 55 | } 56 | 57 | 58 | std::vector Config::getSections(std::string type) { 59 | std::vector result; 60 | std::string prefix = type + ":"; 61 | int len = prefix.length(); 62 | for (auto const& element: sections) { 63 | if (element.first.substr(0, len) == prefix) { 64 | result.push_back(element.first.substr(len)); 65 | } 66 | } 67 | return result; 68 | } 69 | 70 | std::map Config::getSection(std::string name) { 71 | return sections[name]; 72 | } 73 | 74 | std::vector Config::getServers() { 75 | return getSections("server"); 76 | } 77 | 78 | std::map Config::getServerConfig(std::string key) { 79 | return getSection("server:" + key); 80 | } -------------------------------------------------------------------------------- /src/lib/connection.cpp: -------------------------------------------------------------------------------- 1 | #include "connection.hpp" 2 | #include "protocol.hpp" 3 | #include "proto/data.pb.h" 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #define BUFFER_SIZE 65536 10 | 11 | using namespace CodecServer; 12 | using namespace CodecServer::proto; 13 | using namespace google::protobuf::io; 14 | 15 | Connection::Connection(int sock) { 16 | this->sock = sock; 17 | inStream = new FileInputStream(sock); 18 | } 19 | 20 | Connection::~Connection() { 21 | close(); 22 | } 23 | 24 | void Connection::close() { 25 | int s = sock; 26 | sock = -1; 27 | auto old = inStream; 28 | inStream = nullptr; 29 | if (s != -1) { 30 | ::shutdown(s, SHUT_RDWR); 31 | ::close(s); 32 | } 33 | delete old; 34 | } 35 | 36 | bool Connection::sendMessage(google::protobuf::Message* message) { 37 | google::protobuf::Any* any = new google::protobuf::Any(); 38 | any->PackFrom(*message); 39 | FileOutputStream* fos = new FileOutputStream(sock); 40 | CodedOutputStream* os = new CodedOutputStream(fos); 41 | #if GOOGLE_PROTOBUF_VERSION < 3006001 42 | uint64_t size = any->ByteSize(); 43 | #else 44 | uint64_t size = any->ByteSizeLong(); 45 | #endif 46 | os->WriteVarint64(size); 47 | bool rc = any->SerializeToCodedStream(os); 48 | delete any; 49 | delete os; 50 | delete fos; 51 | return rc; 52 | } 53 | 54 | google::protobuf::Any* Connection::receiveMessage() { 55 | // this whole block is mostly just about making sure that data is actually 56 | // available on the socket, while exiting early when any conditions arise on 57 | // the socket. Normally, this shouldn't be necessary, but external 58 | // observation shows that the CodecInputStream does not always seem to 59 | // handle socket errors and / or EOF events correctly. 60 | int s; 61 | while ((s = sock) != -1) { 62 | pollfd pfd = { 63 | .fd = s, 64 | .events = POLLIN 65 | }; 66 | 67 | int rc = poll(&pfd, 1, 10000); 68 | if (rc == -1) { 69 | // poll failed 70 | return nullptr; 71 | } 72 | if (pfd.revents & POLLERR) { 73 | // something wrong about the socket 74 | return nullptr; 75 | } 76 | if (pfd.revents & POLLIN) { 77 | // we actually have some data 78 | break; 79 | } 80 | } 81 | 82 | auto stream = inStream; 83 | 84 | if (stream == nullptr) { 85 | return nullptr; 86 | } 87 | 88 | CodedInputStream* is = new CodedInputStream(stream); 89 | uint64_t size; 90 | if (!is->ReadVarint64(&size)) { 91 | delete is; 92 | return nullptr; 93 | } 94 | if (size == 0) { 95 | delete is; 96 | return nullptr; 97 | } 98 | CodedInputStream::Limit l = is->PushLimit(size); 99 | google::protobuf::Any* any = new google::protobuf::Any(); 100 | bool rc = any->ParseFromCodedStream(is); 101 | while (!rc && !is->ConsumedEntireMessage()) { 102 | rc = any->MergeFromCodedStream(is); 103 | } 104 | is->PopLimit(l); 105 | delete is; 106 | if (!rc) { 107 | return nullptr; 108 | } 109 | return any; 110 | } 111 | 112 | bool Connection::sendChannelData(char* bytes, size_t size) { 113 | ChannelData* data = new ChannelData(); 114 | data->set_data(std::string(bytes, size)); 115 | bool rc = sendMessage(data); 116 | delete data; 117 | return rc; 118 | } 119 | 120 | bool Connection::sendSpeechData(char* bytes, size_t size) { 121 | SpeechData* data = new SpeechData(); 122 | data->set_data(std::string(bytes, size)); 123 | bool rc = sendMessage(data); 124 | delete data; 125 | return rc; 126 | } 127 | 128 | bool Connection::isCompatible(uint32_t protocolVersion) { 129 | // this method should model any upwards / downwards compatibility in protocol versions 130 | // precompiler condition is for protection only, it's not necessary to list previous versions here. 131 | #if PROTOCOL_VERSION == 1 132 | // version 0 did not explicitly exist, but protobuf fills the field with 0, which can be used to handle older versions. 133 | // version 1 introduced the protocol version field and is otherwise identical to the previous protocol. 134 | if (protocolVersion == 0 || protocolVersion == 1) return true; 135 | #endif 136 | // an exact match should always pass 137 | return protocolVersion == PROTOCOL_VERSION; 138 | } -------------------------------------------------------------------------------- /src/lib/device.cpp: -------------------------------------------------------------------------------- 1 | #include "device.hpp" 2 | 3 | using namespace CodecServer; 4 | 5 | DeviceException::DeviceException(std::string message): std::runtime_error(message) {} 6 | 7 | DeviceException::DeviceException(std::string message, int err): DeviceException(message + ": " + strerror(err)) {} -------------------------------------------------------------------------------- /src/lib/proto/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | file(GLOB CODECSERVER_PROTO_FILES "*.proto") 2 | add_library(codecserver_proto OBJECT ${CODECSERVER_PROTO_FILES}) 3 | target_link_libraries(codecserver_proto PUBLIC protobuf::libprotobuf) 4 | protobuf_generate(TARGET codecserver_proto LANGUAGE cpp OUT_VAR CODECSERVER_PROTO_GENERATED_FILES) 5 | 6 | set(CODECSERVER_PROTO_HEADERS ${CODECSERVER_PROTO_GENERATED_FILES}) 7 | list(FILTER CODECSERVER_PROTO_HEADERS INCLUDE REGEX "\\.pb\\.h\$") 8 | 9 | install(FILES ${CODECSERVER_PROTO_FILES} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/codecserver/proto) 10 | install(FILES ${CODECSERVER_PROTO_HEADERS} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/codecserver/proto) 11 | -------------------------------------------------------------------------------- /src/lib/proto/check.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package CodecServer.proto; 4 | 5 | message Check { 6 | string codec = 1; 7 | } -------------------------------------------------------------------------------- /src/lib/proto/data.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package CodecServer.proto; 4 | 5 | message ChannelData { 6 | bytes data = 1; 7 | } 8 | 9 | message SpeechData { 10 | bytes data = 1; 11 | } -------------------------------------------------------------------------------- /src/lib/proto/framing.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package CodecServer.proto; 4 | 5 | message FramingHint { 6 | uint32 channelBits = 1; 7 | uint32 channelBytes = 2; 8 | uint32 audioSamples = 3; 9 | uint32 audioBytes = 4; 10 | } -------------------------------------------------------------------------------- /src/lib/proto/handshake.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package CodecServer.proto; 4 | 5 | message Handshake { 6 | string serverName = 1; 7 | string serverVersion = 2; 8 | uint32 protocolVersion = 3; 9 | } -------------------------------------------------------------------------------- /src/lib/proto/request.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package CodecServer.proto; 4 | 5 | message Settings { 6 | enum Direction { 7 | ENCODE = 0; 8 | DECODE = 1; 9 | } 10 | repeated Direction directions = 2; 11 | map args = 1; 12 | } 13 | 14 | message Request { 15 | string codec = 1; 16 | Settings settings = 3; 17 | } 18 | 19 | message Renegotiation { 20 | Settings settings = 1; 21 | } -------------------------------------------------------------------------------- /src/lib/proto/response.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package CodecServer.proto; 4 | 5 | import "framing.proto"; 6 | 7 | message Response { 8 | enum Status { 9 | OK = 0; 10 | ERROR = 1; 11 | } 12 | 13 | Status result = 1; 14 | string message = 2; 15 | FramingHint framing = 3; 16 | } -------------------------------------------------------------------------------- /src/lib/registry.cpp: -------------------------------------------------------------------------------- 1 | #include "registry.hpp" 2 | #include 3 | #include 4 | 5 | using namespace CodecServer; 6 | 7 | int Registry::registerDriver(Driver* driver) { 8 | return Registry::get()->_registerDriver(driver); 9 | } 10 | 11 | int Registry::_registerDriver(Driver* driver) { 12 | if (drivers.find(driver->getIdentifier()) != drivers.end()) { 13 | std::cerr << "failed to register driver \"" << driver->getIdentifier() << "\": already registered!\n"; 14 | return -1; 15 | } 16 | 17 | std::cout << "registering new driver: \"" << driver->getIdentifier() << "\"\n"; 18 | drivers[driver->getIdentifier()] = driver; 19 | 20 | 21 | return 0; 22 | } 23 | 24 | void Registry::configureDriver(std::string driver, std::map config) { 25 | if (drivers.find(driver) == drivers.end()) { 26 | std::cerr << "cannot configure driver \"" << driver << "\": not registered\n"; 27 | return; 28 | } 29 | 30 | drivers[driver]->configure(config); 31 | } 32 | 33 | void Registry::autoDetectDevices() { 34 | for (auto pair: drivers) { 35 | Driver* driver = pair.second; 36 | std::cout << "scanning for \"" << driver->getIdentifier() << "\" devices...\n"; 37 | for (Device* device: driver->scanForDevices()) { 38 | registerDevice(device); 39 | } 40 | } 41 | } 42 | 43 | void Registry::loadDeviceFromConfig(std::map config) { 44 | if (config.find("driver") == config.end()) { 45 | std::cerr << "unable to load device: driver not specified\n"; 46 | return; 47 | } 48 | if (drivers.find(config["driver"]) == drivers.end()) { 49 | std::cerr << "unable to load device: driver \"" << config["driver"] << "\" not available\n"; 50 | return; 51 | } 52 | Driver* driver = drivers[config["driver"]]; 53 | try { 54 | Device* device = driver->buildFromConfiguration(config); 55 | if (device != nullptr) { 56 | registerDevice(device); 57 | } 58 | } catch (const DeviceException& e) { 59 | std::cerr << "unable to create device: " << e.what() << "\n"; 60 | } 61 | } 62 | 63 | void Registry::registerDevice(Device* device) { 64 | std::cout << "registering new device for codecs: "; 65 | 66 | for (std::string codec: device->getCodecs()) { 67 | std::cout << codec << ", "; 68 | devices[codec].push_back(device); 69 | } 70 | std::cout << "\n"; 71 | } 72 | 73 | void Registry::unregisterDevice(Device* device) { 74 | std::cout << "unregistering device\n"; 75 | std::map>::iterator it; 76 | for (it = devices.begin(); it != devices.end(); it++) { 77 | std::vector& vec = it->second; 78 | std::vector::iterator pos = std::find(vec.begin(), vec.end(), device); 79 | if (pos != vec.end()) { 80 | Device* device = (*pos); 81 | vec.erase(pos); 82 | delete device; 83 | } 84 | } 85 | } 86 | 87 | std::vector Registry::findDevices(std::string identifier) { 88 | return devices[identifier]; 89 | } 90 | 91 | Registry* Registry::get() { 92 | if (sharedRegistry == nullptr) { 93 | sharedRegistry = new Registry(); 94 | } 95 | return sharedRegistry; 96 | } -------------------------------------------------------------------------------- /src/modules/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_subdirectory(ambe3k) -------------------------------------------------------------------------------- /src/modules/ambe3k/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_library(ambe3k SHARED ambe3kdriver.cpp ambe3kdevice.cpp ambe3ksession.cpp protocol.cpp blockingqueue.cpp channel.cpp queueworker.cpp udevmonitor.cpp ambe3kregistry.cpp) 2 | target_link_libraries(ambe3k codecserver ${CMAKE_THREAD_LIBS_INIT} ${UDEV_LIBRARIES}) 3 | target_include_directories(ambe3k PUBLIC ${UDEV_INCLUDE_DIRS}) 4 | install(TARGETS ambe3k 5 | LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/codecserver 6 | ) 7 | -------------------------------------------------------------------------------- /src/modules/ambe3k/ambe3kdevice.cpp: -------------------------------------------------------------------------------- 1 | #include "ambe3kdevice.hpp" 2 | #include "registry.hpp" 3 | #include "ambe3ksession.hpp" 4 | #include 5 | #include 6 | #include 7 | 8 | namespace Ambe3K { 9 | 10 | using namespace Protocol; 11 | 12 | using CodecServer::DeviceException; 13 | 14 | Device::Device(const std::string& tty, unsigned int baudRate) { 15 | open(tty, baudRate); 16 | init(); 17 | queue = new BlockingQueue(10); 18 | worker = new QueueWorker(this, fd, queue); 19 | } 20 | 21 | Device::~Device() { 22 | delete worker; 23 | delete queue; 24 | for (Channel* c: channels) { 25 | delete c; 26 | } 27 | ::close(fd); 28 | } 29 | 30 | std::vector Device::getCodecs() { 31 | return { "ambe" }; 32 | } 33 | 34 | CodecServer::Session* Device::startSession(CodecServer::proto::Request* request) { 35 | for (Channel* channel: channels) { 36 | // TODO lock? 37 | if (!channel->isBusy()) { 38 | std::cerr << "starting new session on channel " << +channel->getIndex() << "\n"; 39 | channel->reserve(); 40 | auto* session = new Ambe3KSession(channel); 41 | try { 42 | session->renegotiate(request->settings()); 43 | return session; 44 | } catch (std::invalid_argument&) { 45 | std::cerr << "invalid or unsupported channel index\n"; 46 | } 47 | session->end(); 48 | delete session; 49 | return nullptr; 50 | } 51 | } 52 | return nullptr; 53 | } 54 | 55 | void Device::open(const std::string& ttyname, unsigned int baudRate) { 56 | speed_t baud = convertBaudrate(baudRate); 57 | 58 | fd = ::open(ttyname.c_str(), O_RDWR | O_NOCTTY /*| O_SYNC*/); 59 | if (fd < 0) { 60 | throw DeviceException("could not open TTY", errno); 61 | } 62 | 63 | struct termios tty{}; 64 | if (tcgetattr(fd, &tty) != 0) { 65 | throw DeviceException("tcgetattr error", errno); 66 | } 67 | 68 | if (cfsetispeed(&tty, 0) != 0) { 69 | throw DeviceException("cfsetispeed error", errno); 70 | } 71 | 72 | if (cfsetospeed(&tty, baud) != 0) { 73 | throw DeviceException("cfsetospeed error", errno); 74 | } 75 | 76 | tty.c_lflag &= ~(ECHO | ECHOE | ICANON | IEXTEN | ISIG ); 77 | tty.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON | IXOFF | IXANY); 78 | tty.c_cflag &= ~(CSIZE | CSTOPB | PARENB ); 79 | tty.c_cflag |= CS8; 80 | tty.c_oflag &= ~(OPOST); 81 | tty.c_cc[VMIN] = 0; 82 | tty.c_cc[VTIME] = 10; 83 | 84 | if (tcsetattr(fd, TCSANOW, &tty) != 0) { 85 | throw DeviceException("tcsetattr error", errno); 86 | } 87 | } 88 | 89 | speed_t Device::convertBaudrate(unsigned int baud) { 90 | switch (baud) { 91 | case 9600: 92 | return B9600; 93 | case 19200: 94 | return B19200; 95 | case 38400: 96 | return B38400; 97 | case 57600: 98 | return B57600; 99 | case 115200: 100 | return B115200; 101 | case 230400: 102 | return B230400; 103 | case 460800: 104 | return B460800; 105 | case 500000: 106 | return B500000; 107 | case 576000: 108 | return B576000; 109 | case 921600: 110 | return B921600; 111 | case 1000000: 112 | return B1000000; 113 | case 1152000: 114 | return B1152000; 115 | case 1500000: 116 | return B1500000; 117 | case 2000000: 118 | return B2000000; 119 | case 2500000: 120 | return B2500000; 121 | case 3000000: 122 | return B3000000; 123 | case 3500000: 124 | return B3500000; 125 | case 4000000: 126 | return B4000000; 127 | default: 128 | throw std::runtime_error("invalid baud rate"); 129 | } 130 | } 131 | 132 | void Device::init() { 133 | ResetPacket reset; 134 | reset.writeTo(fd); 135 | 136 | Packet* response = Packet::receiveFrom(fd); 137 | if (response == nullptr) { 138 | throw DeviceException("device did not respond to reset"); 139 | } 140 | 141 | auto* ready = dynamic_cast(response); 142 | if (ready == nullptr) { 143 | delete response; 144 | throw DeviceException("unexpected response from stick"); 145 | } 146 | if (!ready->hasReadyField()) { 147 | delete response; 148 | throw DeviceException("device is not ready after reset"); 149 | } 150 | delete ready; 151 | 152 | ProdIdRequest prodIdRequest; 153 | prodIdRequest.writeTo(fd); 154 | 155 | response = Packet::receiveFrom(fd); 156 | if (response == nullptr) { 157 | throw DeviceException("device did not respond to product id request"); 158 | } 159 | 160 | auto* prodid = dynamic_cast(response); 161 | if (prodid == nullptr) { 162 | delete response; 163 | throw DeviceException("unexpected response from stick"); 164 | } 165 | if (!prodid->hasProductId()) { 166 | delete response; 167 | throw DeviceException("device did not respond with product id as expected"); 168 | } 169 | 170 | VersionStringRequest versionStringRequest; 171 | versionStringRequest.writeTo(fd); 172 | 173 | response = Packet::receiveFrom(fd); 174 | if (response == nullptr) { 175 | throw DeviceException("device did not respond to version string request"); 176 | } 177 | 178 | auto* versionString = dynamic_cast(response); 179 | if (versionString == nullptr) { 180 | delete response; 181 | throw DeviceException("unexpected response from stick"); 182 | } 183 | if (!versionString->hasVersionString()) { 184 | throw DeviceException("device did not response with version string as expected"); 185 | } 186 | 187 | std::cerr << "Product id: " << prodid->getProductId() << "; Version: " << versionString->getVersionString() << "\n"; 188 | 189 | createChannels(prodid->getProductId()); 190 | 191 | delete prodid; 192 | delete versionString; 193 | } 194 | 195 | void Device::createChannels(const std::string& prodId) { 196 | if (prodId.substr(0, 8) == "AMBE3000") { 197 | std::cerr << "detected AMBE3000, creating one channel\n"; 198 | createChannels(1); 199 | return; 200 | } 201 | 202 | if (prodId.substr(0, 8) == "AMBE3003") { 203 | std::cerr << "detected AMBE3003, creating three channels\n"; 204 | createChannels(3); 205 | return; 206 | } 207 | 208 | std::cerr << "unknown product id, cannot create channels\n"; 209 | } 210 | 211 | void Device::createChannels(unsigned int num_channels) { 212 | for (unsigned int i = 0; i < num_channels; i++) { 213 | channels.push_back(new Channel(this, i)); 214 | } 215 | } 216 | 217 | void Device::writePacket(Packet* packet) { 218 | queue->push(packet); 219 | } 220 | 221 | void Device::receivePacket(Packet* packet) { 222 | auto speech = dynamic_cast(packet); 223 | if (speech != nullptr) { 224 | channels[getChannelNumber(packet)]->receive(speech); 225 | return; 226 | } 227 | auto channel = dynamic_cast(packet); 228 | if (channel != nullptr) { 229 | channels[getChannelNumber(channel)]->receive(channel); 230 | return; 231 | } 232 | auto control = dynamic_cast(packet); 233 | if (control != nullptr) { 234 | if (control->hasChannel()) { 235 | std::cerr << "channel " << +control->getChannel() << ": "; 236 | } 237 | if (control->hasInitResponse()) { 238 | std::cerr << "init response received; "; 239 | } 240 | if (control->hasRateTResponse()) { 241 | std::cerr << "RateT response received; "; 242 | } 243 | if (control->hasRatePResponse()) { 244 | std::cerr << "RateP response received; "; 245 | } 246 | std::cerr << "\n"; 247 | delete control; 248 | return; 249 | } 250 | delete packet; 251 | std::cerr << "unexpected packet received from stick\n"; 252 | } 253 | 254 | int Device::getChannelNumber(Packet* packet) { 255 | // fallback for single-channel chips that don't respond with a channel number 256 | if (!packet->hasChannel()) return 0; 257 | // multi-channel devices will have the field set 258 | int channelNo = packet->getChannel(); 259 | // check to avoid goind beyond array limits 260 | assert(channelNo < channels.size()); 261 | return channelNo; 262 | } 263 | 264 | void Device::onQueueError(const std::string& message) { 265 | std::cerr << "ambe3k queue worker reported error: " << message << "\n"; 266 | CodecServer::Registry::get()->unregisterDevice(this); 267 | } 268 | 269 | } -------------------------------------------------------------------------------- /src/modules/ambe3k/ambe3kdevice.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "device.hpp" 4 | #include "protocol.hpp" 5 | #include "channel.hpp" 6 | #include "blockingqueue.hpp" 7 | #include "queueworker.hpp" 8 | #include "proto/request.pb.h" 9 | #include 10 | #include 11 | 12 | namespace Ambe3K { 13 | 14 | class QueueWorker; 15 | 16 | // forward declaration since those two classes are interdependent 17 | class Channel; 18 | 19 | class Device: public CodecServer::Device { 20 | public: 21 | Device(const std::string& tty, unsigned int baudRate); 22 | ~Device() override; 23 | std::vector getCodecs() override; 24 | CodecServer::Session* startSession(CodecServer::proto::Request* request) override; 25 | void writePacket(Ambe3K::Protocol::Packet* packet); 26 | void receivePacket(Ambe3K::Protocol::Packet* packet); 27 | void onQueueError(const std::string& message); 28 | private: 29 | void open(const std::string& tty, unsigned int baudRate); 30 | speed_t convertBaudrate(unsigned int baudRate); 31 | void init(); 32 | void createChannels(const std::string& prodId); 33 | void createChannels(unsigned int num); 34 | int getChannelNumber(Ambe3K::Protocol::Packet* packet); 35 | int fd = 0; 36 | std::vector channels; 37 | BlockingQueue* queue; 38 | QueueWorker* worker; 39 | }; 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/modules/ambe3k/ambe3kdriver.cpp: -------------------------------------------------------------------------------- 1 | #include "ambe3kdriver.hpp" 2 | #include "ambe3kregistry.hpp" 3 | #include "registry.hpp" 4 | #include "udevmonitor.hpp" 5 | #include 6 | 7 | using namespace Ambe3K; 8 | 9 | Driver::Driver() { 10 | new Ambe3K::Udev::Monitor(); 11 | } 12 | 13 | std::string Driver::getIdentifier(){ 14 | return "ambe3k"; 15 | } 16 | 17 | Device* Driver::buildFromConfiguration(std::map config) { 18 | if (config.find("tty") == config.end()) { 19 | std::cerr << "unable to create ambe3k device: tty not specified\n"; 20 | return nullptr; 21 | } 22 | if (config.find("baudrate") == config.end()) { 23 | std::cerr << "unable to create ambe3k device: baudrade not specified\n"; 24 | return nullptr; 25 | } 26 | unsigned int baudrate; 27 | try { 28 | baudrate = stoul(config["baudrate"]); 29 | } catch (const std::invalid_argument&) { 30 | std::cerr << "unable to create ambe3k device: cannot parse baudrate\n"; 31 | return nullptr; 32 | } 33 | 34 | auto* registration = new Registration(); 35 | registration->config = config; 36 | Registry::get()->addDevice(config["tty"], registration); 37 | 38 | // perform this step last since it can throw exceptions 39 | registration->device = new Device(config["tty"], baudrate); 40 | return registration->device; 41 | } 42 | 43 | 44 | static int registration = CodecServer::Registry::registerDriver(new Driver()); -------------------------------------------------------------------------------- /src/modules/ambe3k/ambe3kdriver.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "device.hpp" 4 | #include "driver.hpp" 5 | #include "ambe3kdevice.hpp" 6 | 7 | namespace Ambe3K { 8 | 9 | class Driver: public CodecServer::Driver { 10 | public: 11 | explicit Driver(); 12 | std::string getIdentifier() override; 13 | Device* buildFromConfiguration(std::map config) override; 14 | }; 15 | 16 | } -------------------------------------------------------------------------------- /src/modules/ambe3k/ambe3kregistry.cpp: -------------------------------------------------------------------------------- 1 | #include "ambe3kregistry.hpp" 2 | 3 | using namespace Ambe3K; 4 | 5 | Registry* Registry::get() { 6 | if (sharedInstance == nullptr) { 7 | sharedInstance = new Registry(); 8 | } 9 | return sharedInstance; 10 | } 11 | 12 | void Registry::addDevice(const std::string& node, Registration* device) { 13 | devices[node] = device; 14 | } 15 | 16 | bool Registry::hasDevice(const std::string& node) { 17 | return findByNode(node) != nullptr; 18 | } 19 | 20 | Registration* Registry::findByNode(const std::string& node) { 21 | auto it = devices.find(node); 22 | if (it != devices.end()) { 23 | return it->second; 24 | } 25 | return nullptr; 26 | } -------------------------------------------------------------------------------- /src/modules/ambe3k/ambe3kregistry.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "ambe3kdevice.hpp" 4 | 5 | #include 6 | 7 | namespace Ambe3K { 8 | 9 | struct Registration { 10 | std::map config; 11 | Device* device = nullptr; 12 | }; 13 | 14 | class Registry { 15 | public: 16 | static Registry* get(); 17 | void addDevice(const std::string& node, Registration* device); 18 | bool hasDevice(const std::string& node); 19 | Registration* findByNode(const std::string& node); 20 | private: 21 | std::map devices; 22 | }; 23 | 24 | static Registry* sharedInstance = nullptr; 25 | 26 | } -------------------------------------------------------------------------------- /src/modules/ambe3k/ambe3ksession.cpp: -------------------------------------------------------------------------------- 1 | #include "ambe3ksession.hpp" 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace Ambe3K; 7 | 8 | Ambe3KSession::Ambe3KSession(Channel* channel) { 9 | this->channel = channel; 10 | } 11 | 12 | void Ambe3KSession::encode(char* input, size_t size) { 13 | channel->encode(input, size); 14 | } 15 | 16 | void Ambe3KSession::decode(char* input, size_t size) { 17 | channel->decode(input, size); 18 | } 19 | 20 | size_t Ambe3KSession::read(char* output) { 21 | return channel->read(output); 22 | } 23 | 24 | void Ambe3KSession::end() { 25 | channel->release(); 26 | } 27 | 28 | CodecServer::proto::FramingHint* Ambe3KSession::getFraming() { 29 | unsigned char bits = channel->getFramingBits(); 30 | if (bits == 0) { 31 | return nullptr; 32 | } 33 | CodecServer::proto::FramingHint* framing; 34 | framing = new CodecServer::proto::FramingHint(); 35 | framing->set_channelbits(bits); 36 | framing->set_channelbytes((int)((bits + 7) / 8)); 37 | framing->set_audiosamples(160); 38 | framing->set_audiobytes(320); 39 | return framing; 40 | } 41 | 42 | void Ambe3KSession::renegotiate(CodecServer::proto::Settings settings) { 43 | std::cout << "renegotiating: direction:"; 44 | std::map args(settings.args().begin(), settings.args().end()); 45 | 46 | unsigned char direction = 0; 47 | for (int dir: settings.directions()) { 48 | if (dir == Settings_Direction_ENCODE) { 49 | direction |= AMBE3K_DIRECTION_ENCODE; 50 | std::cout << " enccode"; 51 | } else if (dir == Settings_Direction_DECODE) { 52 | direction |= AMBE3K_DIRECTION_DECODE; 53 | std::cout << " decode"; 54 | } 55 | } 56 | 57 | std::cout << "; "; 58 | 59 | if (args.find("index") != args.end()) { 60 | std::string indexStr = args["index"]; 61 | std::cout << "index: " << indexStr << "\n"; 62 | unsigned char index = std::stoi(indexStr); 63 | channel->setup(index, direction); 64 | } else if (args.find("ratep") != args.end()) { 65 | std::string ratepStr = args["ratep"]; 66 | short* rateP = parseRatePString(ratepStr); 67 | if (rateP == nullptr) { 68 | std::cout << "invalid ratep string\n"; 69 | } else { 70 | std::cout << "ratep: " << ratepStr << "\n"; 71 | channel->setup(rateP, direction); 72 | } 73 | } else { 74 | std::cout << "invalid parameters\n"; 75 | } 76 | } 77 | 78 | short* Ambe3KSession::parseRatePString(const std::string& input) { 79 | if (input.length() != 29) return nullptr; 80 | std::vector parts; 81 | size_t pos_start = 0, pos_end; 82 | while ((pos_end = input.find(':', pos_start)) != std::string::npos) { 83 | parts.push_back(input.substr(pos_start, pos_end - pos_start)); 84 | pos_start = pos_end + 1; 85 | } 86 | parts.push_back(input.substr(pos_start)); 87 | 88 | if (parts.size() != 6) return nullptr; 89 | 90 | auto data = (short*) malloc(sizeof(short) * 6); 91 | for (int i = 0; i < parts.size(); i++) { 92 | std::string part = parts[i]; 93 | if (part.length() != 4) { 94 | free(data); 95 | return nullptr; 96 | } 97 | 98 | std::stringstream ss; 99 | ss << std::hex << part; 100 | ss >> data[i]; 101 | } 102 | 103 | return data; 104 | } 105 | -------------------------------------------------------------------------------- /src/modules/ambe3k/ambe3ksession.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "session.hpp" 4 | #include "ambe3kdevice.hpp" 5 | #include "proto/framing.pb.h" 6 | #include "proto/request.pb.h" 7 | #include 8 | 9 | using namespace CodecServer::proto; 10 | 11 | namespace Ambe3K { 12 | 13 | class Ambe3KSession: public CodecServer::Session { 14 | public: 15 | explicit Ambe3KSession(Channel* channel); 16 | void encode(char* input, size_t size) override; 17 | void decode(char* input, size_t size) override; 18 | size_t read(char* output) override; 19 | void end() override; 20 | FramingHint* getFraming() override; 21 | void renegotiate(Settings settings) override; 22 | private: 23 | Channel* channel; 24 | short* parseRatePString(const std::string& input); 25 | }; 26 | 27 | } -------------------------------------------------------------------------------- /src/modules/ambe3k/blockingqueue.cpp: -------------------------------------------------------------------------------- 1 | #include "blockingqueue.hpp" 2 | #include "protocol.hpp" 3 | 4 | template 5 | BlockingQueue::BlockingQueue(int size): std::queue() { 6 | maxSize = size; 7 | } 8 | 9 | template 10 | void BlockingQueue::push(T* item, bool block) { 11 | std::unique_lock wlck(queueMutex); 12 | if (block) { 13 | while (run && full()) { 14 | isFull.wait(wlck); 15 | } 16 | if (!run) return; 17 | } else if (full()) { 18 | throw QueueFullException(); 19 | } 20 | std::queue::push(item); 21 | isEmpty.notify_all(); 22 | } 23 | 24 | template 25 | bool BlockingQueue::full(){ 26 | return std::queue::size() >= maxSize; 27 | } 28 | 29 | template 30 | T* BlockingQueue::pop() { 31 | std::unique_lock lck(queueMutex); 32 | while (run && std::queue::empty()) { 33 | isEmpty.wait(lck); 34 | } 35 | if (!run) return nullptr; 36 | T* value = std::queue::front(); 37 | std::queue::pop(); 38 | isFull.notify_all(); 39 | return value; 40 | } 41 | 42 | template 43 | BlockingQueue::~BlockingQueue() { 44 | run = false; 45 | isEmpty.notify_all(); 46 | isFull.notify_all(); 47 | } 48 | 49 | template class BlockingQueue; 50 | template class BlockingQueue; -------------------------------------------------------------------------------- /src/modules/ambe3k/blockingqueue.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | class QueueException: public std::runtime_error { 9 | public: 10 | explicit QueueException(const char* msg): runtime_error(msg) {} 11 | }; 12 | 13 | class QueueFullException: public QueueException { 14 | public: 15 | QueueFullException(): QueueException("queue full") {} 16 | }; 17 | 18 | template 19 | class BlockingQueue: public std::queue { 20 | public: 21 | explicit BlockingQueue(int size); 22 | ~BlockingQueue(); 23 | void push(T* item, bool block = true); 24 | bool full(); 25 | T* pop(); 26 | 27 | private: 28 | int maxSize; 29 | bool run = true; 30 | std::mutex queueMutex; 31 | std::condition_variable isFull; 32 | std::condition_variable isEmpty; 33 | }; -------------------------------------------------------------------------------- /src/modules/ambe3k/channel.cpp: -------------------------------------------------------------------------------- 1 | #include "channel.hpp" 2 | 3 | #include 4 | 5 | using namespace Ambe3K; 6 | using namespace Ambe3K::Protocol; 7 | 8 | Channel::Channel(Device* device, unsigned char index) { 9 | this->device = device; 10 | this->index = index; 11 | } 12 | 13 | Channel::~Channel() { 14 | release(); 15 | } 16 | 17 | unsigned char Channel::getFramingBits() { 18 | switch (getCodecIndex()) { 19 | case 33: 20 | return 72; 21 | case 34: 22 | return 49; 23 | case 59: 24 | return 144; 25 | } 26 | short* cwds = getRateP(); 27 | if (cwds != nullptr) { 28 | short dstar[] = {0x0130, 0x0763, 0x4000, 0x0000, 0x0000, 0x0048}; 29 | if (std::memcmp(cwds, &dstar, sizeof(short) * 6) == 0) { 30 | return 72; 31 | } 32 | short ysf_vw[] = {0x0558, 0x086b, 0x1030, 0x0000, 0x0000, 0x0190}; 33 | if (std::memcmp(cwds, &ysf_vw, sizeof(short) & 6) == 0) { 34 | return 144; 35 | } 36 | } 37 | return 0; 38 | } 39 | 40 | void Channel::decode(char* input, size_t size) { 41 | device->writePacket(new ChannelPacket(index, input, size * 8)); 42 | } 43 | 44 | void Channel::encode(char* input, size_t size) { 45 | device->writePacket(new SpeechPacket(index, input, size / 2)); 46 | } 47 | 48 | void Channel::receive(SpeechPacket* packet) { 49 | // TODO lock to make sure that queue doesn't go away after... 50 | if (outQueue == nullptr) { 51 | delete packet; 52 | std::cerr << "received packet while channel is inactive. recent shutdown?\n"; 53 | return; 54 | } 55 | try { 56 | outQueue->push(packet, false); 57 | } catch (QueueFullException&) { 58 | std::cerr << "channel queue full. shutting down queue...\n"; 59 | delete packet; 60 | delete outQueue; 61 | outQueue = nullptr; 62 | } 63 | } 64 | 65 | void Channel::receive(ChannelPacket* packet) { 66 | // TODO lock to make sure that queue doesn't go away after... 67 | if (outQueue == nullptr) { 68 | delete packet; 69 | std::cerr << "received packet while channel is inactive. recent shutdown?\n"; 70 | return; 71 | } 72 | try { 73 | outQueue->push(packet, false); 74 | } catch (QueueFullException&) { 75 | std::cerr << "channel queue full. shutting down queue...\n"; 76 | delete packet; 77 | delete outQueue; 78 | outQueue = nullptr; 79 | } 80 | } 81 | 82 | size_t Channel::read(char* output) { 83 | if (outQueue == nullptr) { 84 | std::cerr << "queue gone while reading! abort!\n"; 85 | return 0; 86 | } 87 | 88 | Packet* packet = outQueue->pop(); 89 | if (packet == nullptr) { 90 | return 0; 91 | } 92 | 93 | // TODO: this loses the typing. callers of read() will not know if the response is channel or speech data. 94 | 95 | auto speech = dynamic_cast(packet); 96 | if (speech != nullptr) { 97 | size_t size = speech->getSpeechData((short*) output); 98 | delete speech; 99 | return size; 100 | } 101 | 102 | auto channel = dynamic_cast(packet); 103 | if (channel != nullptr) { 104 | size_t size = channel->getChannelData(output); 105 | delete channel; 106 | return size; 107 | } 108 | 109 | std::cerr << "dropping one unexpected packet from channel queue\n"; 110 | delete packet; 111 | return 0; 112 | } 113 | 114 | unsigned char Channel::getIndex() { 115 | return index; 116 | } 117 | 118 | bool Channel::isBusy() { 119 | return busy; 120 | } 121 | 122 | void Channel::reserve() { 123 | busy = true; 124 | outQueue = new BlockingQueue(10); 125 | } 126 | 127 | void Channel::release() { 128 | if (outQueue != nullptr) { 129 | delete outQueue; 130 | outQueue=nullptr; 131 | } 132 | busy = false; 133 | } 134 | 135 | void Channel::setup(unsigned char codecIndex, unsigned char direction) { 136 | this->codecIndex = codecIndex; 137 | if (ratep != nullptr) free(ratep); 138 | ratep = nullptr; 139 | device->writePacket(new SetupRequest(index, codecIndex, direction)); 140 | } 141 | 142 | void Channel::setup(short* cwds, unsigned char direction) { 143 | codecIndex = 0; 144 | if (ratep != nullptr && ratep != cwds) free(ratep); 145 | ratep = cwds; 146 | device->writePacket(new SetupRequest(index, cwds, direction)); 147 | } 148 | 149 | unsigned char Channel::getCodecIndex() { 150 | return codecIndex; 151 | } 152 | 153 | short* Channel::getRateP() { 154 | return ratep; 155 | } -------------------------------------------------------------------------------- /src/modules/ambe3k/channel.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "ambe3kdevice.hpp" 4 | #include "blockingqueue.hpp" 5 | #include "protocol.hpp" 6 | 7 | namespace Ambe3K { 8 | 9 | // forward declaration since those two classes are interdependent 10 | class Device; 11 | 12 | class Channel { 13 | public: 14 | Channel(Device* device, unsigned char index); 15 | ~Channel(); 16 | void encode(char* input, size_t size); 17 | void decode(char* input, size_t size); 18 | void receive(Ambe3K::Protocol::SpeechPacket* speech); 19 | void receive(Ambe3K::Protocol::ChannelPacket* channel); 20 | size_t read(char* output); 21 | unsigned char getIndex(); 22 | bool isBusy(); 23 | void reserve(); 24 | void release(); 25 | void setup(unsigned char codecIndex, unsigned char direction); 26 | void setup(short* cwds, unsigned char direction); 27 | unsigned char getCodecIndex(); 28 | short* getRateP(); 29 | unsigned char getFramingBits(); 30 | private: 31 | bool busy = false; 32 | Device* device; 33 | unsigned char index; 34 | unsigned char codecIndex = 0; 35 | short* ratep = nullptr; 36 | BlockingQueue* outQueue = nullptr; 37 | }; 38 | 39 | } -------------------------------------------------------------------------------- /src/modules/ambe3k/protocol.cpp: -------------------------------------------------------------------------------- 1 | #include "protocol.hpp" 2 | #include 3 | #include 4 | 5 | using namespace Ambe3K::Protocol; 6 | 7 | Field::Field(char *data): data(data) {} 8 | 9 | ChecksumField::ChecksumField(char *data): Field(data) { 10 | data[0] = AMBE3K_PARITY_BYTE; 11 | } 12 | 13 | size_t ChecksumField::getLength() { 14 | return 2; 15 | } 16 | 17 | void ChecksumField::setChecksum(char checksum) { 18 | data[1] = checksum; 19 | } 20 | 21 | bool ChecksumField::isCorrect(char checksum) { 22 | return data[1] == checksum; 23 | } 24 | 25 | ReadyField::ReadyField(char *data): Field(data) { 26 | data[0] = AMBE3K_CONTROL_READY; 27 | } 28 | 29 | size_t ReadyField::getLength() { 30 | return 1; 31 | } 32 | 33 | ResetField::ResetField(char *data): Field(data) { 34 | data[0] = AMBE3K_CONTROL_RESET; 35 | } 36 | 37 | size_t ResetField::getLength() { 38 | return 1; 39 | } 40 | 41 | ProdIdRequestField::ProdIdRequestField(char *data): Field(data) { 42 | data[0] = AMBE3K_CONTROL_PRODID; 43 | } 44 | 45 | size_t ProdIdRequestField::getLength() { 46 | return 1; 47 | } 48 | 49 | ProdIdResponseField::ProdIdResponseField(char *data): 50 | Field(data), 51 | // this is scary. we're relying on a \0 in data to stop us from going beyond its end... 52 | productId(data + 1) 53 | {} 54 | 55 | size_t ProdIdResponseField::getLength() { 56 | return productId.length() + 2; 57 | } 58 | 59 | std::string ProdIdResponseField::getProductId() { 60 | return productId; 61 | } 62 | 63 | VersionStringRequestField::VersionStringRequestField(char *data): Field(data) { 64 | data[0] = AMBE3K_CONTROL_VERSTRING; 65 | } 66 | 67 | size_t VersionStringRequestField::getLength() { 68 | return 1; 69 | } 70 | 71 | VersionStringResponseField::VersionStringResponseField(char *data): Field(data) {} 72 | 73 | size_t VersionStringResponseField::getLength() { 74 | return 49; 75 | } 76 | 77 | std::string VersionStringResponseField::getVersionId() { 78 | return { data + 1, 48 }; 79 | } 80 | 81 | ChannelField::ChannelField(char* data): Field(data) {} 82 | 83 | ChannelField::ChannelField(char *data, unsigned char channel): ChannelField(data) { 84 | assert(channel <= 3); 85 | data[0] = 0x40 + channel; 86 | } 87 | 88 | size_t ChannelField::getLength() { 89 | return 1; 90 | } 91 | 92 | unsigned char ChannelField::getChannel() { 93 | return data[0] - 0x40; 94 | } 95 | 96 | ChannelResponseField::ChannelResponseField(char *data): Field(data) { 97 | assert(data[1] == 0); 98 | } 99 | 100 | size_t ChannelResponseField::getLength() { 101 | return 2; 102 | } 103 | 104 | unsigned char ChannelResponseField::getChannel() { 105 | return data[0] - 0x40; 106 | } 107 | 108 | RateTRequestField::RateTRequestField(char *data, unsigned char index): Field(data) { 109 | data[0] = AMBE3K_CONTROL_RATET; 110 | data[1] = index; 111 | } 112 | 113 | size_t RateTRequestField::getLength() { 114 | return 2; 115 | } 116 | 117 | RateTResponseField::RateTResponseField(char *data): Field(data) { 118 | assert(data[1] == 0); 119 | } 120 | 121 | size_t RateTResponseField::getLength() { 122 | return 2; 123 | } 124 | 125 | RatePRequestField::RatePRequestField(char *data, short *cwds): Field(data) { 126 | data[0] = AMBE3K_CONTROL_RATEP; 127 | auto output = (short*)(data + 1); 128 | for (int i = 0; i < 6; i++) { 129 | output[i] = htons(cwds[i]); 130 | } 131 | } 132 | 133 | size_t RatePRequestField::getLength() { 134 | return 13; 135 | } 136 | 137 | RatePResponseField::RatePResponseField(char *data): Field(data) { 138 | assert(data[1] == 0); 139 | } 140 | 141 | size_t RatePResponseField::getLength() { 142 | return 2; 143 | } 144 | 145 | InitRequestField::InitRequestField(char *data, unsigned char direction): Field(data) { 146 | data[0] = AMBE3K_CONTROL_INIT; 147 | data[1] = direction; 148 | } 149 | 150 | size_t InitRequestField::getLength() { 151 | return 2; 152 | } 153 | 154 | InitResponseField::InitResponseField(char *data): Field(data) { 155 | assert(data[1] == 0); 156 | } 157 | 158 | size_t InitResponseField::getLength() { 159 | return 2; 160 | } 161 | 162 | ChanDField::ChanDField(char *data, char *channelData, unsigned char bits): Field(data), bits(bits) { 163 | data[0] = AMBE3K_CHANNEL_CHAND; 164 | data[1] = bits; 165 | memcpy(data + 2, channelData, (bits + 7) / 8); 166 | } 167 | 168 | ChanDField::ChanDField(char *data): Field(data), bits((unsigned char) data[1]) {} 169 | 170 | size_t ChanDField::getLength() { 171 | return 2 + (bits + 7) / 8; 172 | } 173 | 174 | size_t ChanDField::getChannelData(char *output) { 175 | size_t size = (bits + 7) / 8; 176 | memcpy(output, data + 2, size); 177 | return size; 178 | } 179 | 180 | SpeechDField::SpeechDField(char *data, char *speechData, unsigned char samples): Field(data), samples(samples) { 181 | data[0] = AMBE3K_SPEECH_SPEECHD; 182 | data[1] = samples; 183 | // TODO: this probably needs htons() 184 | memcpy(data + 2, speechData, samples * 2); 185 | } 186 | 187 | SpeechDField::SpeechDField(char *data): Field(data), samples((unsigned char) data[1]) {} 188 | 189 | size_t SpeechDField::getLength() { 190 | return 2 + samples * 2; 191 | } 192 | 193 | size_t SpeechDField::getSpeechData(short *output) { 194 | auto src = (short*) (data + 2); 195 | for (int i = 0; i < samples; i++) { 196 | output[i] = ntohs(src[i]); 197 | } 198 | return samples * 2; 199 | } 200 | 201 | Packet::Packet(char* newData, size_t size): data(newData), dataSize(size) { 202 | // minimum size without parity 203 | assert(size >= 4); 204 | if (size > 4) { 205 | payload = data + 4; 206 | } else { 207 | // packet has no data 208 | payload = nullptr; 209 | } 210 | } 211 | 212 | Packet::Packet(size_t size): Packet((char*) calloc(size, 1), size) { 213 | // start byte is constant 214 | data[0] = AMBE3K_START_BYTE; 215 | 216 | // need to fix endianness 217 | *(short*)(data + 1) = htons(dataSize - 4); 218 | } 219 | 220 | Packet::Packet(size_t size, char type): Packet(size) { 221 | data[3] = type; 222 | } 223 | 224 | Packet::~Packet() { 225 | free(data); 226 | delete checksum; 227 | } 228 | 229 | Packet* Packet::parse(char* data, size_t size) { 230 | Packet* p; 231 | char type = data[3]; 232 | if (type == AMBE3K_TYPE_CONTROL) { 233 | p = new ControlPacket(data, size); 234 | } else if (type == AMBE3K_TYPE_AUDIO) { 235 | p = new SpeechPacket(data, size); 236 | } else if (type == AMBE3K_TYPE_AMBE) { 237 | p = new ChannelPacket(data, size); 238 | } else { 239 | std::cerr << "Warning: unexpected packet (type = " << type << ")\n"; 240 | return nullptr; 241 | } 242 | p->scanFields(); 243 | if (!p->isChecksumValid()) { 244 | std::cerr << "Warning: packet had wrong checksum\n"; 245 | delete p; 246 | return nullptr; 247 | } 248 | return p; 249 | } 250 | 251 | void Packet::scanFields() { 252 | char* current = payload; 253 | size_t remaining = dataSize - 4; 254 | while (remaining > 0) { 255 | Field* f = buildField(current); 256 | if (f == nullptr) { 257 | std::cerr << "Error: packet contains an unexpected field (opcode = " << + *current << "; dataSize = " << dataSize << "; remaining = " << remaining << ")\n"; 258 | // that's a break because we can't continue 259 | break; 260 | } 261 | size_t l = f->getLength(); 262 | if (l > remaining) { 263 | std::cerr << "Error: field length exceeds packet size (we need " << l << "; we got " << remaining << ")\n"; 264 | delete f; 265 | break; 266 | } 267 | current += l; 268 | remaining -= l; 269 | if (dynamic_cast(f) && remaining > 0) { 270 | std::cerr << "Warning: checksum field is not at packet end as expected (remaining: " << remaining << ")\n"; 271 | } 272 | storeField(f); 273 | } 274 | } 275 | 276 | Field* Packet::buildField(char *current) { 277 | switch (*current) { 278 | case AMBE3K_PARITY_BYTE: 279 | return new ChecksumField(current); 280 | case 0x40: 281 | case 0x41: 282 | case 0x42: 283 | return new ChannelField(current); 284 | } 285 | return nullptr; 286 | } 287 | 288 | void Packet::storeField(Field* field) { 289 | if (auto cf = dynamic_cast(field)) { 290 | checksum = cf; 291 | } else if (auto cr = dynamic_cast(field)) { 292 | channel = cr; 293 | } else { 294 | std::cerr << "Error: unexpected field in storeField()\n"; 295 | } 296 | } 297 | 298 | char Packet::getChecksum() { 299 | char parity = 0; 300 | for (int i = 0; i < dataSize - 2; i++) { 301 | parity ^= data[i + 1]; 302 | } 303 | return parity; 304 | } 305 | 306 | void Packet::updateChecksum() { 307 | if (checksum == nullptr) return; 308 | checksum->setChecksum(getChecksum()); 309 | } 310 | 311 | bool Packet::hasChecksum() { 312 | return checksum != nullptr; 313 | } 314 | 315 | bool Packet::isChecksumValid() { 316 | // packets without checksum shall pass without checking 317 | if (!hasChecksum()) return true; 318 | return checksum->isCorrect(getChecksum()); 319 | } 320 | 321 | bool Packet::hasChannel() { 322 | return channel != nullptr; 323 | } 324 | 325 | unsigned char Packet::getChannel() { 326 | if (hasChannel()) return channel->getChannel(); 327 | return 0; 328 | } 329 | 330 | void Packet::writeTo(int fd) { 331 | updateChecksum(); 332 | write(fd, data, dataSize); 333 | } 334 | 335 | Packet* Packet::receiveFrom(int fd) { 336 | char* buf = (char*) malloc(1024); 337 | short remain = 4; 338 | for (int i = 0; i < 10; i++) { 339 | remain -= read(fd, buf + (4 - remain), remain); 340 | if (remain == 0) { 341 | break; 342 | } 343 | } 344 | 345 | if (remain > 0 || buf[0] != AMBE3K_START_BYTE) { 346 | return nullptr; 347 | } 348 | 349 | short payloadLength = ntohs(*((short*) &buf[1])); 350 | remain = payloadLength; 351 | buf = (char*) realloc(buf, remain + 4); 352 | 353 | for (int i = 0; i < 10; i++) { 354 | remain -= read(fd, buf + (4 + payloadLength - remain), remain); 355 | if (remain == 0) { 356 | break; 357 | } 358 | } 359 | 360 | return parse(buf, payloadLength + 4); 361 | } 362 | 363 | size_t Packet::getPayloadLength() { 364 | return dataSize - 4 - hasChecksum() * 2; 365 | } 366 | 367 | ControlPacket::ControlPacket(size_t bytes): Packet(bytes, AMBE3K_TYPE_CONTROL) {} 368 | 369 | ControlPacket::~ControlPacket() { 370 | delete ready; 371 | delete prodid; 372 | delete version; 373 | delete channelResponse; 374 | delete ratePResponse; 375 | delete rateTResponse; 376 | delete initResponse; 377 | } 378 | 379 | Field* ControlPacket::buildField(char *current) { 380 | switch (*current) { 381 | case AMBE3K_CONTROL_READY: 382 | return new ReadyField(current); 383 | case AMBE3K_CONTROL_PRODID: 384 | return new ProdIdResponseField(current); 385 | case AMBE3K_CONTROL_VERSTRING: 386 | return new VersionStringResponseField(current); 387 | case AMBE3K_CONTROL_RATET: 388 | return new RateTResponseField(current); 389 | case AMBE3K_CONTROL_RATEP: 390 | return new RatePResponseField(current); 391 | case AMBE3K_CONTROL_INIT: 392 | return new InitResponseField(current); 393 | case 0x40: 394 | case 0x41: 395 | case 0x42: 396 | return new ChannelResponseField(current); 397 | default: 398 | return Packet::buildField(current); 399 | } 400 | } 401 | 402 | void ControlPacket::storeField(Field* field) { 403 | if (auto rf = dynamic_cast(field)) { 404 | ready = rf; 405 | } else if (auto pr = dynamic_cast(field)) { 406 | prodid = pr; 407 | } else if (auto vr = dynamic_cast(field)) { 408 | version = vr; 409 | } else if (auto rpr = dynamic_cast(field)) { 410 | ratePResponse = rpr; 411 | } else if (auto rtr = dynamic_cast(field)) { 412 | rateTResponse = rtr; 413 | } else if (auto ir = dynamic_cast(field)) { 414 | initResponse = ir; 415 | } else if (auto cr = dynamic_cast(field)) { 416 | channelResponse = cr; 417 | } else { 418 | Packet::storeField(field); 419 | } 420 | } 421 | 422 | bool ControlPacket::hasReadyField() { 423 | return ready != nullptr; 424 | } 425 | 426 | bool ControlPacket::hasProductId() { 427 | return prodid != nullptr; 428 | } 429 | 430 | std::string ControlPacket::getProductId() { 431 | return prodid->getProductId(); 432 | } 433 | 434 | bool ControlPacket::hasVersionString() { 435 | return version != nullptr; 436 | } 437 | 438 | std::string ControlPacket::getVersionString() { 439 | return version->getVersionId(); 440 | } 441 | 442 | bool ControlPacket::hasRatePResponse() { 443 | return ratePResponse != nullptr; 444 | } 445 | 446 | bool ControlPacket::hasRateTResponse() { 447 | return rateTResponse != nullptr; 448 | } 449 | 450 | bool ControlPacket::hasInitResponse() { 451 | return initResponse != nullptr; 452 | } 453 | 454 | bool ControlPacket::hasChannel() { 455 | return channelResponse != nullptr; 456 | } 457 | 458 | unsigned char ControlPacket::getChannel() { 459 | return channelResponse->getChannel(); 460 | } 461 | 462 | ResetPacket::ResetPacket(): ControlPacket(7) { 463 | size_t offset = 0; 464 | reset = new ResetField(payload + offset); 465 | offset += reset->getLength(); 466 | checksum = new ChecksumField(payload + offset); 467 | } 468 | 469 | ResetPacket::~ResetPacket() { 470 | delete reset; 471 | } 472 | 473 | ProdIdRequest::ProdIdRequest(): ControlPacket(7) { 474 | size_t offset = 0; 475 | request = new ProdIdRequestField(payload + offset); 476 | offset += request->getLength(); 477 | checksum = new ChecksumField(payload + offset); 478 | } 479 | 480 | ProdIdRequest::~ProdIdRequest() { 481 | delete request; 482 | } 483 | 484 | VersionStringRequest::VersionStringRequest(): ControlPacket(7) { 485 | size_t offset = 0; 486 | request = new VersionStringRequestField(payload + offset); 487 | offset += request->getLength(); 488 | checksum = new ChecksumField(payload + offset); 489 | } 490 | 491 | VersionStringRequest::~VersionStringRequest() { 492 | delete request; 493 | } 494 | 495 | SetupRequest::SetupRequest(unsigned char channel, unsigned char index, unsigned char direction): ControlPacket(11) { 496 | assert(channel <= 3); 497 | size_t offset = 0; 498 | this->channel = new ChannelField(payload + offset, channel); 499 | offset += this->channel->getLength(); 500 | request = new RateTRequestField(payload + offset, index); 501 | offset += request->getLength(); 502 | init = new InitRequestField(payload + offset, direction); 503 | offset += init->getLength(); 504 | checksum = new ChecksumField(payload + offset); 505 | } 506 | 507 | SetupRequest::SetupRequest(unsigned char channel, short* cwds, unsigned char direction): ControlPacket(22) { 508 | assert(channel <= 3); 509 | size_t offset = 0; 510 | this->channel = new ChannelField(payload + offset, channel); 511 | offset += this->channel->getLength(); 512 | request = new RatePRequestField(payload + offset, cwds); 513 | offset += request->getLength(); 514 | init = new InitRequestField(payload + offset, direction); 515 | offset += init->getLength(); 516 | checksum = new ChecksumField(payload + offset); 517 | } 518 | 519 | SetupRequest::~SetupRequest() { 520 | delete channel; 521 | delete request; 522 | delete init; 523 | } 524 | 525 | ChannelPacket::ChannelPacket(unsigned char channel, char* channelData, unsigned char bits): 526 | Packet((int) ((bits + 7) / 8) + 9, AMBE3K_TYPE_AMBE) 527 | { 528 | size_t offset = 0; 529 | this->channel = new ChannelField(payload + offset, channel); 530 | offset += this->channel->getLength(); 531 | chanD = new ChanDField(payload + offset, channelData, bits); 532 | offset += chanD->getLength(); 533 | checksum = new ChecksumField(payload + offset); 534 | } 535 | 536 | ChannelPacket::~ChannelPacket() { 537 | delete channel; 538 | delete chanD; 539 | } 540 | 541 | Field* ChannelPacket::buildField(char *current) { 542 | switch (*current) { 543 | case AMBE3K_CHANNEL_CHAND: 544 | return new ChanDField(current); 545 | default: 546 | return Packet::buildField(current); 547 | } 548 | } 549 | 550 | void ChannelPacket::storeField(Field* field) { 551 | if (auto cd = dynamic_cast(field)) { 552 | chanD = cd; 553 | } else { 554 | Packet::storeField(field); 555 | } 556 | } 557 | 558 | SpeechPacket::SpeechPacket(unsigned char channel, char* speechData, unsigned char samples): 559 | Packet(samples * 2 + 9, AMBE3K_TYPE_AUDIO) 560 | { 561 | size_t offset = 0; 562 | this->channel = new ChannelField(payload + offset, channel); 563 | offset += this->channel->getLength(); 564 | speechD = new SpeechDField(payload + offset, speechData, samples); 565 | offset += speechD->getLength(); 566 | checksum = new ChecksumField(payload + offset); 567 | } 568 | 569 | SpeechPacket::~SpeechPacket() { 570 | delete channel; 571 | delete speechD; 572 | } 573 | 574 | Field *SpeechPacket::buildField(char* current) { 575 | switch (*current) { 576 | case AMBE3K_SPEECH_SPEECHD: 577 | return new SpeechDField(current); 578 | default: 579 | return Packet::buildField(current); 580 | } 581 | } 582 | 583 | void SpeechPacket::storeField(Field *field) { 584 | if (auto sd = dynamic_cast(field)) { 585 | speechD = sd; 586 | } else { 587 | Packet::storeField(field); 588 | } 589 | } 590 | 591 | size_t SpeechPacket::getSpeechData(short* output) { 592 | if (speechD == nullptr) return 0; 593 | return speechD->getSpeechData(output); 594 | } 595 | 596 | size_t ChannelPacket::getChannelData(char* output) { 597 | if (chanD == nullptr) return 0; 598 | return chanD->getChannelData(output); 599 | } -------------------------------------------------------------------------------- /src/modules/ambe3k/protocol.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include // htons 9 | 10 | #define AMBE3K_START_BYTE 0x61 11 | #define AMBE3K_PARITY_BYTE 0x2f 12 | 13 | #define AMBE3K_TYPE_CONTROL 0x00 14 | #define AMBE3K_TYPE_AMBE 0x01 15 | #define AMBE3K_TYPE_AUDIO 0x02 16 | 17 | #define AMBE3K_CONTROL_RATEP 0x0A 18 | #define AMBE3K_CONTROL_RATET 0x09 19 | #define AMBE3K_CONTROL_INIT 0x0B 20 | #define AMBE3K_CONTROL_PRODID 0x30 21 | #define AMBE3K_CONTROL_VERSTRING 0x31 22 | #define AMBE3K_CONTROL_RESET 0x33 23 | #define AMBE3K_CONTROL_READY 0x39 24 | #define AMBE3K_CONTROL_CHANFMT 0x15 25 | #define AMBE3K_CONTROL_SPCHFMT 0x16 26 | #define AMBE3K_CONTROL_COMPAND 0x32 27 | 28 | #define AMBE3K_DIRECTION_ENCODE 0x01 29 | #define AMBE3K_DIRECTION_DECODE 0x02 30 | 31 | #define AMBE3K_CHANNEL_CHAND 0x01 32 | #define AMBE3K_SPEECH_SPEECHD 0x00 33 | 34 | #define AMBE3K_FIFO_MAX_PENDING 3 35 | 36 | namespace Ambe3K::Protocol { 37 | 38 | class Field { 39 | public: 40 | explicit Field(char* data); 41 | virtual ~Field() = default; 42 | virtual size_t getLength() = 0; 43 | protected: 44 | char* data; 45 | }; 46 | 47 | class ChecksumField: public Field { 48 | public: 49 | explicit ChecksumField(char* data); 50 | size_t getLength() override; 51 | void setChecksum(char checksum); 52 | bool isCorrect(char checksum); 53 | }; 54 | 55 | class ResetField: public Field { 56 | public: 57 | explicit ResetField(char* data); 58 | size_t getLength() override; 59 | }; 60 | 61 | class ReadyField: public Field { 62 | public: 63 | explicit ReadyField(char* data); 64 | size_t getLength() override; 65 | }; 66 | 67 | class ProdIdRequestField: public Field { 68 | public: 69 | explicit ProdIdRequestField(char* data); 70 | size_t getLength() override; 71 | }; 72 | 73 | class ProdIdResponseField: public Field { 74 | public: 75 | explicit ProdIdResponseField(char* data); 76 | size_t getLength() override; 77 | std::string getProductId(); 78 | private: 79 | std::string productId; 80 | }; 81 | 82 | class VersionStringRequestField: public Field { 83 | public: 84 | explicit VersionStringRequestField(char* data); 85 | size_t getLength() override; 86 | }; 87 | 88 | class VersionStringResponseField: public Field { 89 | public: 90 | explicit VersionStringResponseField(char* data); 91 | size_t getLength() override; 92 | std::string getVersionId(); 93 | }; 94 | 95 | class ChannelField: public Field { 96 | public: 97 | ChannelField(char* data, unsigned char channel); 98 | explicit ChannelField(char* data); 99 | size_t getLength() override; 100 | unsigned char getChannel(); 101 | }; 102 | 103 | // in most cases, ChannelField is sufficient for both sending and receiving 104 | // in the ControlPacket however, there's an extra 0 following the channel byte, so we have an extra implementation for that case 105 | class ChannelResponseField: public Field { 106 | public: 107 | explicit ChannelResponseField(char* data); 108 | size_t getLength() override; 109 | unsigned char getChannel(); 110 | }; 111 | 112 | class RateTRequestField: public Field { 113 | public: 114 | explicit RateTRequestField(char* data, unsigned char index); 115 | size_t getLength() override; 116 | }; 117 | 118 | class RateTResponseField: public Field { 119 | public: 120 | explicit RateTResponseField(char* data); 121 | size_t getLength() override; 122 | }; 123 | 124 | class RatePRequestField: public Field { 125 | public: 126 | explicit RatePRequestField(char* data, short* cwds); 127 | size_t getLength() override; 128 | }; 129 | 130 | class RatePResponseField: public Field { 131 | public: 132 | explicit RatePResponseField(char* data); 133 | size_t getLength() override; 134 | }; 135 | 136 | class InitRequestField: public Field { 137 | public: 138 | explicit InitRequestField(char* data, unsigned char direction); 139 | size_t getLength() override; 140 | }; 141 | 142 | class InitResponseField: public Field { 143 | public: 144 | explicit InitResponseField(char* data); 145 | size_t getLength() override; 146 | }; 147 | 148 | class ChanDField: public Field { 149 | public: 150 | explicit ChanDField(char* data); 151 | ChanDField(char* data, char* channelData, unsigned char bits); 152 | size_t getLength() override; 153 | size_t getChannelData(char* output); 154 | private: 155 | size_t bits; 156 | }; 157 | 158 | class SpeechDField: public Field { 159 | public: 160 | explicit SpeechDField(char* data); 161 | SpeechDField(char* data, char* speechData, unsigned char samples); 162 | size_t getLength() override; 163 | size_t getSpeechData(short* output); 164 | private: 165 | size_t samples; 166 | }; 167 | 168 | class Packet { 169 | public: 170 | static Packet* parse(char* data, size_t bytes); 171 | bool hasChecksum(); 172 | bool isChecksumValid(); 173 | 174 | void writeTo(int fd); 175 | static Packet* receiveFrom(int fd); 176 | // necessary to maintain polymorphism 177 | virtual ~Packet(); 178 | 179 | virtual bool hasChannel(); 180 | virtual unsigned char getChannel(); 181 | protected: 182 | // used when parsing incoming packets 183 | Packet(char* payload, size_t bytes); 184 | // used when constructing outgoing packets 185 | explicit Packet(size_t bytes); 186 | Packet(size_t bytes, char type); 187 | 188 | void scanFields(); 189 | virtual Field* buildField(char* current); 190 | virtual void storeField(Field* field); 191 | 192 | void updateChecksum(); 193 | size_t getPayloadLength(); 194 | 195 | char* payload; 196 | ChecksumField* checksum = nullptr; 197 | ChannelField* channel = nullptr; 198 | private: 199 | char getChecksum(); 200 | char* data; 201 | size_t dataSize; 202 | }; 203 | 204 | class ControlPacket: public Packet { 205 | public: 206 | explicit ControlPacket(size_t bytes); 207 | ControlPacket(char* payload, size_t bytes): Packet(payload, bytes) {} 208 | ~ControlPacket() override; 209 | 210 | bool hasReadyField(); 211 | bool hasProductId(); 212 | std::string getProductId(); 213 | bool hasVersionString(); 214 | std::string getVersionString(); 215 | bool hasRatePResponse(); 216 | bool hasRateTResponse(); 217 | bool hasInitResponse(); 218 | bool hasChannel() override; 219 | unsigned char getChannel() override; 220 | protected: 221 | Field* buildField(char* current) override; 222 | void storeField(Field* field) override; 223 | private: 224 | ReadyField* ready = nullptr; 225 | ProdIdResponseField* prodid = nullptr; 226 | VersionStringResponseField* version = nullptr; 227 | RateTResponseField* rateTResponse = nullptr; 228 | RatePResponseField* ratePResponse = nullptr; 229 | InitResponseField* initResponse = nullptr; 230 | ChannelResponseField* channelResponse = nullptr; 231 | }; 232 | 233 | class ResetPacket: public ControlPacket { 234 | public: 235 | ResetPacket(); 236 | ~ResetPacket() override; 237 | private: 238 | ResetField* reset; 239 | }; 240 | 241 | class ProdIdRequest: public ControlPacket { 242 | public: 243 | ProdIdRequest(); 244 | ~ProdIdRequest() override; 245 | private: 246 | ProdIdRequestField* request; 247 | }; 248 | 249 | class VersionStringRequest: public ControlPacket { 250 | public: 251 | VersionStringRequest(); 252 | ~VersionStringRequest() override; 253 | private: 254 | VersionStringRequestField* request; 255 | }; 256 | 257 | class SetupRequest: public ControlPacket{ 258 | public: 259 | SetupRequest(unsigned char channel, unsigned char index, unsigned char direction); 260 | SetupRequest(unsigned char channel, short* cwds, unsigned char direction); 261 | ~SetupRequest() override; 262 | private: 263 | Field* request; 264 | InitRequestField* init; 265 | }; 266 | 267 | class ChannelPacket: public Packet { 268 | public: 269 | ChannelPacket(char* data, size_t size): Packet(data, size) {} 270 | ChannelPacket(unsigned char channel, char* channelData, unsigned char bits); 271 | ~ChannelPacket() override; 272 | size_t getChannelData(char* output); 273 | protected: 274 | Field* buildField(char* current) override; 275 | void storeField(Field* field) override; 276 | private: 277 | ChanDField* chanD = nullptr; 278 | }; 279 | 280 | class SpeechPacket: public Packet { 281 | public: 282 | SpeechPacket(char* data, size_t size): Packet(data, size) {} 283 | SpeechPacket(unsigned char channel, char* speechData, unsigned char samples); 284 | ~SpeechPacket() override; 285 | size_t getSpeechData(short* output); 286 | protected: 287 | Field* buildField(char* current) override; 288 | void storeField(Field* field) override; 289 | private: 290 | SpeechDField* speechD = nullptr; 291 | }; 292 | 293 | 294 | } -------------------------------------------------------------------------------- /src/modules/ambe3k/queueworker.cpp: -------------------------------------------------------------------------------- 1 | #include "queueworker.hpp" 2 | #include 3 | 4 | using namespace Ambe3K; 5 | using namespace Ambe3K::Protocol; 6 | 7 | QueueWorker::QueueWorker(Device* device, int fd, BlockingQueue* queue) { 8 | this->device = device; 9 | this->queue = queue; 10 | std::thread thread = std::thread( [this, fd] { 11 | run(fd); 12 | }); 13 | thread.detach(); 14 | } 15 | 16 | QueueWorker::~QueueWorker() { 17 | dorun = false; 18 | } 19 | 20 | void QueueWorker::run(int fd) { 21 | size_t in_progress = 0; 22 | while (dorun) { 23 | while ((!queue->empty() && in_progress < AMBE3K_FIFO_MAX_PENDING) || in_progress == 0) { 24 | Packet* packet = queue->pop(); 25 | if (!dorun) return; 26 | if (packet == nullptr) { 27 | device->onQueueError("queue returned a null pointer, so assuming queue was shut down. shutting down worker\n"); 28 | dorun = false; 29 | return; 30 | } 31 | packet->writeTo(fd); 32 | delete packet; 33 | in_progress += 1; 34 | //std::cerr << " sent one packet, in_progress is now: " << in_progress << "\n"; 35 | } 36 | 37 | do { 38 | Packet* response = Packet::receiveFrom(fd); 39 | if (response == nullptr) { 40 | device->onQueueError("no response from device"); 41 | dorun = false; 42 | return; 43 | } 44 | device->receivePacket(response); 45 | in_progress -= 1; 46 | //std::cerr << " received one packet, in_progress is now: " << in_progress << "\n"; 47 | } while (in_progress > 0 && queue->empty()); 48 | } 49 | } -------------------------------------------------------------------------------- /src/modules/ambe3k/queueworker.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "ambe3kdevice.hpp" 4 | #include "protocol.hpp" 5 | 6 | namespace Ambe3K { 7 | 8 | // forward declaration since those two classes are interdependent 9 | class Device; 10 | 11 | class QueueWorker { 12 | public: 13 | QueueWorker(Device* device, int fd, BlockingQueue* queue); 14 | ~QueueWorker(); 15 | private: 16 | void run(int fd); 17 | Device* device; 18 | BlockingQueue* queue; 19 | bool dorun = true; 20 | }; 21 | 22 | } -------------------------------------------------------------------------------- /src/modules/ambe3k/udevmonitor.cpp: -------------------------------------------------------------------------------- 1 | #include "udevmonitor.hpp" 2 | #include "registry.hpp" 3 | #include "ambe3kregistry.hpp" 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace Ambe3K::Udev; 10 | 11 | Monitor::Monitor() { 12 | std::thread thread([ this ] { run(); }); 13 | thread.detach(); 14 | } 15 | 16 | void Monitor::run() { 17 | udev* udev = udev_new(); 18 | if (!udev) { 19 | std::cerr << "WARNING: could not create udev context\n"; 20 | return; 21 | } 22 | 23 | udev_monitor* monitor = udev_monitor_new_from_netlink(udev, "udev"); 24 | if (!monitor) { 25 | std::cerr << "WARNING: could not create udev monitor\n"; 26 | udev_unref(udev); 27 | return; 28 | } 29 | 30 | udev_monitor_filter_add_match_subsystem_devtype(monitor, "tty", NULL); 31 | udev_monitor_enable_receiving(monitor); 32 | 33 | int fd = udev_monitor_get_fd(monitor); 34 | fd_set fds; 35 | struct timeval tv {}; 36 | int ret; 37 | 38 | while (true) { 39 | FD_ZERO(&fds); 40 | FD_SET(fd, &fds); 41 | tv.tv_sec = 10; 42 | tv.tv_usec = 0; 43 | 44 | ret = select(fd+1, &fds, NULL, NULL, &tv); 45 | if (ret > 0 && FD_ISSET(fd, &fds)) { 46 | udev_device* dev = udev_monitor_receive_device(monitor); 47 | if (dev) { 48 | std::string action = udev_device_get_action(dev); 49 | std::string node = udev_device_get_devnode(dev); 50 | Registration* match = Registry::get()->findByNode(node); 51 | if (action == "remove") { 52 | if (match && match->device) { 53 | std::cerr << "unregistering device " << node << " due to udev remove event\n"; 54 | CodecServer::Registry::get()->unregisterDevice(match->device); 55 | match->device = nullptr; 56 | } 57 | } else if (action == "add") { 58 | if (match && !match->device) { 59 | CodecServer::Registry::get()->loadDeviceFromConfig(match->config); 60 | } 61 | } 62 | 63 | /* free dev */ 64 | udev_device_unref(dev); 65 | } 66 | } 67 | } 68 | 69 | udev_unref(udev); 70 | } -------------------------------------------------------------------------------- /src/modules/ambe3k/udevmonitor.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | namespace Ambe3K::Udev { 6 | class Monitor { 7 | public: 8 | explicit Monitor(); 9 | private: 10 | void run(); 11 | }; 12 | } -------------------------------------------------------------------------------- /src/server/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_executable(codecserver-bin codecserver.cpp server.cpp scanner.cpp clientconnection.cpp serverconfig.cpp socketserver.cpp tcpserver.cpp unixdomainsocketserver.cpp) 2 | set_target_properties(codecserver-bin PROPERTIES OUTPUT_NAME codecserver) 3 | target_compile_definitions(codecserver-bin PRIVATE 4 | MODULES_PATH="${CMAKE_INSTALL_FULL_LIBDIR}/codecserver" 5 | CONFIG="${CMAKE_INSTALL_FULL_SYSCONFDIR}/codecserver/codecserver.conf" 6 | ) 7 | target_link_libraries(codecserver-bin codecserver dl ${CMAKE_THREAD_LIBS_INIT}) 8 | install(TARGETS codecserver-bin DESTINATION ${CMAKE_INSTALL_BINDIR}) 9 | 10 | configure_file(codecserver.service.in codecserver.service @ONLY) 11 | if (CMAKE_INSTALL_PREFIX STREQUAL "/usr") 12 | set(SYSTEMD_PREFIX "/lib/systemd/system") 13 | else() 14 | set(SYSTEMD_PREFIX "${CMAKE_INSTALL_LIBDIR}/systemd/system") 15 | endif() 16 | install(FILES ${CMAKE_CURRENT_BINARY_DIR}/codecserver.service DESTINATION ${SYSTEMD_PREFIX}) -------------------------------------------------------------------------------- /src/server/clientconnection.cpp: -------------------------------------------------------------------------------- 1 | #include "clientconnection.hpp" 2 | #include "proto/handshake.pb.h" 3 | #include "proto/response.pb.h" 4 | #include "registry.hpp" 5 | #include "protocol.hpp" 6 | #include 7 | #include 8 | 9 | #define BUFFER_SIZE 65536 10 | 11 | using namespace CodecServer; 12 | using namespace CodecServer::proto; 13 | 14 | ClientConnection::ClientConnection(int sock): Connection(sock) { 15 | try { 16 | handshake(); 17 | loop(); 18 | } catch (ConnectionException& e) { 19 | std::cerr << "connection error: " << e.what() << "\n"; 20 | } 21 | delete this; 22 | } 23 | 24 | ClientConnection::~ClientConnection() { 25 | stopSession(); 26 | } 27 | 28 | void ClientConnection::handshake() { 29 | GOOGLE_PROTOBUF_VERIFY_VERSION; 30 | Handshake handshake; 31 | handshake.set_servername("codecserver"); 32 | handshake.set_serverversion(VERSION); 33 | handshake.set_protocolversion(PROTOCOL_VERSION); 34 | if (!sendMessage(&handshake)) { 35 | throw ConnectionException("sending handshake failed"); 36 | } 37 | } 38 | 39 | void ClientConnection::startSession() { 40 | if (session == nullptr) { 41 | return; 42 | } 43 | 44 | session->start(); 45 | 46 | reader = new std::thread( [this] { 47 | read(); 48 | }); 49 | } 50 | 51 | void ClientConnection::stopSession() { 52 | if (session == nullptr) { 53 | return; 54 | } 55 | 56 | session->end(); 57 | reader->join(); 58 | 59 | delete session; 60 | session = nullptr; 61 | delete reader; 62 | reader = nullptr; 63 | } 64 | 65 | void ClientConnection::loop() { 66 | while (run) { 67 | google::protobuf::Any* message = receiveMessage(); 68 | if (message == nullptr) { 69 | run = false; 70 | } else if ( 71 | checkMessageType(message) || 72 | checkMessageType(message) || 73 | checkMessageType(message) || 74 | checkMessageType(message) || 75 | checkMessageType(message) 76 | ) { 77 | // we're good 78 | } else { 79 | std::cerr << "received unexpected message type\n"; 80 | } 81 | 82 | delete message; 83 | } 84 | 85 | stopSession(); 86 | } 87 | 88 | template 89 | bool ClientConnection::checkMessageType(google::protobuf::Any* message) { 90 | if (message->Is()) { 91 | T* content = new T(); 92 | message->UnpackTo(content); 93 | processMessage(content); 94 | return true; 95 | } 96 | return false; 97 | } 98 | 99 | void ClientConnection::processMessage(ChannelData* data) { 100 | if (session == nullptr) { 101 | std::cerr << "dropping incoming channel data since we don't have a decoding session\n"; 102 | } else { 103 | std::string input = data->data(); 104 | session->decode((char*) input.c_str(), input.length()); 105 | } 106 | delete data; 107 | } 108 | 109 | void ClientConnection::processMessage(SpeechData* data) { 110 | if (session == nullptr) { 111 | std::cerr << "dropping incoming speech data since we don't have an encoding session\n"; 112 | } else { 113 | std::string input = data->data(); 114 | session->encode((char*) input.c_str(), input.length()); 115 | } 116 | delete data; 117 | } 118 | 119 | void ClientConnection::processMessage(Renegotiation* reneg) { 120 | auto response = new Response(); 121 | try { 122 | session->renegotiate(reneg->settings()); 123 | response->set_result(Response_Status_OK); 124 | FramingHint* framing = session->getFraming(); 125 | if (framing != nullptr) { 126 | response->set_allocated_framing(framing); 127 | } 128 | } catch (const std::exception&) { 129 | response->set_result(Response_Status_ERROR); 130 | } 131 | bool sent = sendMessage(response); 132 | delete response; 133 | delete reneg; 134 | if (!sent) { 135 | throw ConnectionException("sending response failed"); 136 | } 137 | } 138 | 139 | void ClientConnection::processMessage(Request* request) { 140 | std::cout << "client requests codec " << request->codec() << "\n"; 141 | 142 | // stop existing session, if any 143 | stopSession(); 144 | 145 | for (Device* device: Registry::get()->findDevices(request->codec())) { 146 | session = device->startSession(request); 147 | if (session != nullptr) break; 148 | } 149 | 150 | auto response = new Response(); 151 | 152 | if (session == nullptr) { 153 | response->set_result(Response_Status_ERROR); 154 | response->set_message("no device available"); 155 | } else { 156 | response->set_result(Response_Status_OK); 157 | FramingHint* framing = session->getFraming(); 158 | if (framing != nullptr) { 159 | response->set_allocated_framing(framing); 160 | } 161 | startSession(); 162 | } 163 | 164 | bool sent = sendMessage(response); 165 | delete response; 166 | delete request; 167 | if (!sent) { 168 | throw ConnectionException("sending response failed"); 169 | } 170 | } 171 | 172 | void ClientConnection::processMessage(Check* check) { 173 | std::cout << "check for codec: " << check->codec() << "\n"; 174 | auto response = new Response(); 175 | 176 | if (Registry::get()->findDevices(check->codec()).empty()) { 177 | response->set_result(Response_Status_ERROR); 178 | response->set_message("no device available"); 179 | } else { 180 | response->set_result(Response_Status_OK); 181 | } 182 | 183 | bool sent = sendMessage(response); 184 | delete response; 185 | delete check; 186 | if (!sent) { 187 | throw ConnectionException("sending response failed"); 188 | } 189 | } 190 | 191 | void ClientConnection::read() { 192 | size_t size; 193 | char* output = (char*) malloc(BUFFER_SIZE); 194 | while (run) { 195 | size = session->read(output); 196 | if (size == 0) { 197 | run = false; 198 | break; 199 | } 200 | // TODO: we don't know if it's actually speech data, typing is lost in Session::read() 201 | auto data = new SpeechData(); 202 | data->set_data(std::string(output, size)); 203 | if (!sendMessage(data)) { 204 | run = false; 205 | } 206 | delete data; 207 | } 208 | free(output); 209 | } -------------------------------------------------------------------------------- /src/server/clientconnection.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "connection.hpp" 4 | #include "session.hpp" 5 | #include "proto/data.pb.h" 6 | #include "proto/request.pb.h" 7 | #include "proto/check.pb.h" 8 | #include 9 | #include 10 | #include 11 | 12 | namespace CodecServer { 13 | 14 | class ClientConnection: public Connection { 15 | public: 16 | explicit ClientConnection(int sock); 17 | ~ClientConnection() override; 18 | private: 19 | void handshake(); 20 | void loop(); 21 | void read(); 22 | template bool checkMessageType(google::protobuf::Any* message); 23 | void processMessage(ChannelData* data); 24 | void processMessage(SpeechData* data); 25 | void processMessage(Renegotiation* data); 26 | void processMessage(Request* request); 27 | void processMessage(Check* check); 28 | void startSession(); 29 | void stopSession(); 30 | bool run = true; 31 | Session* session = nullptr; 32 | std::thread* reader = nullptr; 33 | }; 34 | 35 | } -------------------------------------------------------------------------------- /src/server/codecserver.cpp: -------------------------------------------------------------------------------- 1 | #include "server.hpp" 2 | 3 | int main (int argc, char** argv) { 4 | auto server = new CodecServer::Server(); 5 | int rc = server->main(argc, argv); 6 | delete server; 7 | return rc; 8 | } -------------------------------------------------------------------------------- /src/server/codecserver.service.in: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=CodecServer 3 | 4 | [Service] 5 | Type=simple 6 | User=codecserver 7 | Group=codecserver 8 | ExecStart=@CMAKE_INSTALL_FULL_BINDIR@/codecserver 9 | Restart=always 10 | 11 | [Install] 12 | WantedBy=multi-user.target 13 | -------------------------------------------------------------------------------- /src/server/scanner.cpp: -------------------------------------------------------------------------------- 1 | #include "scanner.hpp" 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace CodecServer; 7 | 8 | void Scanner::scanModules() { 9 | std::cout << "now scanning for modules...\n"; 10 | for (const std::string& lib : getLibs()) { 11 | loadLibrary(lib); 12 | } 13 | } 14 | 15 | std::vector Scanner::getSearchPaths() { 16 | std::vector searchPaths; 17 | searchPaths.push_back(MODULES_PATH); 18 | return searchPaths; 19 | } 20 | 21 | std::vector Scanner::getLibs() { 22 | std::vector libs; 23 | for (const std::string& searchPath : getSearchPaths()) { 24 | glob_t globResults; 25 | std::string pattern = searchPath + "/*.so"; 26 | int ret = glob(pattern.c_str(), 0, NULL, &globResults); 27 | if (ret == 0) { 28 | for (size_t i = 0; i < globResults.gl_pathc; i++) { 29 | libs.push_back(globResults.gl_pathv[i]); 30 | } 31 | } else if (ret == GLOB_NOMATCH) { 32 | // pass 33 | } else { 34 | std::cerr << "glob() failed with ret=" << ret << " for pattern " << pattern << "\n"; 35 | } 36 | 37 | globfree(&globResults); 38 | } 39 | return libs; 40 | } 41 | 42 | void Scanner::loadLibrary(const std::string& path) { 43 | void* handle = dlopen(path.c_str(), RTLD_LAZY); 44 | if (handle == NULL) { 45 | std::cerr << "dlopen() failed: " << dlerror() << "\n"; 46 | } 47 | } -------------------------------------------------------------------------------- /src/server/scanner.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | namespace CodecServer { 7 | 8 | class Scanner { 9 | public: 10 | void scanModules(); 11 | private: 12 | std::vector getSearchPaths(); 13 | std::vector getLibs(); 14 | void loadLibrary(const std::string& path); 15 | }; 16 | 17 | } -------------------------------------------------------------------------------- /src/server/server.cpp: -------------------------------------------------------------------------------- 1 | #include "server.hpp" 2 | #include "scanner.hpp" 3 | #include "serverconfig.hpp" 4 | #include "registry.hpp" 5 | #include "unixdomainsocketserver.hpp" 6 | #include "tcpserver.hpp" 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | using namespace CodecServer; 13 | 14 | std::function signal_callback_wrapper; 15 | void signal_callback_function(int value) { 16 | signal_callback_wrapper(value); 17 | } 18 | 19 | int Server::main(int argc, char** argv) { 20 | if (!parseOptions(argc, argv)) { 21 | return 0; 22 | } 23 | 24 | std::cout << "Hello, I'm the codecserver.\n"; 25 | 26 | signal_callback_wrapper = std::bind(&Server::handle_signal, this, std::placeholders::_1); 27 | std::signal(SIGINT, &signal_callback_function); 28 | std::signal(SIGTERM, &signal_callback_function); 29 | std::signal(SIGQUIT, &signal_callback_function); 30 | std::signal(SIGPIPE, &signal_callback_function); 31 | 32 | ServerConfig config(configFile); 33 | 34 | Scanner scanner; 35 | scanner.scanModules(); 36 | 37 | for (const std::string& driver: config.getDrivers()) { 38 | std::map args = config.getDriverConfig(driver); 39 | Registry::get()->configureDriver(driver, args); 40 | } 41 | 42 | std::cout << "loading devices from configuration...\n"; 43 | for (const std::string& device: config.getDevices()) { 44 | std::map args = config.getDeviceConfig(device); 45 | Registry::get()->loadDeviceFromConfig(args); 46 | } 47 | 48 | std::cout << "auto-detecing devices...\n"; 49 | Registry::get()->autoDetectDevices(); 50 | std::cout << "device scan complete.\n"; 51 | 52 | for (const std::string& type: config.getServers()) { 53 | std::map args = config.getServerConfig(type); 54 | SocketServer* server = nullptr; 55 | if (type == "unixdomainsockets") { 56 | server = new UnixDomainSocketServer(); 57 | } else if (type == "tcp4") { 58 | server = new Tcp4Server(); 59 | } else if (type == "tcp" or type == "tcp6") { 60 | server = new Tcp6Server(); 61 | } 62 | 63 | if (server == nullptr) { 64 | std::cerr << "unknown server type: \"" << type << "\"\n"; 65 | continue; 66 | } 67 | 68 | server->readConfig(args); 69 | try { 70 | server->setupSocket(); 71 | servers.push_back(server); 72 | } catch (const std::runtime_error& ex) { 73 | std::cerr << "server type \"" << type << "\" setup failed:\n"; 74 | std::cerr << " " << ex.what() << "\n"; 75 | } 76 | } 77 | 78 | if (servers.empty()) { 79 | std::cerr << "ERROR: No usable servers; cannot accept client connections.\n"; 80 | return 1; 81 | } 82 | 83 | for (SocketServer* server: servers) { 84 | server->start(); 85 | } 86 | 87 | for (SocketServer* server: servers) { 88 | server->join(); 89 | delete server; 90 | } 91 | 92 | return 0; 93 | } 94 | 95 | bool Server::parseOptions(int argc, char** argv) { 96 | int c; 97 | static struct option long_options[] = { 98 | {"version", no_argument, NULL, 'v'}, 99 | {"help", no_argument, NULL, 'h'}, 100 | {"config", required_argument, NULL, 'c'}, 101 | { NULL, 0, NULL, 0 } 102 | }; 103 | while ((c = getopt_long(argc, argv, "vhc:", long_options, NULL)) != -1 ) { 104 | switch (c) { 105 | case 'v': 106 | printVersion(); 107 | return false; 108 | case 'h': 109 | printUsage(); 110 | return false; 111 | case 'c': 112 | configFile = std::string(optarg); 113 | break; 114 | } 115 | } 116 | 117 | return true; 118 | } 119 | 120 | void Server::printUsage() { 121 | std::cerr << 122 | "codecserver version " << VERSION << "\n\n" << 123 | "Usage: codecserver [options]\n\n" << 124 | "Available options:\n" << 125 | " -h, --help show this message\n" << 126 | " -v, --version print version and exit\n" << 127 | " -c, --config path to config file (default: \"" << CONFIG << "\")\n"; 128 | } 129 | 130 | void Server::printVersion() { 131 | std::cout << "codecserver version " << VERSION << "\n"; 132 | } 133 | 134 | void Server::handle_signal(int signal) { 135 | if (signal == SIGPIPE) { 136 | return; 137 | } 138 | std::cerr << "received signal: " << signal << "\n"; 139 | stop(); 140 | } 141 | 142 | void Server::stop() { 143 | for (SocketServer* server: servers) { 144 | server->stop(); 145 | } 146 | } -------------------------------------------------------------------------------- /src/server/server.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include "socketserver.hpp" 6 | 7 | namespace CodecServer { 8 | 9 | class Server { 10 | public: 11 | int main(int argc, char** argv); 12 | void handle_signal(int signal); 13 | private: 14 | bool parseOptions(int argc, char** argv); 15 | void printUsage(); 16 | void printVersion(); 17 | void stop(); 18 | std::string configFile = CONFIG; 19 | std::vector servers; 20 | }; 21 | 22 | } -------------------------------------------------------------------------------- /src/server/serverconfig.cpp: -------------------------------------------------------------------------------- 1 | #include "serverconfig.hpp" 2 | 3 | using namespace CodecServer; 4 | 5 | std::vector ServerConfig::getDevices() { 6 | return getSections("device"); 7 | } 8 | 9 | std::map ServerConfig::getDeviceConfig(const std::string& key) { 10 | return getSection("device:" + key); 11 | } 12 | 13 | std::vector ServerConfig::getDrivers() { 14 | return getSections("driver"); 15 | } 16 | 17 | std::map ServerConfig::getDriverConfig(const std::string& key) { 18 | return getSection("driver:" + key); 19 | } -------------------------------------------------------------------------------- /src/server/serverconfig.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "config.hpp" 4 | #include 5 | #include 6 | #include 7 | 8 | namespace CodecServer { 9 | 10 | class ServerConfig: public Config { 11 | public: 12 | explicit ServerConfig(std::string path): Config(path) {}; 13 | std::vector getDevices(); 14 | std::map getDeviceConfig(const std::string& key); 15 | std::vector getDrivers(); 16 | std::map getDriverConfig(const std::string& key); 17 | }; 18 | 19 | } -------------------------------------------------------------------------------- /src/server/socketserver.cpp: -------------------------------------------------------------------------------- 1 | #include "socketserver.hpp" 2 | #include "clientconnection.hpp" 3 | #include 4 | #include 5 | 6 | using namespace CodecServer; 7 | 8 | SocketServer::~SocketServer() { 9 | stop(); 10 | } 11 | 12 | void SocketServer::setupSocket() { 13 | sock = getSocket(); 14 | if (sock == -1) { 15 | throw std::runtime_error("socket error: " + std::string(strerror(errno))); 16 | } 17 | 18 | int reuse = 1; 19 | if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)) == -1) { 20 | throw std::runtime_error("error setting socket options: " + std::string(strerror(errno))); 21 | } 22 | 23 | bind(); 24 | 25 | if (listen(sock, 1) == -1) { 26 | throw std::runtime_error("listen error: " + std::string(strerror(errno))); 27 | } 28 | } 29 | 30 | void SocketServer::start() { 31 | thread = std::thread([this] { 32 | run(); 33 | }); 34 | } 35 | 36 | void SocketServer::run() { 37 | while (dorun) { 38 | int client_sock = accept(sock, NULL, NULL); 39 | if (client_sock > 0) { 40 | std::thread t([client_sock] { 41 | new ClientConnection(client_sock); 42 | }); 43 | t.detach(); 44 | } 45 | } 46 | } 47 | 48 | void SocketServer::stop() { 49 | dorun = false; 50 | // unlocks the call to accept(); 51 | shutdown(sock, SHUT_RDWR); 52 | ::close(sock); 53 | } 54 | 55 | void SocketServer::join() { 56 | thread.join(); 57 | } -------------------------------------------------------------------------------- /src/server/socketserver.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | namespace CodecServer { 9 | 10 | class SocketServer { 11 | public: 12 | virtual ~SocketServer(); 13 | virtual void readConfig(const std::map& config) {}; 14 | virtual int getSocket() = 0; 15 | virtual void bind() = 0; 16 | virtual void setupSocket(); 17 | virtual void start(); 18 | void stop(); 19 | virtual void run(); 20 | virtual void join(); 21 | protected: 22 | int sock = -1; 23 | bool dorun = true; 24 | private: 25 | std::thread thread; 26 | }; 27 | 28 | } -------------------------------------------------------------------------------- /src/server/tcpserver.cpp: -------------------------------------------------------------------------------- 1 | #include "tcpserver.hpp" 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace CodecServer; 8 | 9 | void TcpServer::readConfig(const std::map& config) { 10 | if (config.find("port") != config.end()) { 11 | port = stoul(config.at("port")); 12 | } 13 | 14 | if (config.find("bind") != config.end()) { 15 | bindAddr = config.at("bind"); 16 | } 17 | } 18 | 19 | void Tcp4Server::bind() { 20 | sockaddr_in addr {}; 21 | memset(&addr, 0, sizeof(addr)); 22 | addr.sin_family = AF_INET; 23 | addr.sin_port = htons(port); 24 | addr.sin_addr.s_addr = inet_addr(bindAddr.c_str()); 25 | if (::bind(sock, (sockaddr*) &addr, sizeof(addr)) != 0) { 26 | throw std::runtime_error("bind error: " + std::string(strerror(errno))); 27 | } 28 | } 29 | 30 | void Tcp6Server::bind() { 31 | sockaddr_in6 addr {}; 32 | memset(&addr, 0, sizeof(addr)); 33 | addr.sin6_family = AF_INET6; 34 | addr.sin6_port = htons(port); 35 | inet_pton(AF_INET6, bindAddr.c_str(), &addr.sin6_addr); 36 | if (::bind(sock, (sockaddr*) &addr, sizeof(addr)) != 0) { 37 | throw std::runtime_error("bind error: " + std::string(strerror(errno))); 38 | } 39 | } 40 | 41 | int Tcp4Server::getSocket() { 42 | return socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 43 | } 44 | 45 | int Tcp6Server::getSocket() { 46 | return socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP); 47 | } 48 | -------------------------------------------------------------------------------- /src/server/tcpserver.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "socketserver.hpp" 4 | #include 5 | 6 | namespace CodecServer { 7 | 8 | class TcpServer: public SocketServer { 9 | public: 10 | TcpServer(): SocketServer() {} 11 | void readConfig(const std::map& config) override; 12 | protected: 13 | std::string bindAddr; 14 | unsigned short port = 1073; 15 | }; 16 | 17 | class Tcp4Server: public TcpServer { 18 | public: 19 | Tcp4Server(): TcpServer() { 20 | bindAddr = "0.0.0.0"; 21 | } 22 | void bind() override; 23 | int getSocket() override; 24 | }; 25 | 26 | class Tcp6Server: public TcpServer { 27 | public: 28 | Tcp6Server(): TcpServer() { 29 | bindAddr = "::"; 30 | } 31 | void bind() override; 32 | int getSocket() override; 33 | }; 34 | 35 | } -------------------------------------------------------------------------------- /src/server/unixdomainsocketserver.cpp: -------------------------------------------------------------------------------- 1 | #include "unixdomainsocketserver.hpp" 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace CodecServer; 8 | 9 | void UnixDomainSocketServer::readConfig(const std::map& config) { 10 | if (config.find("socket") != config.end()) { 11 | socket_path = config.at("socket"); 12 | } 13 | } 14 | 15 | void UnixDomainSocketServer::clearSocket() { 16 | struct stat sb {}; 17 | if (lstat(socket_path.c_str(), &sb) == -1) { 18 | // if the file doesn't exist, we don't need to clear it. everything's fine. 19 | if (errno == ENOENT) { 20 | return; 21 | } 22 | throw std::runtime_error("could not query socket status: " + std::string(strerror(errno))); 23 | } 24 | 25 | if ((sb.st_mode & S_IFMT) != S_IFSOCK) { 26 | throw std::runtime_error("file \"" + socket_path + "\" exists but is not a socket"); 27 | } 28 | 29 | if (unlink(socket_path.c_str()) == -1) { 30 | throw std::runtime_error("failed to clear existing socket: " + std::string(strerror(errno))); 31 | } 32 | } 33 | 34 | void UnixDomainSocketServer::bind() { 35 | clearSocket(); 36 | 37 | sockaddr_un addr {}; 38 | memset(&addr, 0, sizeof(addr)); 39 | addr.sun_family = AF_UNIX; 40 | strncpy(addr.sun_path, socket_path.c_str(), socket_path.length()); 41 | if (::bind(sock, (sockaddr*) &addr, sizeof(addr)) != 0) { 42 | throw std::runtime_error("bind error: " + std::string(strerror(errno))); 43 | } 44 | 45 | // change permissions so that others can use the socket, too 46 | if (chmod(socket_path.c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == -1) { 47 | std::cerr << "error setting socket permissions: " << strerror(errno) << "\n"; 48 | } 49 | } 50 | 51 | int UnixDomainSocketServer::getSocket() { 52 | return socket(AF_UNIX, SOCK_STREAM, 0); 53 | } 54 | 55 | void UnixDomainSocketServer::run() { 56 | SocketServer::run(); 57 | unlink(socket_path.c_str()); 58 | } -------------------------------------------------------------------------------- /src/server/unixdomainsocketserver.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "socketserver.hpp" 4 | #include 5 | 6 | namespace CodecServer { 7 | 8 | class UnixDomainSocketServer: public SocketServer { 9 | public: 10 | UnixDomainSocketServer(): SocketServer() {} 11 | void readConfig(const std::map& config) override; 12 | void clearSocket(); 13 | int getSocket() override; 14 | void bind() override; 15 | void run() override; 16 | private: 17 | std::string socket_path = "/tmp/codecserver.sock"; 18 | }; 19 | 20 | } -------------------------------------------------------------------------------- /systemd/codecserver.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=CodecServer 3 | 4 | [Service] 5 | Type=simple 6 | User=codecserver 7 | Group=codecserver 8 | ExecStart=/usr/bin/codecserver 9 | Restart=always 10 | 11 | [Install] 12 | WantedBy=multi-user.target 13 | --------------------------------------------------------------------------------