├── .gitignore ├── LICENSE ├── README.md ├── dist.old └── webVoiceSDK-linto.min.js ├── dist └── webVoiceSDK-linto.min.js ├── hotwords ├── linto │ ├── group1-shard1of1.bin │ └── model.json └── slinfox │ ├── group1-shard1of1.bin │ └── model.json ├── package.json ├── src ├── vendor │ └── rnnoise-wasm │ │ ├── .gitmodules │ │ ├── Dockerfile │ │ ├── LICENSE │ │ ├── README.md │ │ ├── build.sh │ │ ├── dist │ │ ├── index.js │ │ └── rnnoise.wasm │ │ └── package.json ├── webvoicesdk.js └── webvoicesdk │ ├── nodes │ ├── downsampler.js │ ├── error.js │ ├── features.js │ ├── hotword.js │ ├── mic.js │ ├── node.js │ ├── recorder.js │ ├── speechpreemphasis.js │ └── vad.js │ ├── rnnoise │ ├── index.js │ └── loader.js │ └── workers │ ├── downsampler.blob.js │ ├── features.blob.js │ ├── hotword.blob.js │ └── speechpreemphasis.blob.js └── tests ├── static-html ├── index.html └── index.js └── with-bundler ├── index.html └── index.js /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | **/dev-build 3 | **/node_modules 4 | **/.cache 5 | package-lock.json -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WebVoice SDK 2 | 3 | WebVoice SDK is a JavaScript library that provides lightweights and fairly well optimized buildings block for always-listening voice-enabled applications right in the browser. This library is the main technology behind LinTO's Web Client as it deals with everything related to user's voice input. 4 | 5 | ## Functionalities 6 | - Hardware Microphone Handler : hook to hardware, record, playback, get file from buffer as wav... very handy 7 | - Downsampler : re-inject acquired audio at any given samplerate / frame size 8 | - Speech Preemphaser : Prepare acquired audio for machine learning tasks 9 | - Voice activity detection : Detect when someone's speaking (even at very low signal-to-noise ratio) 10 | - Features extraction : Pure JavaScript MFCC (Mel-Frequency Cepstral Coefficients) implementation 11 | - wake word / hot word / trigger word : Immediatly trigger tasks whenever an associated chosen word has been pronounced 12 | 13 | ### Online demo 14 | 15 | You can find an online demo of the library on this static webpage : [https://webvoicesdk.netlify.app/](https://webvoicesdk.netlify.app/) 16 | 17 | It showcases the entire pipeline : __microphone -> voice-activity-detection -> downsampling -> speech-preemphasis -> features-extraction -> wake-word-inference__ 18 | 19 | _**Note**_ : To start the tool, click on the start button, accept browser's access to the default audio input. The Voice Activity Detection "led" will blink as someone's speaking. Something magic will happen if someone says _Linto_. (Something like "LeanToh" for english speakers as the model was trained with our french data-set) 20 | 21 | 22 | _**Note**_ : You can select the model you want to use. The library comes prepacked with two wake word models (one model for _LinTO_ and a triple headed model that bounces on _LinTO, Snips_ or _Firefox_) 23 | 24 | ## Highlights 25 | - Complete multithreading JavaScript implementation using Workers for real-time processing on any machine 26 | - WebAssembly optimisations whenever possible 27 | - State of the art Recurent Neural Network that uses WebAssembly portable runtime for voice activity detection. This is modern and efficient alternative to the popular [Hark voice activity detection tool](https://www.npmjs.com/package/hark) 28 | - Supports single inline script that can get deployed in any webpage without mandatory bundlers 29 | - Built library embbeds everything (wasm files, tensorflow.js models for wake words, workers...) into a single static javascript file 30 | - The wake word Engine relies on Tensorflow JS and WebAssembly portable runtime to infers towards single or multiple wake-words model with lightweight and ultra-effecient performances. 31 | - Portable machine-learning models : Use the same wake word models on embedded devices, mobile phones, desktop computers, web pages. See : [LinTO Hotword Model Generator](https://github.com/linto-ai/linto-desktoptools-hmg) and [Create your custom wake-word](https://doc.linto.ai/#/client/custom_hotword) 32 | - Full offline speech recognition in browser, no server behind, all the magic happens in your webpage itself 33 | 34 | ## Usage 35 | 36 | Further documentation and information is in progress. For the moment, You can still build and test the library by yourself 37 | ``` 38 | npm run test 39 | ``` 40 | 41 | Or import it in your browser : 42 | 43 | ``` 44 | 45 | ``` 46 | 47 | ## Copyright notice 48 | 49 | This library includes modified bits from : 50 | - [Meyda](https://github.com/meyda/meyda) MIT Licence 51 | - [FFTjs](https://github.com/nevosegal/fftjs) MIT Licence 52 | - [node-dct](https://github.com/vail-systems/node-dct) MIT Licence 53 | - [Jitsi](https://github.com/jitsi/jitsi-meet) Apache License 2.0 -------------------------------------------------------------------------------- /hotwords/linto/group1-shard1of1.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/linto-ai/WebVoiceSDK/4808636bd00904966532940193f486eff28b8dbb/hotwords/linto/group1-shard1of1.bin -------------------------------------------------------------------------------- /hotwords/linto/model.json: -------------------------------------------------------------------------------- 1 | { 2 | "words": ["linto"], 3 | "format": "layers-model", 4 | "generatedBy": "keras v2.2.4-tf", 5 | "convertedBy": "TensorFlow.js Converter v2.0.1.post1", 6 | "modelTopology": { 7 | "keras_version": "2.2.4-tf", 8 | "backend": "tensorflow", 9 | "model_config": { 10 | "class_name": "Sequential", 11 | "config": { 12 | "name": "sequential_16", 13 | "layers": [ 14 | { 15 | "class_name": "GRU", 16 | "config": { 17 | "name": "input", 18 | "trainable": true, 19 | "batch_input_shape": [ 20 | null, 21 | 30, 22 | 13 23 | ], 24 | "dtype": "float32", 25 | "return_sequences": false, 26 | "return_state": false, 27 | "go_backwards": false, 28 | "stateful": false, 29 | "unroll": false, 30 | "time_major": false, 31 | "units": 60, 32 | "activation": "linear", 33 | "recurrent_activation": "sigmoid", 34 | "use_bias": true, 35 | "kernel_initializer": { 36 | "class_name": "GlorotUniform", 37 | "config": { 38 | "seed": null 39 | } 40 | }, 41 | "recurrent_initializer": { 42 | "class_name": "Orthogonal", 43 | "config": { 44 | "gain": 1.0, 45 | "seed": null 46 | } 47 | }, 48 | "bias_initializer": { 49 | "class_name": "Zeros", 50 | "config": {} 51 | }, 52 | "kernel_regularizer": null, 53 | "recurrent_regularizer": null, 54 | "bias_regularizer": null, 55 | "activity_regularizer": null, 56 | "kernel_constraint": null, 57 | "recurrent_constraint": null, 58 | "bias_constraint": null, 59 | "dropout": 0.0, 60 | "recurrent_dropout": 0.0, 61 | "implementation": 2, 62 | "reset_after": false 63 | } 64 | }, 65 | { 66 | "class_name": "Dense", 67 | "config": { 68 | "name": "dense", 69 | "trainable": true, 70 | "dtype": "float32", 71 | "units": 20, 72 | "activation": "relu", 73 | "use_bias": true, 74 | "kernel_initializer": { 75 | "class_name": "GlorotUniform", 76 | "config": { 77 | "seed": null 78 | } 79 | }, 80 | "bias_initializer": { 81 | "class_name": "Zeros", 82 | "config": {} 83 | }, 84 | "kernel_regularizer": null, 85 | "bias_regularizer": null, 86 | "activity_regularizer": null, 87 | "kernel_constraint": null, 88 | "bias_constraint": null 89 | } 90 | }, 91 | { 92 | "class_name": "Dense", 93 | "config": { 94 | "name": "output", 95 | "trainable": true, 96 | "dtype": "float32", 97 | "units": 1, 98 | "activation": "sigmoid", 99 | "use_bias": true, 100 | "kernel_initializer": { 101 | "class_name": "GlorotUniform", 102 | "config": { 103 | "seed": null 104 | } 105 | }, 106 | "bias_initializer": { 107 | "class_name": "Zeros", 108 | "config": {} 109 | }, 110 | "kernel_regularizer": null, 111 | "bias_regularizer": null, 112 | "activity_regularizer": null, 113 | "kernel_constraint": null, 114 | "bias_constraint": null 115 | } 116 | } 117 | ] 118 | } 119 | }, 120 | "training_config": { 121 | "loss": "mean_squared_error", 122 | "metrics": [ 123 | "accuracy" 124 | ], 125 | "weighted_metrics": null, 126 | "sample_weight_mode": null, 127 | "loss_weights": null, 128 | "optimizer_config": { 129 | "class_name": "RMSprop", 130 | "config": { 131 | "name": "RMSprop", 132 | "learning_rate": 0.0010000000474974513, 133 | "decay": 0.0, 134 | "rho": 0.8999999761581421, 135 | "momentum": 0.0, 136 | "epsilon": 1e-07, 137 | "centered": false 138 | } 139 | } 140 | } 141 | }, 142 | "weightsManifest": [ 143 | { 144 | "paths": [ 145 | "group1-shard1of1.bin" 146 | ], 147 | "weights": [ 148 | { 149 | "name": "dense/kernel", 150 | "shape": [ 151 | 60, 152 | 20 153 | ], 154 | "dtype": "float32" 155 | }, 156 | { 157 | "name": "dense/bias", 158 | "shape": [ 159 | 20 160 | ], 161 | "dtype": "float32" 162 | }, 163 | { 164 | "name": "input/kernel", 165 | "shape": [ 166 | 13, 167 | 180 168 | ], 169 | "dtype": "float32" 170 | }, 171 | { 172 | "name": "input/recurrent_kernel", 173 | "shape": [ 174 | 60, 175 | 180 176 | ], 177 | "dtype": "float32" 178 | }, 179 | { 180 | "name": "input/bias", 181 | "shape": [ 182 | 180 183 | ], 184 | "dtype": "float32" 185 | }, 186 | { 187 | "name": "output/kernel", 188 | "shape": [ 189 | 20, 190 | 1 191 | ], 192 | "dtype": "float32" 193 | }, 194 | { 195 | "name": "output/bias", 196 | "shape": [ 197 | 1 198 | ], 199 | "dtype": "float32" 200 | } 201 | ] 202 | } 203 | ] 204 | } -------------------------------------------------------------------------------- /hotwords/slinfox/group1-shard1of1.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/linto-ai/WebVoiceSDK/4808636bd00904966532940193f486eff28b8dbb/hotwords/slinfox/group1-shard1of1.bin -------------------------------------------------------------------------------- /hotwords/slinfox/model.json: -------------------------------------------------------------------------------- 1 | { 2 | "words":["linto","firefox","snips"], 3 | "format": "layers-model", 4 | "generatedBy": "keras v2.2.4-tf", 5 | "convertedBy": "TensorFlow.js Converter v2.0.1.post1", 6 | "modelTopology": { 7 | "keras_version": "2.2.4-tf", 8 | "backend": "tensorflow", 9 | "model_config": { 10 | "class_name": "Sequential", 11 | "config": { 12 | "name": "sequential", 13 | "layers": [{ 14 | "class_name": "GRU", 15 | "config": { 16 | "name": "input", 17 | "trainable": true, 18 | "batch_input_shape": [null, 30, 13], 19 | "dtype": "float32", 20 | "return_sequences": false, 21 | "return_state": false, 22 | "go_backwards": false, 23 | "stateful": false, 24 | "unroll": false, 25 | "time_major": false, 26 | "units": 30, 27 | "activation": "linear", 28 | "recurrent_activation": "sigmoid", 29 | "use_bias": true, 30 | "kernel_initializer": { 31 | "class_name": "GlorotUniform", 32 | "config": { 33 | "seed": null 34 | } 35 | }, 36 | "recurrent_initializer": { 37 | "class_name": "Orthogonal", 38 | "config": { 39 | "gain": 1.0, 40 | "seed": null 41 | } 42 | }, 43 | "bias_initializer": { 44 | "class_name": "Zeros", 45 | "config": {} 46 | }, 47 | "kernel_regularizer": null, 48 | "recurrent_regularizer": null, 49 | "bias_regularizer": null, 50 | "activity_regularizer": null, 51 | "kernel_constraint": null, 52 | "recurrent_constraint": null, 53 | "bias_constraint": null, 54 | "dropout": 0.0, 55 | "recurrent_dropout": 0.0, 56 | "implementation": 2, 57 | "reset_after": false 58 | } 59 | }, { 60 | "class_name": "Dense", 61 | "config": { 62 | "name": "dense", 63 | "trainable": true, 64 | "dtype": "float32", 65 | "units": 20, 66 | "activation": "relu", 67 | "use_bias": true, 68 | "kernel_initializer": { 69 | "class_name": "GlorotUniform", 70 | "config": { 71 | "seed": null 72 | } 73 | }, 74 | "bias_initializer": { 75 | "class_name": "Zeros", 76 | "config": {} 77 | }, 78 | "kernel_regularizer": null, 79 | "bias_regularizer": null, 80 | "activity_regularizer": null, 81 | "kernel_constraint": null, 82 | "bias_constraint": null 83 | } 84 | }, { 85 | "class_name": "Dense", 86 | "config": { 87 | "name": "output", 88 | "trainable": true, 89 | "dtype": "float32", 90 | "units": 3, 91 | "activation": "sigmoid", 92 | "use_bias": true, 93 | "kernel_initializer": { 94 | "class_name": "GlorotUniform", 95 | "config": { 96 | "seed": null 97 | } 98 | }, 99 | "bias_initializer": { 100 | "class_name": "Zeros", 101 | "config": {} 102 | }, 103 | "kernel_regularizer": null, 104 | "bias_regularizer": null, 105 | "activity_regularizer": null, 106 | "kernel_constraint": null, 107 | "bias_constraint": null 108 | } 109 | }] 110 | } 111 | }, 112 | "training_config": { 113 | "loss": "mean_squared_error", 114 | "metrics": ["accuracy"], 115 | "weighted_metrics": null, 116 | "sample_weight_mode": null, 117 | "loss_weights": null, 118 | "optimizer_config": { 119 | "class_name": "RMSprop", 120 | "config": { 121 | "name": "RMSprop", 122 | "learning_rate": 0.0010000000474974513, 123 | "decay": 0.0, 124 | "rho": 0.8999999761581421, 125 | "momentum": 0.0, 126 | "epsilon": 1e-07, 127 | "centered": false 128 | } 129 | } 130 | } 131 | }, 132 | "weightsManifest": [{ 133 | "paths": ["group1-shard1of1.bin"], 134 | "weights": [{ 135 | "name": "dense/kernel", 136 | "shape": [30, 20], 137 | "dtype": "float32" 138 | }, { 139 | "name": "dense/bias", 140 | "shape": [20], 141 | "dtype": "float32" 142 | }, { 143 | "name": "input/kernel", 144 | "shape": [13, 90], 145 | "dtype": "float32" 146 | }, { 147 | "name": "input/recurrent_kernel", 148 | "shape": [30, 90], 149 | "dtype": "float32" 150 | }, { 151 | "name": "input/bias", 152 | "shape": [90], 153 | "dtype": "float32" 154 | }, { 155 | "name": "output/kernel", 156 | "shape": [20, 3], 157 | "dtype": "float32" 158 | }, { 159 | "name": "output/bias", 160 | "shape": [3], 161 | "dtype": "float32" 162 | }] 163 | }] 164 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@linto-ai/webvoicesdk", 3 | "version": "1.2.6", 4 | "description": "Building blocks for voice-enabled applications in the browser", 5 | "author": "Damien Laine - LINAGORA", 6 | "keywords": [ 7 | "speech-recognition", 8 | "wake-word-detection", 9 | "hotword", 10 | "machine-learning", 11 | "voice-commands", 12 | "voice-activity-detection", 13 | "voice-control", 14 | "record-audio", 15 | "voice-assistant", 16 | "offline-speech-recognition", 17 | "mfcc", 18 | "features-exctraction" 19 | ], 20 | "main": "src/webvoicesdk.js", 21 | "module": "src/webvoicesdk.js", 22 | "browser": "dist/webVoiceSDK-linto.min.js", 23 | "scripts": { 24 | "build": "parcel build src/webvoicesdk.js --log-level 4 --no-cache --no-source-maps --detailed-report --out-file webVoiceSDK-linto.min.js", 25 | "test": "parcel tests/with-bundler/index.html --out-dir dev-build --log-level 4 --no-cache" 26 | }, 27 | "repository": { 28 | "type": "git", 29 | "url": "git+https://github.com/linto-ai/WebVoiceSDK.git" 30 | }, 31 | "license": "AGPLV3", 32 | "bugs": { 33 | "url": "https://github.com/linto-ai/WebVoiceSDK/issues" 34 | }, 35 | "homepage": "https://github.com/linto-ai/WebVoiceSDK#readme", 36 | "devDependencies": { 37 | "@tensorflow/tfjs": "^3.21.0", 38 | "@tensorflow/tfjs-backend-cpu": "^3.21.0", 39 | "@tensorflow/tfjs-backend-wasm": "^3.21.0", 40 | "@tensorflow/tfjs-backend-webgl": "^3.21.0", 41 | "parcel-bundler": "^1.12.5", 42 | "parcel-plugin-tensorflowjs-blob": "^1.0.0", 43 | "parcel-plugin-wasm-blob": "^1.0.0", 44 | "parcel-plugin-worker-blob": "^1.0.0" 45 | }, 46 | "browserslist": [ 47 | "since 2017-06" 48 | ] 49 | } 50 | -------------------------------------------------------------------------------- /src/vendor/rnnoise-wasm/.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "rnnoise"] 2 | path = rnnoise 3 | url = https://github.com/xiph/rnnoise.git 4 | -------------------------------------------------------------------------------- /src/vendor/rnnoise-wasm/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM trzeci/emscripten:1.39.17-upstream 2 | 3 | RUN apt-get update && \ 4 | apt-get install -y libtool autotools-dev autoconf automake 5 | 6 | -------------------------------------------------------------------------------- /src/vendor/rnnoise-wasm/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | 205 | 206 | Note: 207 | 208 | This project was originally contributed to the community under the MIT license and with the following notice: 209 | 210 | The MIT License (MIT) 211 | 212 | Copyright (c) 2013 ESTOS GmbH 213 | Copyright (c) 2013 BlueJimp SARL 214 | 215 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 216 | 217 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 218 | 219 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /src/vendor/rnnoise-wasm/README.md: -------------------------------------------------------------------------------- 1 | # rnnoise-wasm 2 | 3 | [rnnoise](https://people.xiph.org/~jm/demo/rnnoise/) noise suppression library as a WASM module. 4 | 5 | This repository contains the necessary utilities to build the library using a Docker build environment with Emscripten. 6 | 7 | ## Build 8 | 9 | ### Prerequisites 10 | 11 | - node - tested version v10.16.3 12 | - npm - tested version v6.9.0 13 | - docker - tested version 19.03.1 14 | 15 | ### Building the module 16 | 17 | Building is straightforward, run: 18 | ``` 19 | npm run build 20 | ``` 21 | The repository already has a pre-compiled version under the **dist** folder, running the above command will replace it with the newly compiled binaries and glue wasm .js file respectively. 22 | 23 | In order to facilitate the build with docker the following prebuilt image is used [trzeci/emscripten/](https://hub.docker.com/r/trzeci/emscripten/) however, it is slightly altered by installing autotools components necessary for building rnnoise. 24 | 25 | In summary the build process consists of two steps: 26 | 27 | 1. `build:dockerfile` - pulls in [trzeci/emscripten/](https://hub.docker.com/r/trzeci/emscripten/) which is then altered and saved. Any suqsequent build is going to check if the images was already installed and use that, so if one wants to make changes to the Dockerfile be sure to first delete the build image from your local docker repo. 28 | 2. `build:emscripten` - mounts the repo to the docker image from step one and runs build.sh on it. The bash script contains all the steps necessary for building rnnoise as a wasm module. 29 | 30 | ## Usage 31 | 32 | Following a build two files are generated under **dist**, the actual webassembly binary `rnnoise.wasm` and the generated emscriten .js file named `index.js` which contains glue code and the necessary libc runtime javascript bindings. 33 | 34 | The repo is structured so it can be used as a npm dependency, with the entry point in dist/index.js, be mindful as using index.js 35 | automatically implies that rnnoise.wasm needs to be present as well, thus for a normal npm build system one must explicitly copy rnnoise.wasm to the project structure. 36 | 37 | -------------------------------------------------------------------------------- /src/vendor/rnnoise-wasm/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | export OPTIMIZE="-Os" 6 | export LDFLAGS=${OPTIMIZE} 7 | export CFLAGS=${OPTIMIZE} 8 | export CXXFLAGS=${OPTIMIZE} 9 | 10 | ENTRY_POINT="rnnoise.js" 11 | 12 | if [[ `uname` == "Darwin" ]]; then 13 | SO_SUFFIX="dylib" 14 | else 15 | SO_SUFFIX="so" 16 | fi 17 | 18 | echo "=============================================" 19 | echo "Compiling wasm bindings" 20 | echo "=============================================" 21 | ( 22 | cd rnnoise 23 | 24 | # Clean possible autotools clutter that might affect the configurations step 25 | git clean -f -d 26 | ./autogen.sh 27 | 28 | # For some reason setting the CFLAGS export doesn't apply optimization to all compilation steps 29 | # so we need to explicitly pass it to configure. 30 | emconfigure ./configure CFLAGS=${OPTIMIZE} --enable-static=no --disable-examples --disable-doc 31 | emmake make clean 32 | emmake make V=1 33 | 34 | # Compile librnnoise generated LLVM bytecode to wasm 35 | emcc \ 36 | ${OPTIMIZE} \ 37 | -s STRICT=1 \ 38 | -s ALLOW_MEMORY_GROWTH=1 \ 39 | -s MALLOC=emmalloc \ 40 | -s MODULARIZE=1 \ 41 | -s ENVIRONMENT="web,worker" \ 42 | -s EXPORT_ES6=1 \ 43 | -s USE_ES6_IMPORT_META=0 \ 44 | -s EXPORTED_FUNCTIONS="['_rnnoise_process_frame', '_rnnoise_init', '_rnnoise_destroy', '_rnnoise_create', '_malloc', '_free']" \ 45 | .libs/librnnoise.${SO_SUFFIX} \ 46 | -o ./$ENTRY_POINT 47 | 48 | # Create output folder 49 | rm -rf ../dist 50 | mkdir -p ../dist 51 | 52 | # Move artifacts 53 | mv $ENTRY_POINT ../dist/index.js 54 | mv rnnoise.wasm ../dist/ 55 | 56 | # Clean cluttter 57 | git clean -f -d 58 | ) 59 | echo "=============================================" 60 | echo "Compiling wasm bindings done" 61 | echo "=============================================" -------------------------------------------------------------------------------- /src/vendor/rnnoise-wasm/dist/index.js: -------------------------------------------------------------------------------- 1 | 2 | var Module = (function() { 3 | var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; 4 | 5 | return ( 6 | function(Module) { 7 | Module = Module || {}; 8 | 9 | null;var Module=typeof Module!=="undefined"?Module:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=function shell_read(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function readBinary(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function readAsync(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function xhr_onload(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime;if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(typeof WebAssembly!=="object"){err("no native wasm support detected")}var wasmMemory;var wasmTable=new WebAssembly.Table({"initial":1,"maximum":1+0,"element":"anyfunc"});var ABORT=false;var EXITSTATUS=0;var WASM_PAGE_SIZE=65536;function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var DYNAMIC_BASE=5340496,DYNAMICTOP_PTR=97456;var INITIAL_INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;if(Module["wasmMemory"]){wasmMemory=Module["wasmMemory"]}else{wasmMemory=new WebAssembly.Memory({"initial":INITIAL_INITIAL_MEMORY/WASM_PAGE_SIZE,"maximum":2147483648/WASM_PAGE_SIZE})}if(wasmMemory){buffer=wasmMemory.buffer}INITIAL_INITIAL_MEMORY=buffer.byteLength;updateGlobalBufferAndViews(buffer);HEAP32[DYNAMICTOP_PTR>>2]=DYNAMIC_BASE;function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){Module["dynCall_v"](func)}else{Module["dynCall_vi"](func,callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what+="";out(what);err(what);ABORT=true;EXITSTATUS=1;what="abort("+what+"). Build with -s ASSERTIONS=1 for more info.";throw new WebAssembly.RuntimeError(what)}function hasPrefix(str,prefix){return String.prototype.startsWith?str.startsWith(prefix):str.indexOf(prefix)===0}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return hasPrefix(filename,dataURIPrefix)}var wasmBinaryFile="rnnoise.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(){try{if(wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(wasmBinaryFile)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&typeof fetch==="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary()})}return new Promise(function(resolve,reject){resolve(getBinary())})}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiatedSource(output){receiveInstance(output["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&typeof fetch==="function"){fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiatedSource,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiatedSource)})})}else{return instantiateArrayBuffer(receiveInstantiatedSource)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync();return{}}__ATINIT__.push({func:function(){___wasm_call_ctors()}});function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function _emscripten_get_heap_size(){return HEAPU8.length}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){requestedSize=requestedSize>>>0;var oldSize=_emscripten_get_heap_size();var PAGE_MULTIPLE=65536;var maxHeapSize=2147483648;if(requestedSize>maxHeapSize){return false}var minHeapSize=16777216;for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(minHeapSize,requestedSize,overGrownHeapSize),PAGE_MULTIPLE));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var asmLibraryArg={"a":_emscripten_memcpy_big,"b":_emscripten_resize_heap,"memory":wasmMemory,"table":wasmTable};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["c"]).apply(null,arguments)};var _rnnoise_init=Module["_rnnoise_init"]=function(){return(_rnnoise_init=Module["_rnnoise_init"]=Module["asm"]["d"]).apply(null,arguments)};var _rnnoise_create=Module["_rnnoise_create"]=function(){return(_rnnoise_create=Module["_rnnoise_create"]=Module["asm"]["e"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["f"]).apply(null,arguments)};var _rnnoise_destroy=Module["_rnnoise_destroy"]=function(){return(_rnnoise_destroy=Module["_rnnoise_destroy"]=Module["asm"]["g"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["h"]).apply(null,arguments)};var _rnnoise_process_frame=Module["_rnnoise_process_frame"]=function(){return(_rnnoise_process_frame=Module["_rnnoise_process_frame"]=Module["asm"]["i"]).apply(null,arguments)};var calledRun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0)return;function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}noExitRuntime=true;run(); 10 | 11 | 12 | return Module.ready 13 | } 14 | ); 15 | })(); 16 | export default Module; -------------------------------------------------------------------------------- /src/vendor/rnnoise-wasm/dist/rnnoise.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/linto-ai/WebVoiceSDK/4808636bd00904966532940193f486eff28b8dbb/src/vendor/rnnoise-wasm/dist/rnnoise.wasm -------------------------------------------------------------------------------- /src/vendor/rnnoise-wasm/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rnnoise-wasm", 3 | "description": "Rnnoise sub-module compiled with emscripten as web assembly module", 4 | "version": "0.0.1", 5 | "repository": { 6 | "type": "git", 7 | "url": "git+https://github.com/jitsi/rnnoise-wasm.git" 8 | }, 9 | "main": "./dist/", 10 | "scripts": { 11 | "build:dockerimage": "docker image inspect -f '.' emscripten-autotools || docker build -t emscripten-autotools .", 12 | "build:emscripten": "docker run --rm -v $(pwd):/src emscripten-autotools bash -x ./build.sh", 13 | "build": "npm run build:dockerimage && npm run build:emscripten" 14 | }, 15 | "dependencies": {}, 16 | "devDependencies": {}, 17 | "licenses": [ 18 | { 19 | "type": "Apache-2.0", 20 | "url": "http://www.apache.org/licenses/LICENSE-2.0" 21 | } 22 | ] 23 | } 24 | -------------------------------------------------------------------------------- /src/webvoicesdk.js: -------------------------------------------------------------------------------- 1 | import Mic from './webvoicesdk/nodes/mic.js' 2 | import Recorder from './webvoicesdk/nodes/recorder.js' 3 | import Vad from './webvoicesdk/nodes/vad.js' 4 | import DownSampler from './webvoicesdk/nodes/downsampler.js' 5 | import SpeechPreemphaser from './webvoicesdk/nodes/speechpreemphasis.js' 6 | import FeaturesExtractor from './webvoicesdk/nodes/features.js' 7 | import Hotword from './webvoicesdk/nodes/hotword.js' 8 | 9 | const webVoiceSDK = { 10 | DownSampler, 11 | Mic, 12 | SpeechPreemphaser, 13 | Vad, 14 | FeaturesExtractor, 15 | Hotword, 16 | Recorder 17 | } 18 | 19 | window.webVoiceSDK = webVoiceSDK 20 | module.exports = webVoiceSDK -------------------------------------------------------------------------------- /src/webvoicesdk/nodes/downsampler.js: -------------------------------------------------------------------------------- 1 | import Node from '../nodes/node.js' 2 | import Worker from '../workers/downsampler.blob.js' 3 | 4 | const handler = function (nodeEvent) { 5 | this.workerRuntime.postMessage({ 6 | method: "process", 7 | audioFrame: nodeEvent.detail 8 | }) 9 | } 10 | 11 | export default class DownSampler extends Node { 12 | 13 | static defaultOptions = { 14 | targetSampleRate: 16000, 15 | targetFrameSize: 512, 16 | Int16Convert: false 17 | } 18 | 19 | constructor({ 20 | targetSampleRate = 16000, 21 | targetFrameSize = 512, 22 | Int16Convert = false 23 | } = {}) { 24 | super() 25 | this.worker = Worker 26 | this.handler = handler.bind(this) 27 | this.type = "downSampler" 28 | this.event = "downSamplerFrame" //emitted 29 | this.hookableOnNodeTypes = ["mic"] 30 | this.options = { 31 | targetSampleRate, 32 | targetFrameSize, 33 | Int16Convert, 34 | sampleRate: targetSampleRate, 35 | frameSize: targetFrameSize 36 | } 37 | } 38 | 39 | async start(node) { 40 | await super.start(node) 41 | this.workerRuntime.postMessage({ 42 | method: "configure", 43 | nativeSampleRate: node.options.sampleRate, 44 | ...this.options 45 | }) 46 | } 47 | } -------------------------------------------------------------------------------- /src/webvoicesdk/nodes/error.js: -------------------------------------------------------------------------------- 1 | export default class NodeError extends Error { 2 | constructor(error) { 3 | super(error) 4 | this.name = 'WEBVOICESDK_NODE_ERROR'; 5 | this.error = error 6 | } 7 | } -------------------------------------------------------------------------------- /src/webvoicesdk/nodes/features.js: -------------------------------------------------------------------------------- 1 | import Node from '../nodes/node.js' 2 | import Worker from '../workers/features.blob.js' 3 | import NodeError from '../nodes/error.js' 4 | 5 | const handler = function (nodeEvent) { 6 | if (this.status == "non-emitting") return 7 | //accumulate audioframes until analysis window is full 8 | if (this.windowBuffer.length == this.windowLength) { 9 | this.workerRuntime.postMessage({ 10 | method: "process", 11 | audioFrame: Float32Array.from(this.windowBuffer) 12 | }) 13 | // slide by windowStride 14 | this.windowBuffer = this.windowBuffer.slice(-this.windowStride) 15 | } 16 | this.windowBuffer = [...this.windowBuffer, ...nodeEvent.detail] 17 | } 18 | 19 | 20 | export default class FeaturesExtractor extends Node { 21 | 22 | static defaultOptions = { 23 | numFilters: 20, 24 | numCoefs: 14, 25 | discardFirstBand: true 26 | } 27 | 28 | constructor({ 29 | numFilters = 20, 30 | numCoefs = 14, 31 | discardFirstBand = true 32 | } = {}) { 33 | super() 34 | this.worker = Worker 35 | this.handler = handler.bind(this) 36 | this.type = "featuresExtractor" 37 | this.event = "mfccFeatures" //emitted 38 | this.hookableOnNodeTypes = ["mic", "downSampler", "speechPreemphaser"] 39 | this.windowBuffer = new Array() 40 | this.options = { 41 | numFilters, 42 | numCoefs, 43 | discardFirstBand 44 | } 45 | } 46 | 47 | async start(node) { 48 | if (!node) throw new NodeError(`${this.type} requires a node argument to hook on`) 49 | try { 50 | this.options = { 51 | ...this.options, 52 | sampleRate: node.options.sampleRate, 53 | frameSize: node.options.frameSize 54 | } 55 | await super.start(node) 56 | this.windowStride = node.options.frameSize 57 | this.windowLength = node.options.frameSize * 2 58 | this.workerRuntime.postMessage({ 59 | method: "configure", 60 | bufferSize: this.windowLength, 61 | ...this.options 62 | }) 63 | } catch (e) { 64 | throw new NodeError(`${node.type} needs to get started before being passed to ${this.type}.start()`) 65 | } 66 | 67 | } 68 | } -------------------------------------------------------------------------------- /src/webvoicesdk/nodes/hotword.js: -------------------------------------------------------------------------------- 1 | import Node from '../nodes/node.js' 2 | import Worker from '../workers/hotword.blob.js' 3 | //uses a specific parcel bundler plugin to get the blob URL of the backend wasm file 4 | import tfWasmThreadedSimd from '../../../node_modules/@tensorflow/tfjs-backend-wasm/dist/tfjs-backend-wasm-threaded-simd.wasm' 5 | import tfWasmSimd from '../../../node_modules/@tensorflow/tfjs-backend-wasm/dist/tfjs-backend-wasm-simd.wasm' 6 | import tfWasm from '../../../node_modules/@tensorflow/tfjs-backend-wasm/dist/tfjs-backend-wasm.wasm' 7 | // import all hotword models using a specific parcel bundler plugin 8 | import models from "../../../hotwords/**/*.bin" 9 | 10 | const handler = function (mfcc) { 11 | if (this.mfccBuffer.length < this.mfccBufferSize) { 12 | this.mfccBuffer.push(mfcc.detail) 13 | } else { 14 | this.mfccBuffer.shift() 15 | this.mfccBuffer.push(mfcc.detail) 16 | if (this.vadNode && !this.vadNode.speaking) return 17 | this.workerRuntime.postMessage({ 18 | method: "process", 19 | features: this.mfccBuffer 20 | }) 21 | } 22 | } 23 | 24 | export default class HotWord extends Node { 25 | 26 | constructor() { 27 | super() 28 | this.worker = Worker 29 | this.mfccBuffer = [] // buffer to infer when filled with 30 mfcc. See handler 30 | this.handler = handler.bind(this) 31 | this.type = "hotword" 32 | this.event = "hotword" //emitted 33 | this.hookableOnNodeTypes = ["featuresExtractor"] 34 | this.availableModels = {} 35 | for (let modelName in models) { 36 | let weigthManifest = models[modelName] 37 | for (let callOnMe in weigthManifest) { 38 | let modelURL = models[modelName][callOnMe]["blobModelPath"].call() 39 | this.availableModels[modelName] = modelURL 40 | } 41 | } 42 | } 43 | 44 | //Optional VAD node to infer only if vad.speaking==true 45 | async start(node, vadNode, threshold = 0.8) { 46 | await super.start(node) 47 | if (vadNode) this.vadNode = vadNode 48 | // Loads wasm backend on tensorflowJs 49 | this.workerRuntime.postMessage({ 50 | method: "configure", 51 | threshold, 52 | wasmPaths: { 53 | tfWasm: tfWasm.forInstanciate(), 54 | tfWasmSimd: tfWasmSimd.forInstanciate(), 55 | tfWasmThreadedSimd: tfWasmThreadedSimd.forInstanciate() 56 | } 57 | }) 58 | } 59 | 60 | pause() { 61 | super.pause() 62 | this.mfccBuffer = [] // Clears already processed buffer 63 | } 64 | 65 | stop() { 66 | if (this.hookedOn) { 67 | super.stop() 68 | } 69 | } 70 | 71 | async loadModel(modelUrl) { 72 | //fetches the model manifest 73 | const manifestRequest = await fetch(modelUrl, { 74 | method: 'GET' 75 | }) 76 | const manifest = await manifestRequest.json() 77 | // Sets number of MFCC frames 78 | this.mfccBufferSize = manifest.modelTopology.model_config.config.layers[0].config.batch_input_shape[1] 79 | this.workerRuntime.postMessage({ 80 | method: "loadModel", 81 | modelUrl, 82 | words:manifest.words 83 | }) 84 | return Promise.resolve() 85 | } 86 | } -------------------------------------------------------------------------------- /src/webvoicesdk/nodes/mic.js: -------------------------------------------------------------------------------- 1 | import Node from '../nodes/node.js' 2 | import NodeError from '../nodes/error.js' 3 | 4 | export default class Mic extends Node { 5 | static defaultOptions = { 6 | frameSize: 4096, 7 | constraints: { 8 | echoCancellation: true, 9 | autoGainControl: true, 10 | noiseSuppression: true 11 | } 12 | } 13 | 14 | constructor({ 15 | frameSize = 4096, 16 | constraints = { 17 | echoCancellation: true, 18 | autoGainControl: true, 19 | noiseSuppression: true 20 | } 21 | } = {}) { 22 | super() 23 | this.hookableOnNodeTypes = [] //none, this node will connect to getUserMedia stream 24 | this.type = "mic" 25 | this.event = "micFrame" //emitted 26 | this.hookedOn = null 27 | this.options = { 28 | frameSize, 29 | constraints 30 | } 31 | } 32 | 33 | async start(deviceId = null) { 34 | if (this.hookedOn) throw new NodeError(`Microphone is already started, call stop() first`) 35 | this.stream = await navigator.mediaDevices.getUserMedia({ 36 | audio: { 37 | channelCount: 1, 38 | ...this.options.constraints, 39 | deviceId 40 | }, 41 | }) 42 | this.hookedOn = true 43 | this.audioContext = new(window.AudioContext || window.webkitAudioContext)() 44 | this.options.sampleRate = this.audioContext.sampleRate 45 | this.mediaStreamSource = this.audioContext.createMediaStreamSource(this.stream) 46 | this.micFrameGenerator = this.audioContext.createScriptProcessor(this.options.frameSize, 1, 1) 47 | if (this.status == "non-emitting" && this.hookedOn) { 48 | this.micFrameGenerator.onaudioprocess = (audioFrame) => { 49 | const micFrame = audioFrame.inputBuffer.getChannelData(0) 50 | this.dispatchEvent(new CustomEvent(this.event, { 51 | "detail": micFrame 52 | })) 53 | } 54 | this.mediaStreamSource.connect(this.micFrameGenerator) 55 | this.micFrameGenerator.connect(this.audioContext.destination) 56 | this.status = "emitting" 57 | } 58 | return Promise.resolve() 59 | } 60 | 61 | resume() { 62 | super.resume() 63 | this.mediaStreamSource.connect(this.micFrameGenerator) 64 | this.micFrameGenerator.connect(this.audioContext.destination) 65 | } 66 | 67 | 68 | pause() { 69 | super.pause() 70 | this.mediaStreamSource.disconnect() 71 | this.micFrameGenerator.disconnect() 72 | } 73 | 74 | stop() { 75 | if (this.hookedOn) { 76 | if(this.stream) { 77 | this.stream.getTracks().map((track) => { 78 | return track.readyState === 'live' && track.kind === 'audio' ? track.stop() : false 79 | }) 80 | } 81 | 82 | this.pause() 83 | delete this.mediaStreamSource 84 | delete this.micFrameGenerator 85 | 86 | if(this.audioContext) { 87 | this.audioContext.close().then(() => { 88 | delete this.stream 89 | delete this.audioContext 90 | }) 91 | } else { 92 | delete this.stream 93 | delete this.audioContext 94 | } 95 | 96 | this.hookedOn = null 97 | } 98 | } 99 | } -------------------------------------------------------------------------------- /src/webvoicesdk/nodes/node.js: -------------------------------------------------------------------------------- 1 | import NodeError from '../nodes/error.js' 2 | 3 | export default class Node extends EventTarget { 4 | constructor() { 5 | super() 6 | this.status = "non-emitting" 7 | } 8 | 9 | async start(node) { 10 | if (this.hookedOn) throw new NodeError(`node ${this.type} is already hooked on ${this.hookedOn}, call stop() first`) 11 | if (!node) throw new NodeError(`${this.type} requires a node argument to hook on`) 12 | if (node && !this.hookableOnNodeTypes.includes(node.type)) throw new NodeError(`${this.type} node cannot hook on ${node.type}`) 13 | this.startWorker() 14 | this.hookedOn = node 15 | this.resume() 16 | } 17 | 18 | startWorker() { 19 | if (this.worker) { 20 | this.workerRuntime = this.worker.init() 21 | this.workerRuntime.onmessage = (event) => { 22 | this.dispatchEvent(new CustomEvent(this.event, { 23 | "detail": event.data 24 | })) 25 | } 26 | } 27 | } 28 | 29 | stop() { 30 | this.pause() 31 | if (this.workerRuntime) { 32 | this.workerRuntime.terminate() 33 | delete this.workerRuntime 34 | } 35 | this.hookedOn = null 36 | } 37 | 38 | pause() { 39 | if (this.hookedOn && this.status == "emitting") { 40 | if (this.type != "mic") this.hookedOn.removeEventListener(this.hookedOn.event, this.handler) 41 | this.status = "non-emitting" 42 | } 43 | } 44 | 45 | resume() { 46 | // force this.handler to bind on "this" instead of default addEventListener target (this.hookedOn) 47 | if (this.hookedOn && this.status == "non-emitting") { 48 | if (this.type != "mic") this.hookedOn.addEventListener(this.hookedOn.event, this.handler) 49 | this.status = "emitting" 50 | } 51 | } 52 | 53 | 54 | } -------------------------------------------------------------------------------- /src/webvoicesdk/nodes/recorder.js: -------------------------------------------------------------------------------- 1 | import Node from '../nodes/node.js' 2 | 3 | function audioBufferToWav(buffer, opt) { 4 | opt = opt || {} 5 | var numChannels = buffer.numberOfChannels 6 | var sampleRate = buffer.sampleRate 7 | var format = opt.float32 ? 3 : 1 8 | var bitDepth = format === 3 ? 32 : 16 9 | var result 10 | if (numChannels === 2) { 11 | result = interleave(buffer.getChannelData(0), buffer.getChannelData(1)) 12 | } else { 13 | result = buffer.getChannelData(0) 14 | } 15 | return encodeWAV(result, format, sampleRate, numChannels, bitDepth) 16 | } 17 | 18 | function encodeWAV(samples, format, sampleRate, numChannels, bitDepth) { 19 | var bytesPerSample = bitDepth / 8 20 | var blockAlign = numChannels * bytesPerSample 21 | var buffer = new ArrayBuffer(44 + samples.length * bytesPerSample) 22 | var view = new DataView(buffer) 23 | /* RIFF identifier */ 24 | writeString(view, 0, 'RIFF') 25 | /* RIFF chunk length */ 26 | view.setUint32(4, 36 + samples.length * bytesPerSample, true) 27 | /* RIFF type */ 28 | writeString(view, 8, 'WAVE') 29 | /* format chunk identifier */ 30 | writeString(view, 12, 'fmt ') 31 | /* format chunk length */ 32 | view.setUint32(16, 16, true) 33 | /* sample format (raw) */ 34 | view.setUint16(20, format, true) 35 | /* channel count */ 36 | view.setUint16(22, numChannels, true) 37 | /* sample rate */ 38 | view.setUint32(24, sampleRate, true) 39 | /* byte rate (sample rate * block align) */ 40 | view.setUint32(28, sampleRate * blockAlign, true) 41 | /* block align (channel count * bytes per sample) */ 42 | view.setUint16(32, blockAlign, true) 43 | /* bits per sample */ 44 | view.setUint16(34, bitDepth, true) 45 | /* data chunk identifier */ 46 | writeString(view, 36, 'data') 47 | /* data chunk length */ 48 | view.setUint32(40, samples.length * bytesPerSample, true) 49 | if (format === 1) { // Raw PCM 50 | floatTo16BitPCM(view, 44, samples) 51 | } else { 52 | writeFloat32(view, 44, samples) 53 | } 54 | return buffer 55 | } 56 | 57 | function interleave(inputL, inputR) { 58 | var length = inputL.length + inputR.length 59 | var result = new Float32Array(length) 60 | var index = 0 61 | var inputIndex = 0 62 | while (index < length) { 63 | result[index++] = inputL[inputIndex] 64 | result[index++] = inputR[inputIndex] 65 | inputIndex++ 66 | } 67 | return result 68 | } 69 | 70 | function writeFloat32(output, offset, input) { 71 | for (var i = 0; i < input.length; i++, offset += 4) { 72 | output.setFloat32(offset, input[i], true) 73 | } 74 | } 75 | 76 | function floatTo16BitPCM(output, offset, input) { 77 | for (var i = 0; i < input.length; i++, offset += 2) { 78 | var s = Math.max(-1, Math.min(1, input[i])) 79 | output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true) 80 | } 81 | } 82 | 83 | function writeString(view, offset, string) { 84 | for (var i = 0; i < string.length; i++) { 85 | view.setUint8(offset + i, string.charCodeAt(i)) 86 | } 87 | } 88 | 89 | const handler = function(nodeEvent) { 90 | if (this.recOn) { 91 | if (this.hookedOn.type == "mic" || this.hookedOn.type == "downSampler" || this.hookedOn.type == "speechPreemphaser") { 92 | for (const sample of nodeEvent.detail) this.rawBuffer.push(sample) 93 | } 94 | if (this.hookedOn.type == "featuresExtractor") { 95 | this.features.push(nodeEvent.detail) 96 | } 97 | if (this.hookedOn.type == "hotword") { 98 | this.infers.push(nodeEvent.detail) 99 | } 100 | } 101 | } 102 | 103 | export default class recorder extends Node { 104 | constructor() { 105 | super() 106 | this.handler = handler.bind(this) 107 | this.type = "recorder" 108 | this.event = "recorder" //emitted 109 | this.recOn = false 110 | this.hookableOnNodeTypes = ["mic", "downSampler", "speechPreemphaser", "featuresExtractor", "hotword"] 111 | } 112 | 113 | async start(node) { 114 | await super.start(node) 115 | if (this.hookedOn.type == "mic" || this.hookedOn.type == "downSampler" || this.hookedOn.type == "speechPreemphaser") { 116 | this.rawBuffer = [] 117 | this.context = new(window.AudioContext || window.webkitAudioContext)() //fix for Safari 118 | } 119 | if (this.hookedOn.type == "featuresExtractor") { 120 | this.features = [] 121 | this.mfccBuffer = [] 122 | } 123 | if (this.hookedOn.type == "hotword") { 124 | this.infers = [] 125 | } 126 | } 127 | 128 | rec() { 129 | if (!this.recOn) this.recOn = true 130 | } 131 | 132 | stopRec() { 133 | if (this.recOn) this.recOn = false 134 | if (this.hookedOn.type == "mic" || this.hookedOn.type == "downSampler" || this.hookedOn.type == "speechPreemphaser") { 135 | this.audioBuffer = this.context.createBuffer(1, this.rawBuffer.length, this.hookedOn.options.sampleRate) 136 | this.audioBuffer.getChannelData(0).set(this.rawBuffer) 137 | } 138 | } 139 | 140 | cleanBuffer() { 141 | this.rawBuffer = [] 142 | } 143 | 144 | getBuffer() { 145 | return this.rawBuffer 146 | } 147 | 148 | play() { 149 | let replaySource = this.context.createBufferSource() 150 | replaySource.buffer = this.audioBuffer 151 | // Playback default 152 | replaySource.connect(this.context.destination) 153 | replaySource.start(0) 154 | } 155 | 156 | getFile() { 157 | let url 158 | if (this.hookedOn.type == "mic" || this.hookedOn.type == "downSampler" || this.hookedOn.type == "speechPreemphaser") { 159 | let wavFile = this.getWavFile() 160 | // our final blob 161 | this.blob = new Blob([wavFile], { 162 | type: 'audio/wav' 163 | }) 164 | } 165 | if (this.hookedOn.type == "featuresExtractor") { 166 | let featuresString = JSON.stringify(this.features) 167 | this.blob = new Blob([featuresString], { type: 'application/json' }) 168 | } 169 | if (this.hookedOn.type == "hotword") { 170 | let infersString = JSON.stringify(this.infers) 171 | this.blob = new Blob([infersString], { type: 'application/json' }) 172 | } 173 | url = URL.createObjectURL(this.blob) 174 | return url 175 | } 176 | getWavFile() { 177 | return audioBufferToWav(this.audioBuffer) 178 | } 179 | punchIn() { 180 | this.cleanBuffer() 181 | this.rec() 182 | } 183 | 184 | punchOut() { 185 | this.stopRec() 186 | this.cleanBuffer 187 | return this.getFile() 188 | } 189 | } -------------------------------------------------------------------------------- /src/webvoicesdk/nodes/speechpreemphasis.js: -------------------------------------------------------------------------------- 1 | import Node from '../nodes/node.js' 2 | import Worker from '../workers/speechpreemphasis.blob.js' 3 | 4 | const handler = function (nodeEvent) { 5 | this.workerRuntime.postMessage({ 6 | method: "process", 7 | audioFrame: nodeEvent.detail 8 | }) 9 | } 10 | 11 | export default class SpeechPreemphaser extends Node { 12 | constructor() { 13 | super() 14 | this.worker = Worker 15 | this.handler = handler.bind(this) 16 | this.type = "speechPreemphaser" 17 | this.event = "speechPreemphaserFrame" //emitted 18 | this.hookableOnNodeTypes = ["mic","downSampler"] 19 | } 20 | 21 | async start(node){ 22 | await super.start(node) 23 | this.options = { 24 | sampleRate: node.options.sampleRate, 25 | frameSize: node.options.frameSize 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /src/webvoicesdk/nodes/vad.js: -------------------------------------------------------------------------------- 1 | import Node from '../nodes/node.js' 2 | import { 3 | RNNOISE_SAMPLE_LENGTH, 4 | Rnnoise 5 | } from '../rnnoise/index.js' 6 | 7 | 8 | const handler = function (nodeEvent) { 9 | // Prepend the residue PCM buffer from the previous process callback 10 | const inData = nodeEvent.detail 11 | const completeInData = [...this.bufferResidue, ...inData] 12 | let i = 0 13 | for (; i + RNNOISE_SAMPLE_LENGTH < completeInData.length; i += RNNOISE_SAMPLE_LENGTH) { 14 | const pcmSample = completeInData.slice(i, i + RNNOISE_SAMPLE_LENGTH) 15 | const vadScore = this.wasmRuntime.calculateAudioFrameVAD(pcmSample) 16 | if (this.activations.length == this.options.numActivations) this.activations.shift() 17 | this.activations.push(0 + (vadScore > this.options.threshold)) 18 | let activations = this.activations.reduce((accum, val) => accum + val) 19 | // @TODO : Rework this shitty hysteresis (ashamed i am) 20 | if (vadScore >= this.options.threshold && this.redemptionTimer) { 21 | clearTimeout(this.redemptionTimer) 22 | this.redemptionTimer = false 23 | } 24 | if ((vadScore < this.options.threshold) && !this.redemptionTimer && this.speaking) { 25 | this.redemptionTimer = setTimeout(() => { 26 | if (this.wasmRuntime) { 27 | this.speaking = false 28 | this.dispatchEvent(new CustomEvent(this.event, { 29 | "detail": false 30 | })) 31 | } 32 | }, this.options.timeAfterStop) 33 | } 34 | if ((activations >= this.options.numActivations) && !this.speaking) { 35 | this.speaking = true 36 | this.dispatchEvent(new CustomEvent(this.event, { 37 | "detail": true 38 | })) 39 | } 40 | } 41 | this.bufferResidue = completeInData.slice(i, completeInData.length) 42 | } 43 | 44 | export default class Vad extends Node { 45 | static defaultOptions = { 46 | numActivations: 10, 47 | threshold: 0.85, 48 | timeAfterStop: 800 49 | } 50 | 51 | constructor({ 52 | numActivations = 10, 53 | threshold = 0.85, 54 | timeAfterStop = 800 55 | } = {}) { 56 | super() 57 | this.handler = handler.bind(this) 58 | this.type = "vad" 59 | this.event = "speakingStatus" //emitted 60 | this.hookableOnNodeTypes = ["mic", "downSampler", "speechPreemphaser"] 61 | this.options = { 62 | numActivations, 63 | threshold, 64 | timeAfterStop 65 | } 66 | } 67 | 68 | start(node) { 69 | this.wasmRuntime = new Rnnoise() 70 | this.bufferResidue = new Float32Array([]) 71 | this.redemptionTimer = false 72 | this.activations = [] 73 | this.speaking = false 74 | super.start(node) 75 | } 76 | 77 | stop() { 78 | if (this.hookedOn) { 79 | super.stop() 80 | this.wasmRuntime.destroy() 81 | delete this.wasmRuntime 82 | } 83 | } 84 | } -------------------------------------------------------------------------------- /src/webvoicesdk/rnnoise/index.js: -------------------------------------------------------------------------------- 1 | import rnnoiseloader from './loader' 2 | export const RNNOISE_SAMPLE_LENGTH = 480 3 | const RNNOISE_BUFFER_SIZE = RNNOISE_SAMPLE_LENGTH * 4 4 | 5 | // Wrapper for rnnoise WASM module 6 | export class Rnnoise { 7 | 8 | constructor() { 9 | this.destroyed = false 10 | this.init() 11 | } 12 | 13 | async init() { 14 | try { 15 | this.wasmInterface = await rnnoiseloader() // vendor (jitsi meet) script that loads wasm file 16 | this.wasmPcmInput = this.wasmInterface._malloc(RNNOISE_BUFFER_SIZE) 17 | if (!this.wasmPcmInput) throw Error('Failed to create wasm input memory buffer') 18 | this.wasmPcmOutput = this.wasmInterface._malloc(RNNOISE_BUFFER_SIZE) 19 | if (!this.wasmPcmOutput) { 20 | this.wasmInterface._free(this.wasmPcmInput) 21 | throw Error('Failed to create wasm output memory buffer') 22 | } 23 | // The HEAPF32.set function requires an index relative to a Float32 array view of the wasm memory model 24 | // which is an array of bytes. This means we have to divide it by the size of a float to get the index 25 | // relative to a Float32 Array. 26 | if (this.wasmPcmInput) { 27 | this.wasmPcmInputF32Index = this.wasmPcmInput / 4 28 | } 29 | this.context = this.wasmInterface._rnnoise_create() 30 | } catch (e) { 31 | this.releaseWasmResources() 32 | throw e 33 | } 34 | return this 35 | } 36 | 37 | releaseWasmResources() { 38 | // For VAD score purposes only allocate the buffers once and reuse them 39 | if (this.wasmPcmInput) { 40 | this.wasmInterface._free(this.wasmPcmInput) 41 | this.wasmPcmInput = null 42 | } 43 | 44 | if (this.wasmPcmOutput) { 45 | this.wasmInterface._free(this.wasmPcmOutput) 46 | this.wasmPcmOutput = null 47 | } 48 | 49 | if (this.context) { 50 | this.wasmInterface._rnnoise_destroy(this.context) 51 | this.context = null 52 | } 53 | } 54 | 55 | /** 56 | * Calculate the Voice Activity Detection for a raw Float32 PCM sample Array. 57 | * The size of the array must be of exactly 480 samples, this constraint comes from the rnnoise library. 58 | * 59 | * @param {Float32Array} pcmFrame - Array containing 32 bit PCM samples. 60 | * @returns {Float} Contains VAD score in the interval 0 - 1 i.e. 0.90 . 61 | */ 62 | calculateAudioFrameVAD(pcmFrame) { 63 | if (this.destroyed) { 64 | throw new Error('RnnoiseProcessor instance is destroyed, please create another one!') 65 | } 66 | 67 | const pcmFrameLength = pcmFrame.length; 68 | 69 | if (pcmFrameLength !== RNNOISE_SAMPLE_LENGTH) { 70 | throw new Error(`Rnnoise can only process PCM frames of 480 samples! Input sample was:${pcmFrameLength}`) 71 | } 72 | 73 | this.convertTo16BitPCM(pcmFrame) 74 | this.copyPCMSampleToWasmBuffer(pcmFrame) 75 | return this.wasmInterface._rnnoise_process_frame(this.context, this.wasmPcmOutput, this.wasmPcmInput) 76 | } 77 | 78 | /** 79 | * Convert 32 bit Float PCM samples to 16 bit Float PCM samples and store them in 32 bit Floats. 80 | * 81 | * @param {Float32Array} f32Array - Array containing 32 bit PCM samples. 82 | * @returns {void} 83 | */ 84 | convertTo16BitPCM(f32Array) { 85 | f32Array.forEach((value, index) => { 86 | f32Array[index] = value * 0x7fff; 87 | }); 88 | } 89 | 90 | 91 | /** 92 | * Copy the input PCM Audio Sample to the wasm input buffer. 93 | * 94 | * @param {Float32Array} pcmSample - Array containing 16 bit format PCM sample stored in 32 Floats . 95 | * @returns {void} 96 | */ 97 | copyPCMSampleToWasmBuffer(pcmSample) { 98 | this.wasmInterface.HEAPF32.set(pcmSample, this.wasmPcmInputF32Index); 99 | } 100 | 101 | /** 102 | * Release any resources required by the rnnoise context this needs to be called 103 | * before destroying any context that uses the processor. 104 | * 105 | * @returns {void} 106 | */ 107 | destroy() { 108 | // Attempting to release a non initialized processor, do nothing. 109 | if (this.destroyed) { 110 | return 111 | } 112 | this.releaseWasmResources() 113 | this.destroyed = true 114 | } 115 | 116 | } -------------------------------------------------------------------------------- /src/webvoicesdk/rnnoise/loader.js: -------------------------------------------------------------------------------- 1 | import * as wasm from '../../vendor/rnnoise-wasm/dist/rnnoise.wasm' 2 | // slight modification from vendor file to enable loading of wasm from blob 3 | // compare with vendor file in ../rnnoise/loader.js 4 | 5 | var Module = (function () { 6 | var _scriptDir = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : undefined; 7 | 8 | return function (Module) { 9 | Module = Module || {}; 10 | 11 | null; 12 | var Module = typeof Module !== "undefined" ? Module : {}; 13 | var readyPromiseResolve, readyPromiseReject; 14 | Module["ready"] = new Promise(function (resolve, reject) { 15 | readyPromiseResolve = resolve; 16 | readyPromiseReject = reject; 17 | }); 18 | var moduleOverrides = {}; 19 | var key; 20 | for (key in Module) { 21 | if (Module.hasOwnProperty(key)) { 22 | moduleOverrides[key] = Module[key]; 23 | } 24 | } 25 | var arguments_ = []; 26 | var thisProgram = "./this.program"; 27 | var quit_ = function (status, toThrow) { 28 | throw toThrow; 29 | }; 30 | var ENVIRONMENT_IS_WEB = false; 31 | var ENVIRONMENT_IS_WORKER = false; 32 | var ENVIRONMENT_IS_NODE = false; 33 | var ENVIRONMENT_IS_SHELL = false; 34 | ENVIRONMENT_IS_WEB = typeof window === "object"; 35 | ENVIRONMENT_IS_WORKER = typeof importScripts === "function"; 36 | ENVIRONMENT_IS_NODE = typeof process === "object" && typeof process.versions === "object" && typeof process.versions.node === "string"; 37 | ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER; 38 | var scriptDirectory = ""; 39 | function locateFile(path) { 40 | if (Module["locateFile"]) { 41 | return Module["locateFile"](path, scriptDirectory); 42 | } 43 | return scriptDirectory + path; 44 | } 45 | var read_, readAsync, readBinary, setWindowTitle; 46 | if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { 47 | if (ENVIRONMENT_IS_WORKER) { 48 | scriptDirectory = self.location.href; 49 | } else if (document.currentScript) { 50 | scriptDirectory = document.currentScript.src; 51 | } 52 | if (_scriptDir) { 53 | scriptDirectory = _scriptDir; 54 | } 55 | if (scriptDirectory.indexOf("blob:") !== 0) { 56 | scriptDirectory = scriptDirectory.substr(0, scriptDirectory.lastIndexOf("/") + 1); 57 | } else { 58 | scriptDirectory = ""; 59 | } 60 | { 61 | read_ = function shell_read(url) { 62 | var xhr = new XMLHttpRequest(); 63 | xhr.open("GET", url, false); 64 | xhr.send(null); 65 | return xhr.responseText; 66 | }; 67 | if (ENVIRONMENT_IS_WORKER) { 68 | readBinary = function readBinary(url) { 69 | var xhr = new XMLHttpRequest(); 70 | xhr.open("GET", url, false); 71 | xhr.responseType = "arraybuffer"; 72 | xhr.send(null); 73 | return new Uint8Array(xhr.response); 74 | }; 75 | } 76 | readAsync = function readAsync(url, onload, onerror) { 77 | var xhr = new XMLHttpRequest(); 78 | xhr.open("GET", url, true); 79 | xhr.responseType = "arraybuffer"; 80 | xhr.onload = function xhr_onload() { 81 | if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { 82 | onload(xhr.response); 83 | return; 84 | } 85 | onerror(); 86 | }; 87 | xhr.onerror = onerror; 88 | xhr.send(null); 89 | }; 90 | } 91 | setWindowTitle = function (title) { 92 | document.title = title; 93 | }; 94 | } else { 95 | } 96 | var out = Module["print"] || console.log.bind(console); 97 | var err = Module["printErr"] || console.warn.bind(console); 98 | for (key in moduleOverrides) { 99 | if (moduleOverrides.hasOwnProperty(key)) { 100 | Module[key] = moduleOverrides[key]; 101 | } 102 | } 103 | moduleOverrides = null; 104 | if (Module["arguments"]) arguments_ = Module["arguments"]; 105 | if (Module["thisProgram"]) thisProgram = Module["thisProgram"]; 106 | if (Module["quit"]) quit_ = Module["quit"]; 107 | var wasmBinary; 108 | if (Module["wasmBinary"]) wasmBinary = Module["wasmBinary"]; 109 | var noExitRuntime; 110 | if (Module["noExitRuntime"]) noExitRuntime = Module["noExitRuntime"]; 111 | if (typeof WebAssembly !== "object") { 112 | err("no native wasm support detected"); 113 | } 114 | var wasmMemory; 115 | var wasmTable = new WebAssembly.Table({ initial: 1, maximum: 1 + 0, element: "anyfunc" }); 116 | var ABORT = false; 117 | var EXITSTATUS = 0; 118 | var WASM_PAGE_SIZE = 65536; 119 | function alignUp(x, multiple) { 120 | if (x % multiple > 0) { 121 | x += multiple - (x % multiple); 122 | } 123 | return x; 124 | } 125 | var buffer, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64; 126 | function updateGlobalBufferAndViews(buf) { 127 | buffer = buf; 128 | Module["HEAP8"] = HEAP8 = new Int8Array(buf); 129 | Module["HEAP16"] = HEAP16 = new Int16Array(buf); 130 | Module["HEAP32"] = HEAP32 = new Int32Array(buf); 131 | Module["HEAPU8"] = HEAPU8 = new Uint8Array(buf); 132 | Module["HEAPU16"] = HEAPU16 = new Uint16Array(buf); 133 | Module["HEAPU32"] = HEAPU32 = new Uint32Array(buf); 134 | Module["HEAPF32"] = HEAPF32 = new Float32Array(buf); 135 | Module["HEAPF64"] = HEAPF64 = new Float64Array(buf); 136 | } 137 | var DYNAMIC_BASE = 5340496, 138 | DYNAMICTOP_PTR = 97456; 139 | var INITIAL_INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 16777216; 140 | if (Module["wasmMemory"]) { 141 | wasmMemory = Module["wasmMemory"]; 142 | } else { 143 | wasmMemory = new WebAssembly.Memory({ initial: INITIAL_INITIAL_MEMORY / WASM_PAGE_SIZE, maximum: 2147483648 / WASM_PAGE_SIZE }); 144 | } 145 | if (wasmMemory) { 146 | buffer = wasmMemory.buffer; 147 | } 148 | INITIAL_INITIAL_MEMORY = buffer.byteLength; 149 | updateGlobalBufferAndViews(buffer); 150 | HEAP32[DYNAMICTOP_PTR >> 2] = DYNAMIC_BASE; 151 | function callRuntimeCallbacks(callbacks) { 152 | while (callbacks.length > 0) { 153 | var callback = callbacks.shift(); 154 | if (typeof callback == "function") { 155 | callback(Module); 156 | continue; 157 | } 158 | var func = callback.func; 159 | if (typeof func === "number") { 160 | if (callback.arg === undefined) { 161 | Module["dynCall_v"](func); 162 | } else { 163 | Module["dynCall_vi"](func, callback.arg); 164 | } 165 | } else { 166 | func(callback.arg === undefined ? null : callback.arg); 167 | } 168 | } 169 | } 170 | var __ATPRERUN__ = []; 171 | var __ATINIT__ = []; 172 | var __ATMAIN__ = []; 173 | var __ATPOSTRUN__ = []; 174 | var runtimeInitialized = false; 175 | function preRun() { 176 | if (Module["preRun"]) { 177 | if (typeof Module["preRun"] == "function") Module["preRun"] = [Module["preRun"]]; 178 | while (Module["preRun"].length) { 179 | addOnPreRun(Module["preRun"].shift()); 180 | } 181 | } 182 | callRuntimeCallbacks(__ATPRERUN__); 183 | } 184 | function initRuntime() { 185 | runtimeInitialized = true; 186 | callRuntimeCallbacks(__ATINIT__); 187 | } 188 | function preMain() { 189 | callRuntimeCallbacks(__ATMAIN__); 190 | } 191 | function postRun() { 192 | if (Module["postRun"]) { 193 | if (typeof Module["postRun"] == "function") Module["postRun"] = [Module["postRun"]]; 194 | while (Module["postRun"].length) { 195 | addOnPostRun(Module["postRun"].shift()); 196 | } 197 | } 198 | callRuntimeCallbacks(__ATPOSTRUN__); 199 | } 200 | function addOnPreRun(cb) { 201 | __ATPRERUN__.unshift(cb); 202 | } 203 | function addOnPostRun(cb) { 204 | __ATPOSTRUN__.unshift(cb); 205 | } 206 | var runDependencies = 0; 207 | var runDependencyWatcher = null; 208 | var dependenciesFulfilled = null; 209 | function addRunDependency(id) { 210 | runDependencies++; 211 | if (Module["monitorRunDependencies"]) { 212 | Module["monitorRunDependencies"](runDependencies); 213 | } 214 | } 215 | function removeRunDependency(id) { 216 | runDependencies--; 217 | if (Module["monitorRunDependencies"]) { 218 | Module["monitorRunDependencies"](runDependencies); 219 | } 220 | if (runDependencies == 0) { 221 | if (runDependencyWatcher !== null) { 222 | clearInterval(runDependencyWatcher); 223 | runDependencyWatcher = null; 224 | } 225 | if (dependenciesFulfilled) { 226 | var callback = dependenciesFulfilled; 227 | dependenciesFulfilled = null; 228 | callback(); 229 | } 230 | } 231 | } 232 | Module["preloadedImages"] = {}; 233 | Module["preloadedAudios"] = {}; 234 | function abort(what) { 235 | if (Module["onAbort"]) { 236 | Module["onAbort"](what); 237 | } 238 | what += ""; 239 | out(what); 240 | err(what); 241 | ABORT = true; 242 | EXITSTATUS = 1; 243 | what = "abort(" + what + "). Build with -s ASSERTIONS=1 for more info."; 244 | throw new WebAssembly.RuntimeError(what); 245 | } 246 | function hasPrefix(str, prefix) { 247 | return String.prototype.startsWith ? str.startsWith(prefix) : str.indexOf(prefix) === 0; 248 | } 249 | var dataURIPrefix = "data:application/octet-stream;base64,"; 250 | function isDataURI(filename) { 251 | return hasPrefix(filename, dataURIPrefix); 252 | } 253 | var wasmBinaryFile = wasm.forInstanciate()//"rnnoise.wasm"; 254 | // if (!isDataURI(wasmBinaryFile)) { 255 | // wasmBinaryFile = locateFile(wasmBinaryFile); 256 | // } 257 | function getBinary() { 258 | try { 259 | if (wasmBinary) { 260 | return new Uint8Array(wasmBinary); 261 | } 262 | if (readBinary) { 263 | return readBinary(wasmBinaryFile); 264 | } else { 265 | throw "both async and sync fetching of the wasm failed"; 266 | } 267 | } catch (err) { 268 | abort(err); 269 | } 270 | } 271 | function getBinaryPromise() { 272 | if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && typeof fetch === "function") { 273 | return fetch(wasmBinaryFile, { credentials: "same-origin" }) 274 | .then(function (response) { 275 | if (!response["ok"]) { 276 | throw "failed to load wasm binary file at '" + wasmBinaryFile + "'"; 277 | } 278 | return response["arrayBuffer"](); 279 | }) 280 | .catch(function () { 281 | return getBinary(); 282 | }); 283 | } 284 | return new Promise(function (resolve, reject) { 285 | resolve(getBinary()); 286 | }); 287 | } 288 | function createWasm() { 289 | var info = { a: asmLibraryArg }; 290 | function receiveInstance(instance, module) { 291 | var exports = instance.exports; 292 | Module["asm"] = exports; 293 | removeRunDependency("wasm-instantiate"); 294 | } 295 | addRunDependency("wasm-instantiate"); 296 | function receiveInstantiatedSource(output) { 297 | receiveInstance(output["instance"]); 298 | } 299 | function instantiateArrayBuffer(receiver) { 300 | return getBinaryPromise() 301 | .then(function (binary) { 302 | console.log(binary) 303 | return WebAssembly.instantiate(binary, info); 304 | }) 305 | .then(receiver, function (reason) { 306 | err("failed to asynchronously prepare wasm: " + reason); 307 | abort(reason); 308 | }); 309 | } 310 | function instantiateAsync() { 311 | if (!wasmBinary && typeof WebAssembly.instantiateStreaming === "function" && typeof fetch === "function") { 312 | fetch(wasmBinaryFile, { credentials: "same-origin" }).then(function (response) { 313 | var result = WebAssembly.instantiateStreaming(response, info); 314 | return result.then(receiveInstantiatedSource, function (reason) { 315 | err("wasm streaming compile failed: " + reason); 316 | err("falling back to ArrayBuffer instantiation"); 317 | return instantiateArrayBuffer(receiveInstantiatedSource); 318 | }); 319 | }); 320 | } else { 321 | return instantiateArrayBuffer(receiveInstantiatedSource); 322 | } 323 | } 324 | if (Module["instantiateWasm"]) { 325 | try { 326 | var exports = Module["instantiateWasm"](info, receiveInstance); 327 | return exports; 328 | } catch (e) { 329 | err("Module.instantiateWasm callback failed with error: " + e); 330 | return false; 331 | } 332 | } 333 | instantiateAsync(); 334 | return {}; 335 | } 336 | __ATINIT__.push({ 337 | func: function () { 338 | ___wasm_call_ctors(); 339 | }, 340 | }); 341 | function _emscripten_memcpy_big(dest, src, num) { 342 | HEAPU8.copyWithin(dest, src, src + num); 343 | } 344 | function _emscripten_get_heap_size() { 345 | return HEAPU8.length; 346 | } 347 | function emscripten_realloc_buffer(size) { 348 | try { 349 | wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16); 350 | updateGlobalBufferAndViews(wasmMemory.buffer); 351 | return 1; 352 | } catch (e) {} 353 | } 354 | function _emscripten_resize_heap(requestedSize) { 355 | requestedSize = requestedSize >>> 0; 356 | var oldSize = _emscripten_get_heap_size(); 357 | var PAGE_MULTIPLE = 65536; 358 | var maxHeapSize = 2147483648; 359 | if (requestedSize > maxHeapSize) { 360 | return false; 361 | } 362 | var minHeapSize = 16777216; 363 | for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { 364 | var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); 365 | overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296); 366 | var newSize = Math.min(maxHeapSize, alignUp(Math.max(minHeapSize, requestedSize, overGrownHeapSize), PAGE_MULTIPLE)); 367 | var replacement = emscripten_realloc_buffer(newSize); 368 | if (replacement) { 369 | return true; 370 | } 371 | } 372 | return false; 373 | } 374 | var asmLibraryArg = { a: _emscripten_memcpy_big, b: _emscripten_resize_heap, memory: wasmMemory, table: wasmTable }; 375 | var asm = createWasm(); 376 | var ___wasm_call_ctors = (Module["___wasm_call_ctors"] = function () { 377 | return (___wasm_call_ctors = Module["___wasm_call_ctors"] = Module["asm"]["c"]).apply(null, arguments); 378 | }); 379 | var _rnnoise_init = (Module["_rnnoise_init"] = function () { 380 | return (_rnnoise_init = Module["_rnnoise_init"] = Module["asm"]["d"]).apply(null, arguments); 381 | }); 382 | var _rnnoise_create = (Module["_rnnoise_create"] = function () { 383 | return (_rnnoise_create = Module["_rnnoise_create"] = Module["asm"]["e"]).apply(null, arguments); 384 | }); 385 | var _malloc = (Module["_malloc"] = function () { 386 | return (_malloc = Module["_malloc"] = Module["asm"]["f"]).apply(null, arguments); 387 | }); 388 | var _rnnoise_destroy = (Module["_rnnoise_destroy"] = function () { 389 | return (_rnnoise_destroy = Module["_rnnoise_destroy"] = Module["asm"]["g"]).apply(null, arguments); 390 | }); 391 | var _free = (Module["_free"] = function () { 392 | return (_free = Module["_free"] = Module["asm"]["h"]).apply(null, arguments); 393 | }); 394 | var _rnnoise_process_frame = (Module["_rnnoise_process_frame"] = function () { 395 | return (_rnnoise_process_frame = Module["_rnnoise_process_frame"] = Module["asm"]["i"]).apply(null, arguments); 396 | }); 397 | var calledRun; 398 | dependenciesFulfilled = function runCaller() { 399 | if (!calledRun) run(); 400 | if (!calledRun) dependenciesFulfilled = runCaller; 401 | }; 402 | function run(args) { 403 | args = args || arguments_; 404 | if (runDependencies > 0) { 405 | return; 406 | } 407 | preRun(); 408 | if (runDependencies > 0) return; 409 | function doRun() { 410 | if (calledRun) return; 411 | calledRun = true; 412 | Module["calledRun"] = true; 413 | if (ABORT) return; 414 | initRuntime(); 415 | preMain(); 416 | readyPromiseResolve(Module); 417 | if (Module["onRuntimeInitialized"]) Module["onRuntimeInitialized"](); 418 | postRun(); 419 | } 420 | if (Module["setStatus"]) { 421 | Module["setStatus"]("Running..."); 422 | setTimeout(function () { 423 | setTimeout(function () { 424 | Module["setStatus"](""); 425 | }, 1); 426 | doRun(); 427 | }, 1); 428 | } else { 429 | doRun(); 430 | } 431 | } 432 | Module["run"] = run; 433 | if (Module["preInit"]) { 434 | if (typeof Module["preInit"] == "function") Module["preInit"] = [Module["preInit"]]; 435 | while (Module["preInit"].length > 0) { 436 | Module["preInit"].pop()(); 437 | } 438 | } 439 | noExitRuntime = true; 440 | run(); 441 | 442 | return Module.ready; 443 | }; 444 | })(); 445 | export default Module; 446 | -------------------------------------------------------------------------------- /src/webvoicesdk/workers/downsampler.blob.js: -------------------------------------------------------------------------------- 1 | let nativeSampleRate 2 | let inputBuffer = [] 3 | let targetSampleRate 4 | let targetFrameSize 5 | let Int16Convert 6 | 7 | onmessage = function (msg) { 8 | switch (msg.data.method) { 9 | case "configure": 10 | nativeSampleRate = msg.data.nativeSampleRate 11 | targetSampleRate = msg.data.targetSampleRate 12 | targetFrameSize = msg.data.targetFrameSize 13 | Int16Convert = msg.data.Int16Convert 14 | break 15 | case "process": 16 | process(msg.data.audioFrame) 17 | break 18 | } 19 | } 20 | 21 | function process(audioFrame) { 22 | for (let sample of audioFrame) 23 | { 24 | //binary 111111111111111, casts to 16Bit wav file spec 25 | Int16Convert ? inputBuffer.push(sample * 32767) : inputBuffer.push(sample) 26 | } 27 | while ((inputBuffer.length * targetSampleRate / nativeSampleRate) > targetFrameSize) { 28 | let outputFrame 29 | Int16Convert ? outputFrame = new Int16Array(targetFrameSize) : outputFrame = new Float32Array(targetFrameSize) 30 | let sum = 0 31 | let num = 0 32 | let outputIndex = 0 33 | let inputIndex = 0 34 | while (outputIndex < targetFrameSize) { 35 | sum = 0 36 | num = 0 37 | while (inputIndex < Math.min(inputBuffer.length, (outputIndex + 1) * nativeSampleRate / targetSampleRate)) { 38 | sum += inputBuffer[inputIndex] 39 | num++ 40 | inputIndex++ 41 | } 42 | outputFrame[outputIndex] = sum / num 43 | outputIndex++ 44 | } 45 | inputBuffer = inputBuffer.slice(inputIndex) 46 | postMessage(outputFrame) 47 | } 48 | } 49 | 50 | -------------------------------------------------------------------------------- /src/webvoicesdk/workers/features.blob.js: -------------------------------------------------------------------------------- 1 | /* 2 | references : 3 | https://github.com/meyda/meyda 4 | https://github.com/nevosegal/fftjs 5 | https://github.com/vail-systems/node-dct 6 | https://github.com/Lokhozt/mfcc/blob/master/lib/mfcc.dart 7 | */ 8 | 9 | 10 | // ============================================================================= 11 | // DCT 12 | // ============================================================================= 13 | var cosMap = null; 14 | 15 | // Builds a cosine map for the given input size. This allows multiple input sizes to be memoized automagically 16 | // if you want to run the DCT over and over. 17 | var memoizeCosines = function (N) { 18 | cosMap = cosMap || {}; 19 | cosMap[N] = new Array(N * N); 20 | var PI_N = Math.PI / N; 21 | for (var k = 0; k < N; k++) { 22 | for (var n = 0; n < N; n++) { 23 | cosMap[N][n + (k * N)] = Math.cos(PI_N * (n + 0.5) * k); 24 | } 25 | } 26 | }; 27 | // DCT type 2 with ortho norm 28 | function dct(signal) { 29 | var N = signal.length 30 | var result = new Array(N); 31 | var sum = 0.0; 32 | 33 | // First value 34 | for (var n = 0; n < N ; n++) { 35 | sum += signal[n]; 36 | } 37 | result[0] = sum * 2 * Math.sqrt(1 / (4 * N)) 38 | 39 | // Following values 40 | for (var k = 1; k < N; k++){ 41 | sum = 0.0; 42 | for (var n = 0; n < N ; n++) { 43 | sum += signal[n] * Math.cos(Math.PI * k * (2 * n + 1)/(2 * N)); 44 | } 45 | result[k] = sum * 2 * Math.sqrt(1 / (2 * N)); 46 | } 47 | return result; 48 | } 49 | 50 | // ============================================================================= 51 | // FFT UTILS 52 | // ============================================================================= 53 | 54 | // memoization of the reversal of different lengths. 55 | var memoizedReversal = {}; 56 | var memoizedZeroBuffers = {} 57 | 58 | let constructComplexArray = function (signal) { 59 | var complexSignal = {}; 60 | 61 | complexSignal.real = (signal.real === undefined) ? signal.slice() : signal.real.slice(); 62 | 63 | var bufferSize = complexSignal.real.length; 64 | 65 | if (memoizedZeroBuffers[bufferSize] === undefined) { 66 | memoizedZeroBuffers[bufferSize] = Array.apply(null, Array(bufferSize)).map(Number.prototype.valueOf, 0); 67 | } 68 | 69 | complexSignal.imag = memoizedZeroBuffers[bufferSize].slice(); 70 | 71 | return complexSignal; 72 | } 73 | 74 | let bitReverseArray = function (N) { 75 | if (memoizedReversal[N] === undefined) { 76 | let maxBinaryLength = (N - 1).toString(2).length; //get the binary length of the largest index. 77 | let templateBinary = '0'.repeat(maxBinaryLength); //create a template binary of that length. 78 | let reversed = {}; 79 | for (let n = 0; n < N; n++) { 80 | let currBinary = n.toString(2); //get binary value of current index. 81 | 82 | //prepend zeros from template to current binary. This makes binary values of all indices have the same length. 83 | currBinary = templateBinary.substr(currBinary.length) + currBinary; 84 | 85 | currBinary = [...currBinary].reverse().join(''); //reverse 86 | reversed[n] = parseInt(currBinary, 2); //convert to decimal 87 | } 88 | memoizedReversal[N] = reversed; //save 89 | } 90 | return memoizedReversal[N]; 91 | } 92 | 93 | // complex multiplication 94 | let multiply = function (a, b) { 95 | return { 96 | 'real': a.real * b.real - a.imag * b.imag, 97 | 'imag': a.real * b.imag + a.imag * b.real 98 | }; 99 | } 100 | 101 | // complex addition 102 | let add = function (a, b) { 103 | return { 104 | 'real': a.real + b.real, 105 | 'imag': a.imag + b.imag 106 | }; 107 | } 108 | 109 | // complex subtraction 110 | let subtract = function (a, b) { 111 | return { 112 | 'real': a.real - b.real, 113 | 'imag': a.imag - b.imag 114 | }; 115 | } 116 | 117 | // euler's identity e^x = cos(x) + sin(x) 118 | let euler = function (kn, N) { 119 | let x = -2 * Math.PI * kn / N; 120 | return { 121 | 'real': Math.cos(x), 122 | 'imag': Math.sin(x) 123 | }; 124 | } 125 | 126 | // complex conjugate 127 | let conj = function (a) { 128 | a.imag *= -1; 129 | return a; 130 | } 131 | 132 | // ============================================================================= 133 | // FFT COMPUTE 134 | // ============================================================================= 135 | 136 | 137 | // real to complex fft 138 | let fft = function (signal) { 139 | 140 | let complexSignal = {}; 141 | 142 | if (signal.real === undefined || signal.imag === undefined) { 143 | complexSignal = constructComplexArray(signal); 144 | } else { 145 | complexSignal.real = signal.real.slice(); 146 | complexSignal.imag = signal.imag.slice(); 147 | } 148 | 149 | const N = complexSignal.real.length; 150 | const logN = Math.log2(N); 151 | 152 | if (Math.round(logN) != logN) throw new Error('Input size must be a power of 2.'); 153 | 154 | if (complexSignal.real.length != complexSignal.imag.length) { 155 | throw new Error('Real and imaginary components must have the same length.'); 156 | } 157 | 158 | const bitReversedIndices = bitReverseArray(N); 159 | 160 | // sort array 161 | let ordered = { 162 | 'real': [], 163 | 'imag': [] 164 | }; 165 | 166 | for (let i = 0; i < N; i++) { 167 | ordered.real[bitReversedIndices[i]] = complexSignal.real[i]; 168 | ordered.imag[bitReversedIndices[i]] = complexSignal.imag[i]; 169 | } 170 | 171 | for (let i = 0; i < N; i++) { 172 | complexSignal.real[i] = ordered.real[i]; 173 | complexSignal.imag[i] = ordered.imag[i]; 174 | } 175 | // iterate over the number of stages 176 | for (let n = 1; n <= logN; n++) { 177 | let currN = Math.pow(2, n); 178 | 179 | // find twiddle factors 180 | for (let k = 0; k < currN / 2; k++) { 181 | let twiddle = euler(k, currN); 182 | 183 | // on each block of FT, implement the butterfly diagram 184 | for (let m = 0; m < N / currN; m++) { 185 | let currEvenIndex = (currN * m) + k; 186 | let currOddIndex = (currN * m) + k + (currN / 2); 187 | 188 | let currEvenIndexSample = { 189 | 'real': complexSignal.real[currEvenIndex], 190 | 'imag': complexSignal.imag[currEvenIndex] 191 | } 192 | let currOddIndexSample = { 193 | 'real': complexSignal.real[currOddIndex], 194 | 'imag': complexSignal.imag[currOddIndex] 195 | } 196 | 197 | let odd = multiply(twiddle, currOddIndexSample); 198 | 199 | let subtractionResult = subtract(currEvenIndexSample, odd); 200 | complexSignal.real[currOddIndex] = subtractionResult.real; 201 | complexSignal.imag[currOddIndex] = subtractionResult.imag; 202 | 203 | let additionResult = add(odd, currEvenIndexSample); 204 | complexSignal.real[currEvenIndex] = additionResult.real; 205 | complexSignal.imag[currEvenIndex] = additionResult.imag; 206 | } 207 | } 208 | } 209 | 210 | return complexSignal; 211 | } 212 | 213 | 214 | // ============================================================================= 215 | // MFCC 216 | // ============================================================================= 217 | 218 | var prepareSignalWithSpectrum = function (signal, bufferSize) { 219 | var preparedSignal = {}; 220 | preparedSignal.complexSpectrum = fft(signal.slice(0, bufferSize)); 221 | preparedSignal.powSpectrum = new Float32Array(bufferSize / 2 + 1); 222 | for (var i = 0; i < bufferSize / 2 + 1; i++) { 223 | preparedSignal.powSpectrum[i] = ( 224 | Math.pow(preparedSignal.complexSpectrum.real[i], 2) + 225 | Math.pow(preparedSignal.complexSpectrum.imag[i], 2)); 226 | } 227 | return preparedSignal; 228 | }; 229 | 230 | function _melToFreq(melValue) { 231 | var freqValue = 700 * (Math.exp(melValue / 1127) - 1); 232 | return freqValue; 233 | } 234 | 235 | function _freqToMel(freqValue) { 236 | var melValue = 1127 * Math.log(1 + (freqValue / 700)); 237 | return melValue; 238 | } 239 | 240 | function melToFreq(mV) { 241 | return _melToFreq(mV); 242 | } 243 | 244 | function freqToMel(fV) { 245 | return _freqToMel(fV); 246 | } 247 | 248 | function createMelFilterBank(numFilters, sampleRate, bufferSize) { 249 | //the +2 is the upper and lower limits 250 | let melValues = new Float32Array(numFilters + 2); 251 | let melValuesInFreq = new Float32Array(numFilters + 2); 252 | 253 | //Generate limits in Hz - from 0 to the nyquist. 254 | let lowerLimitFreq = 0; 255 | let upperLimitFreq = sampleRate / 2; 256 | 257 | //Convert the limits to Mel 258 | let lowerLimitMel = _freqToMel(lowerLimitFreq); 259 | let upperLimitMel = _freqToMel(upperLimitFreq); 260 | 261 | //Find the range 262 | let range = upperLimitMel - lowerLimitMel; 263 | 264 | //Find the range as part of the linear interpolation 265 | let valueToAdd = range / (numFilters + 1); 266 | 267 | let fftBinsOfFreq = Array(numFilters + 2); 268 | 269 | for (let i = 0; i < melValues.length; i++) { 270 | // Initialising the mel frequencies 271 | // They're a linear interpolation between the lower and upper limits. 272 | melValues[i] = i * valueToAdd; 273 | 274 | // Convert back to Hz 275 | melValuesInFreq[i] = _melToFreq(melValues[i]); 276 | 277 | // Find the corresponding bins 278 | fftBinsOfFreq[i] = Math.floor((bufferSize + 1) * 279 | melValuesInFreq[i] / sampleRate); 280 | } 281 | 282 | var filterBank = Array(numFilters); 283 | for (let j = 0; j < filterBank.length; j++) { 284 | // Create a two dimensional array of size numFilters * (buffersize/2)+1 285 | // pre-populating the arrays with 0s. 286 | filterBank[j] = Array.apply( 287 | null, 288 | new Array((bufferSize / 2) + 1)).map(Number.prototype.valueOf, 0); 289 | 290 | //creating the lower and upper slopes for each bin 291 | for (let i = fftBinsOfFreq[j]; i < fftBinsOfFreq[j + 1]; i++) { 292 | filterBank[j][i] = (i - fftBinsOfFreq[j]) / 293 | (fftBinsOfFreq[j + 1] - fftBinsOfFreq[j]); 294 | } 295 | 296 | for (let i = fftBinsOfFreq[j + 1]; i < fftBinsOfFreq[j + 2]; i++) { 297 | filterBank[j][i] = (fftBinsOfFreq[j + 2] - i) / 298 | (fftBinsOfFreq[j + 2] - fftBinsOfFreq[j + 1]); 299 | } 300 | } 301 | return filterBank; 302 | } 303 | 304 | 305 | function mffcCompute(args) { 306 | if (typeof args.powSpectrum !== 'object') { 307 | throw new TypeError('Valid ampSpectrum is required to generate MFCC'); 308 | } 309 | if (typeof args.melFilterBank !== 'object') { 310 | throw new TypeError('Valid melFilterBank is required to generate MFCC'); 311 | } 312 | 313 | let numberOfMFCCCoefficients = Math.min(40, Math.max(1, args.numberOfMFCCCoefficients || 13)); 314 | 315 | // Tutorial from: 316 | // http://practicalcryptography.com/miscellaneous/machine-learning 317 | // /guide-mel-frequency-cepstral-coefficients-mfccs/ 318 | let numFilters = args.melFilterBank.length; 319 | let filtered = Array(numFilters); 320 | 321 | if (numFilters < numberOfMFCCCoefficients) { 322 | throw new Error("Insufficient filter bank for requested number of coefficients"); 323 | } 324 | let loggedMelBands = new Float32Array(numFilters); 325 | 326 | for (let i = 0; i < loggedMelBands.length; i++) { 327 | filtered[i] = new Float32Array(args.bufferSize / 2 + 1); 328 | loggedMelBands[i] = 0; 329 | for (let j = 0; j < (args.bufferSize / 2 + 1); j++) { 330 | //point-wise multiplication between power spectrum and filterbanks. 331 | filtered[i][j] = args.melFilterBank[i][j] * args.powSpectrum[j]; 332 | //summing up all of the coefficients into one array 333 | loggedMelBands[i] += filtered[i][j]; 334 | } 335 | //log each coefficient. 336 | loggedMelBands[i] = Math.log(loggedMelBands[i] > 0.0 ? loggedMelBands[i] : 1e-45); 337 | } 338 | //dct 339 | let loggedMelBandsArray = Array.prototype.slice.call(loggedMelBands); 340 | let mfccs = dct(loggedMelBandsArray).slice(0, numberOfMFCCCoefficients); 341 | 342 | return mfccs; 343 | } 344 | 345 | // ============================================================================= 346 | // JAVASCRIPT WORKER IMPLEMENTATION 347 | // ============================================================================= 348 | 349 | let melFilterBank = null 350 | let sampleRate 351 | let numFilters 352 | let numCoefs 353 | let discardFirstBand = true 354 | let bufferSize = 0 355 | 356 | onmessage = function (msg) { 357 | switch (msg.data.method) { 358 | case "configure": 359 | numFilters = msg.data.numFilters 360 | numCoefs = msg.data.numCoefs 361 | sampleRate = msg.data.sampleRate 362 | bufferSize = msg.data.bufferSize 363 | discardFirstBand = msg.data.discardFirstBand 364 | melFilterBank = createMelFilterBank(numFilters, sampleRate * 2, bufferSize) 365 | break 366 | case "process": 367 | mfcc(msg.data.audioFrame, sampleRate, bufferSize) 368 | break 369 | } 370 | } 371 | 372 | function mfcc(audioBuffer, sampleRate, bufferSize) { 373 | let preparedSignal = prepareSignalWithSpectrum(audioBuffer, bufferSize) 374 | let preparedObject = { 375 | numberOfMFCCCoefficients: numCoefs, 376 | sampleRate, 377 | bufferSize, 378 | powSpectrum: preparedSignal.powSpectrum, 379 | melFilterBank 380 | } 381 | let mfccs = mffcCompute(preparedObject) 382 | if (discardFirstBand) mfccs.shift() 383 | postMessage(mfccs) 384 | } -------------------------------------------------------------------------------- /src/webvoicesdk/workers/hotword.blob.js: -------------------------------------------------------------------------------- 1 | self.importScripts('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.21.0/dist/tf.min.js') 2 | self.importScripts('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@3.21.0/dist/tf-backend-wasm.min.js') //.min.js not working when using SIMD/Threaded flags ? 3 | 4 | 5 | let model 6 | let hotWords 7 | let threshold 8 | onmessage = async function (msg) { 9 | switch (msg.data.method) { 10 | case "process": 11 | await tf.ready() 12 | infer(msg.data.features) 13 | break 14 | case "configure": 15 | threshold = msg.data.threshold 16 | await tf.wasm.setWasmPaths({ 17 | 'tfjs-backend-wasm.wasm': msg.data.wasmPaths.tfWasm, 18 | 'tfjs-backend-wasm-simd.wasm': msg.data.wasmPaths.tfWasmSimd, 19 | 'tfjs-backend-wasm-threaded-simd.wasm': msg.data.wasmPaths.tfWasmThreadedSimd, 20 | }); 21 | //const simdSupported = await tf.env().getAsync('WASM_HAS_SIMD_SUPPORT') 22 | //const threadsSupported = await tf.env().getAsync('WASM_HAS_MULTITHREAD_SUPPORT') 23 | await tf.setBackend('wasm') 24 | break 25 | case "loadModel": 26 | await tf.enableProdMode() 27 | await tf.ready() 28 | hotWords = msg.data.words 29 | model = await tf.loadLayersModel(msg.data.modelUrl) 30 | break 31 | } 32 | } 33 | 34 | 35 | let noSpam = false 36 | function infer(features) { 37 | if (!noSpam) { 38 | noSpam = !noSpam 39 | setTimeout(() => { 40 | noSpam = !noSpam 41 | }, 0) // Prevents for firying multiple hotword events. Even if hotword node is paused. This is ugly but necessary 42 | let tensor 43 | let inference 44 | let inferedArray 45 | tf.tidy((tensor) => { 46 | tensor = tf.tensor3d(new Array(features)) 47 | inference = model.predict(tensor) 48 | inferedArray = Array.from(inference.dataSync()) 49 | // 1st map Constructs array ["hotWordName":float(0->1)] 50 | // 2nd map Checks if any value > threshold 51 | tensor.dispose() 52 | }) 53 | hotWords.map((hotWord, index) => { 54 | return [hotWord, inferedArray[index]] 55 | }).map((val) => { 56 | if (val[1] > threshold) { 57 | postMessage(val[0]) // name of the spotted hotword 58 | } 59 | }) 60 | } 61 | 62 | } -------------------------------------------------------------------------------- /src/webvoicesdk/workers/speechpreemphasis.blob.js: -------------------------------------------------------------------------------- 1 | 2 | onmessage = function (msg) { 3 | switch (msg.data.method) { 4 | case "process": 5 | process(msg.data.audioFrame) 6 | break 7 | } 8 | } 9 | 10 | let lastFrameValue = 0 11 | let val 12 | 13 | function process(audioFrame) { 14 | let emphasedAudioFrame = [] 15 | for (let i = 0; i < audioFrame.length; i++) { 16 | if (i == 0) { 17 | val = audioFrame[i] - lastFrameValue * 0.97 18 | } else { 19 | val = audioFrame[i] - audioFrame[i - 1] * 0.97 20 | } 21 | emphasedAudioFrame.push(val) 22 | } 23 | lastFrameValue = audioFrame[audioFrame.length - 1] 24 | postMessage(Float32Array.from(emphasedAudioFrame)) 25 | } -------------------------------------------------------------------------------- /tests/static-html/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Some tests 5 | 80 | 81 | 82 | 83 | 84 | 85 | 86 |
87 | LinTO ! 88 |
89 |
90 |
91 | 92 | 93 | 94 | 95 | 96 | 97 |
98 |
99 |
100 | LinTO ! 101 |
102 |
103 | 104 | 105 |
106 |
107 |
108 |
109 | 110 |
111 | 112 | 113 |
114 | 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /tests/static-html/index.js: -------------------------------------------------------------------------------- 1 | const VADHandler = function (speakingEvent) { 2 | speakingEvent.detail ? (document.getElementById("VADLed").classList.add("led-red"), document.getElementById("VADLed").classList.remove("led-green")) : (document.getElementById("VADLed").classList.add("led-green"), document.getElementById("VADLed").classList.remove("led-red")) 3 | } 4 | 5 | const HotwordHandler = function (hotWordEvent) { 6 | hotword.pause() 7 | document.getElementById("LinTO").innerHTML = hotWordEvent.detail 8 | document.getElementById("LinTO").setAttribute('style', 'display:inline-block;') 9 | 10 | setTimeout(() => { 11 | hotword.resume() 12 | document.getElementById("LinTO").setAttribute('style', 'display:none;') 13 | }, 1500) 14 | } 15 | window.start = async function () { 16 | window.mic = new webVoiceSDK.Mic(JSON.parse(document.getElementById('mic').value)) 17 | window.downSampler = new webVoiceSDK.DownSampler() 18 | window.vad = new webVoiceSDK.Vad(JSON.parse(document.getElementById('VAD').value)) 19 | window.speechPreemphaser = new webVoiceSDK.SpeechPreemphaser() 20 | window.feat = new webVoiceSDK.FeaturesExtractor() 21 | window.hotword = new webVoiceSDK.Hotword() 22 | await mic.start() 23 | await downSampler.start(mic) 24 | await vad.start(mic) 25 | await speechPreemphaser.start(downSampler) 26 | await feat.start(speechPreemphaser) 27 | await hotword.start(feat, vad, 0.9) 28 | await hotword.loadModel(hotword.availableModels["linto"]) 29 | document.getElementById("VADLed").setAttribute('style', 'display:inline-block;') 30 | vad.addEventListener("speakingStatus", VADHandler) 31 | hotword.addEventListener("hotword", HotwordHandler) 32 | } 33 | 34 | window.stop = async function () { 35 | await downSampler.stop() 36 | await vad.stop() 37 | await speechPreemphaser.stop() 38 | await feat.stop() 39 | await hotword.stop(feat, vad) 40 | document.getElementById("VADLed").setAttribute('style', 'display:none;') 41 | vad.removeEventListener("speakingStatus", VADHandler) 42 | } 43 | 44 | window.rec = async function () { 45 | window.recMic = new webVoiceSDK.Recorder() 46 | window.recFeatures = new webVoiceSDK.Recorder() 47 | window.recDownsampler = new webVoiceSDK.Recorder() 48 | window.recSpeechPreemphaser = new webVoiceSDK.Recorder() 49 | window.recHw = new webVoiceSDK.Recorder() 50 | await recMic.start(mic) 51 | await recHw.start(hotword) 52 | await recFeatures.start(feat) 53 | await recDownsampler.start(downSampler) 54 | await recSpeechPreemphaser.start(speechPreemphaser) 55 | recMic.rec() 56 | recFeatures.rec() 57 | recDownsampler.rec() 58 | recSpeechPreemphaser.rec() 59 | recHw.rec() 60 | } 61 | 62 | window.stopRec = async function () { 63 | recMic.stopRec() 64 | recFeatures.stopRec() 65 | recDownsampler.stopRec() 66 | recSpeechPreemphaser.stopRec() 67 | recHw.stopRec() 68 | 69 | showLink(recMic) 70 | showLink(recFeatures) 71 | showLink(recDownsampler) 72 | showLink(recSpeechPreemphaser) 73 | showLink(recHw) 74 | } 75 | 76 | window.showLink = function (recInstance) { 77 | let url = recInstance.getFile() 78 | let link = window.document.createElement('a') 79 | link.href = url 80 | if (recInstance.hookedOn.type == "mic" || recInstance.hookedOn.type == "downSampler" || recInstance.hookedOn.type == "speechPreemphaser") { 81 | link.download = recInstance.hookedOn.type + ".wav" 82 | } 83 | if (recInstance.hookedOn.type == "featuresExtractor") { 84 | link.download = recInstance.hookedOn.type + '.json' 85 | } 86 | if (recInstance.hookedOn.type == "hotword") { 87 | link.download = recInstance.hookedOn.type + '.json' 88 | } 89 | link.textContent = recInstance.hookedOn.type 90 | let click = document.createEvent("Event") 91 | click.initEvent("click", true, true) 92 | link.dispatchEvent(click) 93 | // Attach the link to the DOM 94 | document.body.appendChild(link) 95 | let hr = window.document.createElement('hr') 96 | document.body.appendChild(hr) 97 | } 98 | 99 | // HTML Interface 100 | document.getElementById('mic').value = JSON.stringify(webVoiceSDK.Mic.defaultOptions, false, 4) 101 | document.getElementById('VAD').value = JSON.stringify(webVoiceSDK.Vad.defaultOptions, false, 4) 102 | 103 | 104 | document.getElementById("start").onclick = async () => { 105 | start() 106 | } 107 | 108 | document.getElementById("lintomodel").onclick = async () => { 109 | hotword.loadModel(hotword.availableModels["linto"]) 110 | } 111 | 112 | document.getElementById("slinfoxmodel").onclick = async () => { 113 | hotword.loadModel(hotword.availableModels["slinfox"]) 114 | } 115 | 116 | document.getElementById("stop").onclick = async () => { 117 | stop() 118 | } 119 | 120 | document.getElementById("startrecord").onclick = async () => { 121 | rec() 122 | } 123 | 124 | document.getElementById("stoprecord").onclick = async () => { 125 | stopRec() 126 | } -------------------------------------------------------------------------------- /tests/with-bundler/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Some tests 5 | 80 | 81 | 82 | 83 | 84 | 85 |
86 | LinTO ! 87 |
88 |
89 |
90 | 91 | 92 | 93 | 94 | 95 | 96 |
97 |
98 |
99 | LinTO ! 100 |
101 |
102 | 103 | 104 |
105 |
106 |
107 |
108 | 109 |
110 | 111 | 112 |
113 | 114 | 115 | 116 | 117 | -------------------------------------------------------------------------------- /tests/with-bundler/index.js: -------------------------------------------------------------------------------- 1 | import webVoiceSDK from '../../src/webvoicesdk.js' 2 | 3 | const VADHandler = function (speakingEvent) { 4 | speakingEvent.detail ? (document.getElementById("VADLed").classList.add("led-red"), document.getElementById("VADLed").classList.remove("led-green")) : (document.getElementById("VADLed").classList.add("led-green"), document.getElementById("VADLed").classList.remove("led-red")) 5 | } 6 | 7 | const HotwordHandler = function (hotWordEvent) { 8 | hotword.pause() 9 | document.getElementById("LinTO").innerHTML = hotWordEvent.detail 10 | document.getElementById("LinTO").setAttribute('style', 'display:inline-block;') 11 | 12 | setTimeout(() => { 13 | hotword.resume() 14 | document.getElementById("LinTO").setAttribute('style', 'display:none;') 15 | }, 1500) 16 | } 17 | window.start = async function () { 18 | window.mic = new webVoiceSDK.Mic(JSON.parse(document.getElementById('mic').value)) 19 | window.downSampler = new webVoiceSDK.DownSampler() 20 | window.vad = new webVoiceSDK.Vad(JSON.parse(document.getElementById('VAD').value)) 21 | window.speechPreemphaser = new webVoiceSDK.SpeechPreemphaser() 22 | window.feat = new webVoiceSDK.FeaturesExtractor() 23 | window.hotword = new webVoiceSDK.Hotword() 24 | await mic.start() 25 | await downSampler.start(mic) 26 | await vad.start(mic) 27 | await speechPreemphaser.start(downSampler) 28 | await feat.start(speechPreemphaser) 29 | await hotword.start(feat, vad, 0.9) 30 | await hotword.loadModel(hotword.availableModels["linto"]) 31 | document.getElementById("VADLed").setAttribute('style', 'display:inline-block;') 32 | vad.addEventListener("speakingStatus", VADHandler) 33 | hotword.addEventListener("hotword", HotwordHandler) 34 | } 35 | 36 | window.stop = async function () { 37 | await downSampler.stop() 38 | await vad.stop() 39 | await speechPreemphaser.stop() 40 | await feat.stop() 41 | await hotword.stop(feat, vad) 42 | document.getElementById("VADLed").setAttribute('style', 'display:none;') 43 | vad.removeEventListener("speakingStatus", VADHandler) 44 | } 45 | 46 | window.rec = async function () { 47 | window.recMic = new webVoiceSDK.Recorder() 48 | window.recFeatures = new webVoiceSDK.Recorder() 49 | window.recDownsampler = new webVoiceSDK.Recorder() 50 | window.recSpeechPreemphaser = new webVoiceSDK.Recorder() 51 | window.recHw = new webVoiceSDK.Recorder() 52 | await recMic.start(mic) 53 | await recHw.start(hotword) 54 | await recFeatures.start(feat) 55 | await recDownsampler.start(downSampler) 56 | await recSpeechPreemphaser.start(speechPreemphaser) 57 | recMic.rec() 58 | recFeatures.rec() 59 | recDownsampler.rec() 60 | recSpeechPreemphaser.rec() 61 | recHw.rec() 62 | } 63 | 64 | window.stopRec = async function () { 65 | recMic.stopRec() 66 | recFeatures.stopRec() 67 | recDownsampler.stopRec() 68 | recSpeechPreemphaser.stopRec() 69 | recHw.stopRec() 70 | 71 | showLink(recMic) 72 | showLink(recFeatures) 73 | showLink(recDownsampler) 74 | showLink(recSpeechPreemphaser) 75 | showLink(recHw) 76 | } 77 | 78 | window.showLink = function (recInstance) { 79 | let url = recInstance.getFile() 80 | let link = window.document.createElement('a') 81 | link.href = url 82 | if (recInstance.hookedOn.type == "mic" || recInstance.hookedOn.type == "downSampler" || recInstance.hookedOn.type == "speechPreemphaser") { 83 | link.download = recInstance.hookedOn.type + ".wav" 84 | } 85 | if (recInstance.hookedOn.type == "featuresExtractor") { 86 | link.download = recInstance.hookedOn.type + '.json' 87 | } 88 | if (recInstance.hookedOn.type == "hotword") { 89 | link.download = recInstance.hookedOn.type + '.json' 90 | } 91 | link.textContent = recInstance.hookedOn.type 92 | let click = document.createEvent("Event") 93 | click.initEvent("click", true, true) 94 | link.dispatchEvent(click) 95 | // Attach the link to the DOM 96 | document.body.appendChild(link) 97 | let hr = window.document.createElement('hr') 98 | document.body.appendChild(hr) 99 | } 100 | 101 | // HTML Interface 102 | document.getElementById('mic').value = JSON.stringify(webVoiceSDK.Mic.defaultOptions, false, 4) 103 | document.getElementById('VAD').value = JSON.stringify(webVoiceSDK.Vad.defaultOptions, false, 4) 104 | 105 | 106 | document.getElementById("start").onclick = async () => { 107 | start() 108 | } 109 | 110 | document.getElementById("lintomodel").onclick = async () => { 111 | hotword.loadModel(hotword.availableModels["linto"]) 112 | } 113 | 114 | document.getElementById("slinfoxmodel").onclick = async () => { 115 | hotword.loadModel(hotword.availableModels["slinfox"]) 116 | } 117 | 118 | document.getElementById("stop").onclick = async () => { 119 | stop() 120 | } 121 | 122 | document.getElementById("startrecord").onclick = async () => { 123 | rec() 124 | } 125 | 126 | document.getElementById("stoprecord").onclick = async () => { 127 | stopRec() 128 | } --------------------------------------------------------------------------------