├── .gitignore ├── LICENSE ├── README.md ├── load-runner.pl ├── resources ├── pcap │ └── one-minute-wait-music.pcap └── wav │ └── audio_long16.wav ├── tools ├── README.md ├── cert │ ├── cert.pem │ ├── csr.pem │ └── key.pem ├── http-server.js ├── tmp │ └── server.py └── webrtc-test.py └── webrtc-load-tests ├── README.md ├── scripts ├── WebRTComm.js ├── adapter.js ├── jain-sip.js ├── restcomm-web-client.js └── sounds │ ├── calling.mp3 │ ├── message.mp3 │ └── ringing.mp3 ├── webrtc-client.html └── webrtc-sipp-client.xml /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | -------------------------------------------------------------------------------- /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 637 | by 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 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | [Try Restcomm Cloud NOW for FREE!](https://www.restcomm.com/sign-up/) Zero download and install required. 5 | 6 | 7 | All Restcomm [docs](https://www.restcomm.com/docs/) and [downloads](https://www.restcomm.com/downloads/) are now available at [Restcomm.com](https://www.restcomm.com). 8 | 9 | 10 | 11 | # webrtc-test 12 | 13 | Framework for functional and Load Testing of WebRTC. Can be used to test client and server media components utilizing WebRTC, like Media Servers, SIP clients, etc. Has been tested both in regular hosts that have a window environment as well as headless servers in Amazon EC2 (using Xvfb) 14 | 15 | ## How it works ## 16 | 17 | At the heart of webrtc-test is python script [webrtc-test](https://github.com/RestComm/webrtc-test/blob/master/tools/webrtc-test.py) which sets up Restcomm for the test, spawns webrtc clients in browser tabs and starts some servers to help with the scenario, more specifically it: 18 | * Provisions the Restcomm instance with needed Incoming Number and Restcomm Clients that will be used by the webrtc clients when registering 19 | * Starts up a node js http server that will serve the RCML for the Restcomm external service linked with the Incoming Number we provisioned previously. 20 | * Starts up a node js http(s) server that will serve the web app to the browser tabs. This app is configured to register with restcomm and wait for webrtc calls. 21 | * Starts up a python http(s) server that will serve wait for re-spawn Ajax requests from the web app. That is, each browser tab when finished with the phone call from Restcomm it notifies webrtc-test.py that it's done and closes. Once webrtc-test.py receives that requests it respawns a browser tab for the same user (this is a way to workaround an issue where after some calls browser tabs performance would degrade) 22 | * Spawn as many browser tabs as requested targeting the webrtc web app, using a separate username for each to register with Restcomm (from the pool provisioned previously) 23 | 24 | Once that setup is done we can then start the Sipp load scenarios found at [webrtc-load-tests](https://github.com/RestComm/webrtc-test/webrtc-load-tests) towards Restcomm Incoming Number and play a 1-minute media stream. Notice that you can use any tool you like to generate traffic towards Restcomm; we are using Sipp as an example. For each call this is what happens: 25 | * Restcomm receives the call and contacts the external service to see what to do with it 26 | * External service return RCML that instructs Restcomm to call the next available webrtc client and bridge the 2 calls 27 | * Webrtc client running in the browser tab receives the call from Restcomm and hears the 1-minute media stream sent by Sipp. At the same time it sends dummy media stream back 28 | * Once the whole media stream is played Sipp hangs up the call, which means that the call from Restcomm -> Webrtc client is also hung up 29 | * At that point the webrtc client notifies webrtc-test.py that it's about to close the tab so that the tool re-spawns another tab in it's stead 30 | 31 | ## How to use it ## 32 | 33 | For sake of brevity we 'll go over the simple case where both Restcomm, webrtc-test.py and sipp are all on the same host. But keep in mind that you can separate them since both Restcomm and webrtc-test.py take up a lot of resources (remember that webrtc-test can spawn a lot of browsers for testing that can be pretty resource-hungry). In this example I will be using an Ubuntu Server image in Amazon EC2, but it should work on any GNU/Linux distribution as well as OSX which we have tested as well. 34 | 35 | ### 1. Install prerequisites ### 36 | 37 | * Install sipp for the SIP call generation (as already mentioned we are using Sipp for this example, but you can use any tool you like to generate calls) 38 | * Download latest tar.gz bundle from https://github.com/SIPp/sipp/releases 39 | * Install prerequisites: `$ sudo apt-get install ncurses-dev libpcap-dev` 40 | * Uncompress and configure with pcap support (so that we can RTP media as well, not only signaling) and build: `$ ./configure --with-pcap && make` 41 | * Install: `$ sudo make install` 42 | * Install python packages (main load script is written in python) 43 | * Install python package manager: `$ sudo apt-get install python-pip` 44 | * Install selenium (currently it isn’t used due to some scaling issues but the dependencies in the code are still there, so please install until we decide on this): `$ sudo pip install selenium` 45 | * Install nodejs packages (http server script is in nodejs as it appears to scale better than python; with python starting more that ~30 webrtc clients caused the python web server to fail for some of them) 46 | * Install nodejs `$ sudo apt-get install nodejs` 47 | * Some applications expect nodejs to be named node, so create this link: `$ sudo ln -s "$(which nodejs)" /usr/bin/node` 48 | * Install nodejs package manager: `$ sudo apt-get install npm` 49 | * Install needed nodejs modules (globally usually works best): `$ sudo npm -g install node-static express command-line-args` 50 | * Export nodejs modules path so that they can be discovered and used by nodejs (remember to add this in your profile or similar to be able to use it in future sessions): `$ export NODE_PATH=/usr/local/lib/node_modules` 51 | * Setup for headless execution 52 | * Install xvfb which is a virtual window environment where apps can render on memory instead of a real screen: `$ sudo apt-get install xvfb` 53 | * Optionally install some additional fonts to avoid getting warnings in xvfb: `$ sudo apt-get install xfonts-100dpi xfonts-75dpi xfonts-scalable xfonts-cyrillic` 54 | * Install firefox and chromium browsers `$ sudo apt-get install firefox chromium-browser` 55 | * Start xvfb in the background and configure it to use display 99 (randomly chosen display): `$ Xvfb :99 &` 56 | * Clone webrtc-test repo that contains the load testing tools: `$ git clone https://github.com/RestComm/webrtc-test.git` 57 | * Change dir to the load testing dir: `$ cd webrtc-test/tools` 58 | 59 | ### 2. Start webrtc-test.py ### 60 | 61 | In this example we are running the load testing tool to use 40 webrtc clients in headless mode in an Amazon EC2 instance: 62 | 63 | ``` 64 | $ ./webrtc-test.py 65 | --client-count 40 66 | --client-url https://10.231.4.197:10510/webrtc-client.html 67 | --client-register-ws-url wss://10.231.4.197:5083 68 | --client-register-domain 10.231.4.197 69 | --client-username-prefix user 70 | --client-password 1234 71 | --restcomm-account-sid ACae6e420f425248d6a26948c17a9e2acf 72 | --restcomm-auth-token 3349145c827863209020dbc513c87260 73 | --restcomm-base-url https://10.231.4.197:8443 74 | --restcomm-phone-number "+5556" 75 | --restcomm-external-service-url http://10.231.4.197:10512/rcml 76 | --client-browser "chromium-browser" 77 | --client-web-app-dir ../webrtc-load-tests/ 78 | --client-respawn 79 | --client-respawn-url https://10.231.4.197:10511/respawn-user 80 | --client-headless 81 | --client-headless-x-display ":99" 82 | ``` 83 | 84 | Option details: 85 | * **client-count** is the number of webrtc clients to handle calls (i.e. concurrent connections) 86 | * **client-url** is the webrtc web app URL, which will automatically register with Restcomm and be able to receive calls and auto-answer (or make in another scenario) 87 | * **client-register-ws-url** is the websocket URL that the webrtc web app should use for registering and general signalling with Restcomm 88 | * **client-register-domain** is the domain that the webrtc web app should use when registering 89 | * **client-username-prefix** is the username prefix for the generated Restcomm Clients (for example if the prefix is ‘user’ and the count is 10 the generated clients will be user1-user10) 90 | * **client-password** is the SIP password for the webrtc clients 91 | * **restcomm-account-sid** is the Restcomm account sid that we use for various Restcomm REST APIs (mostly for provisioning/unprovisioning) 92 | * **restcomm-auth-token** is the Restcomm auth token that we use for various Restcomm REST APIs 93 | * **restcomm-base-url** is the base url for Restcomm that we use for various Restcomm REST APIs 94 | * **restcomm-phone-number** is the incoming Restcomm number that we will target with our traffic generator (in this case Sipp) 95 | * **restcomm-external-service-url** is the external service URL that Restcomm will contact via GET to retrieve the RCML for the App (associated with number shown previously) 96 | * **client-browser** is the desired browser to use for the client. Currently supported are Firefox and Chrome 97 | * **client-web-app-dir** which directory should be served over http 98 | * **client-respawn** switch which if provided tells the tool to use respawn logic for the browser tabs. This means that after each tab finishes handling a call will be closed and recycled 99 | * **client-respawn-url** the URL where the browser window will notify webrtc-test.py that it just finished with a call and will close, so that webrtc-test.py will spawn a new tab. 100 | * **client-headless** switch to be used when we want the client to run in a headless fashion, where no real X windows environment is set and instead xvfb or other virtual window manager is used 101 | * **client-headless-x-display** when using headless, which virtual X display to use. Default is \':99\' 102 | 103 | ### 3. Initiate load tests ### 104 | 105 | Although you can use any tool you like to generate call traffic towards Restcomm, we are using Sipp as an example. What we do is use Sipp to create calls towards ‘+5556’ Restcomm number. In this example we are setting up sipp to use 20 concurrent calls. Important: the number of concurrent calls should be less than ‘--client-count’ passed in webrtc-test.py to give the closing browser windows time to re-spawn before a new call arrives for them. In fact it's a good practice to use half the client count for sipp concurrent calls for best results, as we do here: 106 | 107 | ``` 108 | $ sudo sipp -sf webrtc-sipp-client.xml -s +5556 10.231.4.197:5080 -mi 10.231.4.197:5090 -l 20 -m 40 -r 2 -trace_screen -trace_err -recv_timeout 5000 -nr -t u1 109 | ``` 110 | 111 | The main figure to note is the `-l 20 -m 40 -r 2` portion which means 20 concurrent calls, 40 total calls, at a rate of 2 calls per second. 112 | 113 | ### 4. Analyze the results ### 114 | 115 | When the Sipp test finishes we are presented with this output: 116 | 117 | ``` 118 | ----------------------------- Statistics Screen ------- [1-9]: Change Screen -- 119 | Start Time | 2016-04-07 09:32:01.115325 1460021521.115325 120 | Last Reset Time | 2016-04-07 09:34:15.723558 1460021655.723558 121 | Current Time | 2016-04-07 09:34:15.724996 1460021655.724996 122 | -------------------------+---------------------------+-------------------------- 123 | Counter Name | Periodic value | Cumulative value 124 | -------------------------+---------------------------+-------------------------- 125 | Elapsed Time | 00:00:00:001000 | 00:02:14:609000 126 | Call Rate | 0.000 cps | 0.297 cps 127 | -------------------------+---------------------------+-------------------------- 128 | Incoming call created | 0 | 0 129 | OutGoing call created | 0 | 40 130 | Total Call created | | 40 131 | Current Call | 0 | 132 | -------------------------+---------------------------+-------------------------- 133 | Successful call | 0 | 40 134 | Failed call | 0 | 0 135 | -------------------------+---------------------------+-------------------------- 136 | Response Time 1 | 00:00:00:000000 | 00:00:00:100000 137 | Call Length | 00:00:00:000000 | 00:01:02:115000 138 | ------------------------------ Test Terminated -------------------------------- 139 | ``` 140 | 141 | Which tells us that all calls are successful along with other interesting statistics. 142 | 143 | But this isn't the full picture. We need to check the browser side too make sure that Webrtc calls from Restcomm -> browser web clients are successful. To do that we take advantage of the [restcomm-web-sdks's](https://github.com/RestComm/restcomm-web-sdk) latest addition that exposes PeerConnection getStats() to the web app. For now we don't do anything fancy in the app, just print out in the browser console the whole dictionary as returned from the SDK. Here's a sample for one of the calls (noticed that I have beautified this to be easier to see here: 144 | 145 | ``` 146 | [5551:5551:0407/091640:INFO:CONSOLE(226)] "Retrieved call media stats: { 147 | "direction":"inbound", 148 | "bytes-transfered":"19092", 149 | "packets-transfered":"111", 150 | "output-level":"528", 151 | "media-type":"audio", 152 | "codec-name":"PCMA", 153 | "packets-lost":"0", 154 | "jitter":"0", 155 | "ssrc":"3967089803" 156 | }, 157 | { 158 | "direction":"outbound", 159 | "bytes-transfered":"19264", 160 | "packets-transfered":"112", 161 | "input-level":"6435", 162 | "media-type":"audio", 163 | "codec-name":"PCMA", 164 | "packets-lost":"-1", 165 | "jitter":"-1", 166 | "ssrc":"3854772780" 167 | }", ... 168 | ``` 169 | 170 | The fact that we see bytes transfered and no packets lost in both directions is a pretty good indication that things went well. Another indication is the input-level and output-level, but as far as I know these are only available in Chrome. Remember that all calls from Restcomm -> web app are audio-only, which is why you only see audio 'media-type' in the getStats() results. 171 | 172 | As always, feel free to jump in and play with the code and get your hands dirty. There's a list of [open issues](https://github.com/RestComm/webrtc-test/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) that you can start with, or you can suggest your own enhancements. If you have any questions please post at the [Restcomm forum](https://groups.google.com/forum/#!forum/restcomm) or in Stackoverflow using tag 'restcomm'. 173 | 174 | 175 | 176 | For frequently asked questions, please refer to the [FAQ](https://github.com/RestComm/webrtc-test/wiki/FAQ) 177 | -------------------------------------------------------------------------------- /load-runner.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | use warnings; 4 | use strict; 5 | use Getopt::Long; 6 | #use Switch; 7 | 8 | # globals 9 | my $version = "0.3"; 10 | 11 | # default command is to run actual load test 12 | my $command = "run"; 13 | my $clientCount = "30"; 14 | my $clientPrefix = "user"; 15 | my $clientPassword = "1234"; 16 | my $clientBrowser = "chromium-browser"; 17 | # grab eth0 interface ip address 18 | my $headlessIp = qx(ifconfig eth0 | perl -n -e 'if (m/inet addr:([\\d\\.]+)/g) { print \$1 }'); 19 | my $restcommIp = "10.142.205.168"; 20 | my $restcommAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; 21 | my $restcommAuthToken = "3349145c827863209020dbc513c87260"; 22 | my $restcommPhoneNumber = "+5556"; 23 | my $webrtcTestOutputFile = "webrtc-test-run.log"; 24 | my $sippOutputFile = "sipp-run.log"; 25 | my $sippConcurrentCalls = "10"; 26 | my $sippTotalCalls = "10000"; 27 | my $sippCallsPerSecond = "1"; 28 | my $noLogCleanup = 0; 29 | #my $eraseLogsOnly = 0; 30 | #my $shutdownOnly = 0; 31 | my $restcommEnableRecording = 0; 32 | 33 | # prints out a short usage for the tool 34 | sub printUsage 35 | { 36 | print "load-runner.pl, Ver. $version\n"; 37 | print "Usage: \$ load-runner.pl [options]\n"; 38 | print "Examples:\n"; 39 | print "\t\$ load-runner.pl --command run --client-count 30 --sipp-total-calls 35000 --sipp-concurrent-calls 10 --sipp-calls-per-second 1 --client-prefix 0user --restcomm-ip 10.142.205.168 --restcomm-account-sid ACae6e420f425248d6a26948c17a9e2acf --restcomm-auth-token 3349145c827863209020dbc513c87260 --restcomm-phone-number \"+5556\"\n"; 40 | print "\t\$ load-runner.pl --command erase-logs\n"; 41 | print "\t\$ load-runner.pl --command shutdown\n"; 42 | print "\t\$ load-runner.pl --command collect-logs\n"; 43 | } 44 | 45 | # kill all load test processes 46 | sub killProcesses 47 | { 48 | print "[load-runner] Killing load test processes\n"; 49 | qx(sudo pkill sipp; sudo pkill python; sudo pkill node; sudo pkill chrom); 50 | } 51 | 52 | # cleanup log files, etc from previous runs 53 | sub cleanupFiles 54 | { 55 | print "[load-runner] Cleaning up log files\n"; 56 | qx(rm -fr tools/*log.* tools/*log webrtc-load-tests/*log); 57 | } 58 | 59 | # start Xvfb if not already running 60 | sub startXvfb 61 | { 62 | my $stdout = qx(ps -ef | grep Xvfb | grep -v grep | wc -l); 63 | if (int($stdout) == 0) { 64 | print "[load-runner] Starting Xvfb\n"; 65 | qx(Xvfb :99 &); 66 | } 67 | else { 68 | print "[load-runner] Xvfb already running\n"; 69 | } 70 | } 71 | 72 | 73 | # start webrtc-test.py 74 | sub startWebrtcTest 75 | { 76 | my $enableRecordingOption = ""; 77 | if ($restcommEnableRecording) { 78 | $enableRecordingOption = "--restcomm-record-media"; 79 | } 80 | my $cmd = "cd tools; nohup ./webrtc-test.py --client-count " . $clientCount . " --client-url https://" . $headlessIp . ":10510/webrtc-client.html --client-register-ws-url wss://" . $restcommIp . ":5083 --client-register-domain " . $restcommIp . " --client-username-prefix " . $clientPrefix . " --client-password " . $clientPassword . " --restcomm-account-sid " . $restcommAccountSid . " --restcomm-auth-token " . $restcommAuthToken . " --restcomm-base-url https://" . $restcommIp . ":8443 --restcomm-phone-number \"" . $restcommPhoneNumber . "\" --restcomm-external-service-url http://" . $headlessIp . ":10512/rcml --client-browser \"" . $clientBrowser . "\" --client-web-app-dir ../webrtc-load-tests/ --client-headless --client-headless-x-display \":99\" --client-respawn --client-respawn-url https://" . $headlessIp . ":10511/respawn-user " . $enableRecordingOption . " < /dev/null > " . $webrtcTestOutputFile . " 2>&1 &"; 81 | print "[load-runner] Starting webrtc-test.py, \$ " . $cmd . "\n"; 82 | 83 | qx($cmd); 84 | } 85 | 86 | # wait for webrtc clients to register 87 | sub waitForClients 88 | { 89 | my $counter = 0; 90 | while ($counter < 30) { 91 | my $currentCount = qx(cd tools; cat *.log* | grep "\] Device is ready" | wc -l); 92 | chomp($currentCount); 93 | if ($currentCount eq $clientCount) { 94 | print "[load-runner] All clients are registered: " . $currentCount . "/" . $clientCount . "\n"; 95 | return 0; 96 | } 97 | else { 98 | print "[load-runner] Still waiting for clients to register: " . $currentCount . "/" . $clientCount . "\n"; 99 | } 100 | sleep 1; 101 | $counter += 1; 102 | } 103 | 104 | # error some/all clients still unregistered 105 | return 1; 106 | } 107 | 108 | # start sipp traffic 109 | sub startTraffic 110 | { 111 | my $cmd = "cd webrtc-load-tests; nohup sudo sipp -sf webrtc-sipp-client.xml -s " . $restcommPhoneNumber . " " . $restcommIp . ":5080 -mi " . $headlessIp . ":5090 -l " . $sippConcurrentCalls . " -m " . $sippTotalCalls . " -r " . $sippCallsPerSecond . " -trace_screen -trace_err -recv_timeout 5000 -nr -t u1 < /dev/null > " . $sippOutputFile . " 2>&1 &"; 112 | print "[load-runner] Starting sipp traffic, \$ " . $cmd . "\n"; 113 | 114 | qx($cmd); 115 | } 116 | 117 | #------------------------------# MAIN CODE #------------------------------# 118 | 119 | my $num_args = $#ARGV + 1; 120 | if ($num_args < 0) { 121 | print "args: " . $num_args . "\n"; 122 | printUsage(); 123 | exit 1; 124 | } 125 | 126 | 127 | my $result = GetOptions("command|c=s" => \$command, 128 | "client-count=s" => \$clientCount, 129 | "client-prefix=s" => \$clientPrefix, 130 | "client-password=s" => \$clientPassword, 131 | "client-browser=s" => \$clientBrowser, 132 | "headless-ip=s" => \$headlessIp, 133 | "restcomm-ip=s" => \$restcommIp, 134 | "restcomm-account-sid=s" => \$restcommAccountSid, 135 | "restcomm-auth-token=s" => \$restcommAuthToken, 136 | "restcomm-phone-number=s" => \$restcommPhoneNumber, 137 | "restcomm-enable-recording=i" => \$restcommEnableRecording, 138 | "sipp-concurrent-calls=s" => \$sippConcurrentCalls, 139 | "sipp-total-calls=s" => \$sippTotalCalls, 140 | "sipp-calls-per-second=s" => \$sippCallsPerSecond, 141 | "no-log-cleanup" => \$noLogCleanup, 142 | #"erase-logs-only" => \$eraseLogsOnly, 143 | #"shutdown-only" => \$shutdownOnly, 144 | "help|h" => sub { printUsage(); exit 1; }); 145 | 146 | if (!$result) { 147 | print STDERR "[nreg] Error parsing command-line options\n"; 148 | exit 1; 149 | } 150 | 151 | if ($command eq "run") { 152 | # stop any prior instances of load runner 153 | killProcesses(); 154 | 155 | if (!$noLogCleanup) { 156 | cleanupFiles(); 157 | } 158 | 159 | startXvfb(); 160 | 161 | startWebrtcTest(); 162 | 163 | if (waitForClients() != 0) { 164 | print "[load-runner] Clients still unregistered; bailing out\n"; 165 | exit 1; 166 | } 167 | 168 | startTraffic(); 169 | } 170 | elsif ($command eq "erase-logs") { 171 | cleanupFiles(); 172 | exit 0; 173 | } 174 | elsif ($command eq "shutdown") { 175 | killProcesses(); 176 | exit 0; 177 | } 178 | elsif ($command eq "collect-logs") { 179 | my $logFiles = qx(find . -name "*log" -o -name "*log.*"); 180 | chomp($logFiles); 181 | $logFiles =~ s/\n/ /; 182 | 183 | my $date = qx(date); 184 | chomp($date); 185 | # replace spaces in date 186 | $date =~ s/ /-/g; 187 | # remove colons that cause issues in the invocation 188 | $date =~ s/\://g; 189 | 190 | qx(mkdir $date); 191 | 192 | qx(cp $logFiles $date/); 193 | 194 | print "Compressing logs into $date.tar.gz\n"; 195 | qx(tar -zcvf $date.tar.gz $date); 196 | if ($? == 0) { 197 | qx(rm -fr $date); 198 | } 199 | else { 200 | print "[load-runner] Failed to compress logs"; 201 | } 202 | } 203 | 204 | -------------------------------------------------------------------------------- /resources/pcap/one-minute-wait-music.pcap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RestComm/webrtc-test/342617665383918f1252e6b46c29f02d958b491c/resources/pcap/one-minute-wait-music.pcap -------------------------------------------------------------------------------- /resources/wav/audio_long16.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RestComm/webrtc-test/342617665383918f1252e6b46c29f02d958b491c/resources/wav/audio_long16.wav -------------------------------------------------------------------------------- /tools/README.md: -------------------------------------------------------------------------------- 1 | ## Tools comprising the webrtc-test framework: ## 2 | 3 | * Main script is webrtc-test.py that does the orchestration 4 | * http-server.js is a node js script that handles both external service for Restcomm as well as serving the webrtc web app to the browsers 5 | * cert/ has a self-signed cert used when we need to use https instead of http for serving the web app with http-server.js (remember that this is needed for chrome to avoid issues with getUserMedia() from insecure origins) 6 | -------------------------------------------------------------------------------- /tools/cert/cert.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDqjCCApICCQCySgN7jKzm9zANBgkqhkiG9w0BAQsFADCBljELMAkGA1UEBhMC 3 | R1IxDzANBgNVBAgMBkF0dGlraTEPMA0GA1UEBwwGQXRoZW5zMREwDwYDVQQKDAhU 4 | ZWxlc3RheDENMAsGA1UECwwEVW5pdDETMBEGA1UEAwwKdGVzdC5sb2NhbDEuMCwG 5 | CSqGSIb3DQEJARYfYW50b25pcy50c2FraXJpZGlzQHRlbGVzdGF4LmNvbTAeFw0x 6 | NTEyMDcxNjMxMTBaFw00MzA0MjMxNjMxMTBaMIGWMQswCQYDVQQGEwJHUjEPMA0G 7 | A1UECAwGQXR0aWtpMQ8wDQYDVQQHDAZBdGhlbnMxETAPBgNVBAoMCFRlbGVzdGF4 8 | MQ0wCwYDVQQLDARVbml0MRMwEQYDVQQDDAp0ZXN0LmxvY2FsMS4wLAYJKoZIhvcN 9 | AQkBFh9hbnRvbmlzLnRzYWtpcmlkaXNAdGVsZXN0YXguY29tMIIBIjANBgkqhkiG 10 | 9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoyn8W+rm16BrPQjLQgjpsHB6fy0+KmtyM519 11 | BnM9IvUydyn/iaW6gjqow4gzN4iCYiSyq4WwsR2kqwwm0P3yR2w+yj3HcuWNcA0T 12 | 1v1vewEb8Y69T/OkgLpCS86599CtR1aIhPQ3H41L47HzlwTWvu87Ko436pwOVhZ7 13 | vwKQuV5S4VMYxhilAAv9LcWQo+f6yAE+g8gc9s5xspRLBvgbbO2ZtQY+DT9SckHZ 14 | /IlsmjdwcrsuxqLQrchamECuz2dIEbUxowdVfk3l73RSQa0LcOQg9AgkjSrLwlHo 15 | 2wboozQp2kqWm8w9w02G9gjLqoWRsEhYByKTDwDPOa0FpbIWmwIDAQABMA0GCSqG 16 | SIb3DQEBCwUAA4IBAQBRFkLNtRANmGhihg8VRbdJeZaJ1i6RjhdWQLnz30ivDVF2 17 | KeOIYg2sjitdsDGvMZz9Yfwx6Nlx6rpQIMDGXqG/hkIEdJ3LThNS1oZzSdFVEynn 18 | ha6VSGR3WyvCepQlHsKGz8jF0frCf+x6NVz+AOBV0itwFYoFIjvFnidUjQiCtq8f 19 | Av18eCRlIdSHFjc8iMTgRw4lAwZ+kDITbY6iiDVZiMmCbTrs4tNTOyJIRXjUF9aV 20 | 7rh7Hrf1Q3TGJPbjynQLuJz7ay0BCZ1MhzXLB2/b7/DtNngr/RyLeNv6k0qUt9Hw 21 | 5qgcAxtVLZg601Lz+5FbhvT11AoqdeJWykoFRJSQ 22 | -----END CERTIFICATE----- 23 | -------------------------------------------------------------------------------- /tools/cert/csr.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE REQUEST----- 2 | MIIC9TCCAd0CAQAwgZYxCzAJBgNVBAYTAkdSMQ8wDQYDVQQIDAZBdHRpa2kxDzAN 3 | BgNVBAcMBkF0aGVuczERMA8GA1UECgwIVGVsZXN0YXgxDTALBgNVBAsMBFVuaXQx 4 | EzARBgNVBAMMCnRlc3QubG9jYWwxLjAsBgkqhkiG9w0BCQEWH2FudG9uaXMudHNh 5 | a2lyaWRpc0B0ZWxlc3RheC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK 6 | AoIBAQCjKfxb6ubXoGs9CMtCCOmwcHp/LT4qa3IznX0Gcz0i9TJ3Kf+JpbqCOqjD 7 | iDM3iIJiJLKrhbCxHaSrDCbQ/fJHbD7KPcdy5Y1wDRPW/W97ARvxjr1P86SAukJL 8 | zrn30K1HVoiE9DcfjUvjsfOXBNa+7zsqjjfqnA5WFnu/ApC5XlLhUxjGGKUAC/0t 9 | xZCj5/rIAT6DyBz2znGylEsG+Bts7Zm1Bj4NP1JyQdn8iWyaN3Byuy7GotCtyFqY 10 | QK7PZ0gRtTGjB1V+TeXvdFJBrQtw5CD0CCSNKsvCUejbBuijNCnaSpabzD3DTYb2 11 | CMuqhZGwSFgHIpMPAM85rQWlshabAgMBAAGgGTAXBgkqhkiG9w0BCQIxCgwIVGVs 12 | ZXN0YXgwDQYJKoZIhvcNAQELBQADggEBAIIqxvWJH3ZiLc9hRc0pzQAwaIAmNrhQ 13 | 0U7sjLMjNjbzEQ/PXQcCjeggCDysVrz8JsLUhqOtnhnZg/9061FSDoI0ppPvcFtV 14 | snokgQl2NvLu3OZfSEhIxb8vJq7iUJkXNpnmr/zAVqASJ9mjyCK8hZ3a68Zv+HSx 15 | wNwMZ60EsacJn93vjCm10g2EEDaaSyvigvQjHr7QqIyf5HhqTeWxcnztGT1SOfC7 16 | IzAOCtmSJmj3KiHG5WYjlJvkIod4jBjO1okbzoe2AG4FG13dGeDj1W2WMnM/9Gon 17 | DBMvII6asXbTzVJE3McBE/ezNvPB+etpx3aaOW4POtULm9AvA0hNLSw= 18 | -----END CERTIFICATE REQUEST----- 19 | -------------------------------------------------------------------------------- /tools/cert/key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIEogIBAAKCAQEAoyn8W+rm16BrPQjLQgjpsHB6fy0+KmtyM519BnM9IvUydyn/ 3 | iaW6gjqow4gzN4iCYiSyq4WwsR2kqwwm0P3yR2w+yj3HcuWNcA0T1v1vewEb8Y69 4 | T/OkgLpCS86599CtR1aIhPQ3H41L47HzlwTWvu87Ko436pwOVhZ7vwKQuV5S4VMY 5 | xhilAAv9LcWQo+f6yAE+g8gc9s5xspRLBvgbbO2ZtQY+DT9SckHZ/Ilsmjdwcrsu 6 | xqLQrchamECuz2dIEbUxowdVfk3l73RSQa0LcOQg9AgkjSrLwlHo2wboozQp2kqW 7 | m8w9w02G9gjLqoWRsEhYByKTDwDPOa0FpbIWmwIDAQABAoIBAHo2OI+gosdfoPNW 8 | YuhTRLajiR05Bhc/44pFrB/osSI+Bk67Zmvzdn+U8FOE8Nfnp8FbO3i96lq/mVeF 9 | Ao4HqDFXIrDZFUs6JXaIVRPzQE0hx4xnHeWE2PKSkJW3ghPcee21Iwxy39cCPpWN 10 | 9KZpOXBKQEbfv4I64YIZ1RZ9FWnByjw8UT+8/a8LMVUxSRX+QfkJMbvmJ4rb3jGk 11 | wCBKd4qpO42L4JnglzVBdAkWSmLYiXrT9HH9R/wfIrnbSe6GylU9vjK0aT26/hb4 12 | QF2vcPEKifm4lGsEB3DLpNt9ISZiIhASJ502Yxa1jXcxyrGgQivRHsmFw2v2qp64 13 | V8zm3AECgYEA119npg7Llu2YbDPTVDNhLRu3l5EqFRbUZIB/RPf4XGFHdHEKKagT 14 | HJd9BGs9hIXAeAezKrkyvjmhru2NimDNKtsWlMrP4KEr4Y6nVfRhFufe2rOXKGQ/ 15 | Bb/QU0YVk6dPjw+iG15oPB9fgWOXmDqBIHXTHjQhltlcSXFXyiz+WMMCgYEAwfFd 16 | MVFtcaOYHKf+GAVZSTZozaNjxTMRM4Iry0oFS8kO6pIMMZHkMbxEc7f1sWC3KAvB 17 | Aq+5Mt0VfM8XQMBJtpm0363l3xMDqoA5rBVO4gIzsbPpZseqwmWJJeY0b9V+GAbM 18 | POl1XFtfpeGMj19wUB9SdW4D6+3p1BtCQcklrUkCgYBj08PuM4NodL6mwKrep2YO 19 | i39gkJep6MgPwYO8SxficfC150NnpZEeOpVm+/Iqv/hDaoZAclEz3PC1bUSi9FWE 20 | 3MItu4f5PZtiVEX50GlEPbuNMZsJzNVta8g7IQwVQYLd88gW2X6FB6G0Dp6Qn+WE 21 | TzjJEi7ThfKB1Dh17L8EEwKBgCiwsTLFuMac4i8w99imVqNLrRVn8GjRXAyIhROz 22 | xgSufFiup6xGxa/BpkL5F61Nc2ANh0M/BwYq6HU1JdXKAi0zdoVvgMkaviwplvAJ 23 | 0HEOsTXZX2DXB3adwvaWo+3KxxfXZUZqXNsxuJGfDtSN24yT5cMJf/0h/2snBPG0 24 | eBkxAoGAZPJjJMIjT/Ke1NoOJkFaI85XiWzKk6pr1aqvdS7slcN5h+cqrr2aldZl 25 | Zy417/gaPqGCzeb05cW5E71ecFT/QNpGLJwtj/xPnRDqM/aGr6/RxpzFxPQFSReG 26 | Vm5TYiZpPTYP9pohuz4JFRu4Lo5CvF5ZDeS+3TlsscYhWOyGAzo= 27 | -----END RSA PRIVATE KEY----- 28 | -------------------------------------------------------------------------------- /tools/http-server.js: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a unified server used in our testing for serving: 3 | * - html pages of this directory at /, like webrtc-client.html over http 4 | * - html pages of this directory at /, like webrtc-client.html over https 5 | * - RCML (REST) for Restcomm at /rcml. The logic for RCML is to return a Dial command towards Restcomm Client userX, where X is a increasing counter reaching up to client count and wrapping around so that continuous tests can be ran 6 | * 7 | * Command line: 8 | * $ node server.js [client count] [REST RCML port] [HTTP port for html] [HTTPS port for html] 9 | */ 10 | 11 | var nodeStatic = require('node-static'); 12 | var commandLineArgs = require('command-line-args'); 13 | var http = require('http'); 14 | var https = require('https'); 15 | var express = require('express'); 16 | var fs = require('fs'); 17 | 18 | var TAG = '[http-server] '; 19 | 20 | // TODO: replace with node-getopt 21 | var CLIENT_COUNT = 10; 22 | var RCML_PORT = 10512; 23 | var HTTP_PORT = 10510; 24 | var HTTPS_PORT = 10511; 25 | 26 | var cli = commandLineArgs([ 27 | { name: 'client-count', alias: 'c', type: Number, defaultValue: 10 }, 28 | { name: 'external-service-port', alias: 'p', type: Number, defaultValue: 10512 }, 29 | { name: 'external-service-client-prefix', alias: 'x', type: String, defaultValue: 'user' }, 30 | { name: 'web-app-port', alias: 'w', type: Number, defaultValue: 10510 }, 31 | { name: 'web-app-dir', alias: 'd', type: String, defaultValue: '.' }, 32 | { name: 'secure-web-app', alias: 's', type: Boolean, defaultValue: false }, 33 | { name: 'record-media', alias: 'm', type: Boolean, defaultValue: false }, 34 | { name: 'client-role', alias: 'r', type: String, defaultValue: 'passive' }, 35 | { name: 'help', alias: 'h' }, 36 | ]); 37 | 38 | var options = cli.parse(); 39 | if (options['help']) { 40 | cli.getUsage(); 41 | } 42 | //console.log('[server.js] Options: ' + JSON.stringify(options)); 43 | 44 | /* 45 | if (process.argv.length <= 2) { 46 | console.log('[server.js] Usage: $ server.js [client count] [REST RCML port] [HTTP port for html] [HTTPS port for html]'); 47 | process.exit(1); 48 | } 49 | if (process.argv[2]) { 50 | CLIENT_COUNT = process.argv[2]; 51 | } 52 | if (process.argv[3]) { 53 | RCML_PORT = process.argv[3]; 54 | } 55 | if (process.argv[4]) { 56 | HTTP_PORT = process.argv[4]; 57 | } 58 | if (process.argv[5]) { 59 | HTTPS_PORT = process.argv[5]; 60 | } 61 | */ 62 | 63 | //console.log('[server.js] Initializing http(s) server with ' + options[' + ' clients: \n\tRCML (REST) port: ' + RCML_PORT + ' \n\thttp (Webrtc App) port: ' + HTTP_PORT + ' \n\thttps (Webrtc App) port: ' + HTTPS_PORT); 64 | console.log(TAG + 'External service settings: \n\tclient count: ' + options['client-count'] + '\n\tport: ' + options['external-service-port'] + '\n\tclient prefix: ' + options['external-service-client-prefix'] + '\n\tclient role: ' + options['client-role'] + '\n\trecord media: ' + options['record-media']); 65 | console.log(TAG + 'Web app server settings: \n\tport: ' + options['web-app-port'] + '\n\tsecure: ' + options['secure-web-app'] + '\n\tserving contents of: ' + options['web-app-dir']); 66 | 67 | // -- Serve html pages over http 68 | var fileServer = new nodeStatic.Server(options['web-app-dir']); 69 | var app = null; 70 | 71 | if (!options['secure-web-app']) { 72 | app = http.createServer(function (req, res) { 73 | fileServer.serve(req, res); 74 | }).listen(options['web-app-port']); 75 | } 76 | else { 77 | // Options for https 78 | var secureOptions = { 79 | key: fs.readFileSync('cert/key.pem'), 80 | cert: fs.readFileSync('cert/cert.pem') 81 | }; 82 | 83 | // Serve html pages over https 84 | app = https.createServer(secureOptions, function (req, res) { 85 | fileServer.serve(req, res); 86 | }).listen(options['web-app-port']); 87 | } 88 | 89 | // -- Serve RCML with REST 90 | var app = express(); 91 | var id = 1; 92 | 93 | app.get('/rcml', function (req, res) { 94 | console.log('[server.js] Handing client ' + id); 95 | var rcml = '' 96 | if (options['client-role'] == 'passive') { 97 | // when webrtc client is passive the RCML should be active and make calls towards it 98 | //rcml = ' Welcome to RestComm, a TeleStax sponsored project.'; 99 | rcml = ' '; 119 | } 120 | 121 | res.set('Content-Type', 'text/xml'); 122 | res.send(rcml); 123 | }) 124 | 125 | app.listen(options['external-service-port']); 126 | -------------------------------------------------------------------------------- /tools/tmp/server.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # 3 | # IMPORTANT: this is no longer used by webrtc-test.py, since we had scaling 4 | # issues, so it has been superseded by http-server.js implemented in node js. 5 | # I'm just keeping this around in case we need it in the future 6 | # 7 | # This is a 'unified' server used in our testing for serving: 8 | # - RCML (REST) for Restcomm at /rcml. The logic for RCML is to return a Dial command towards Restcomm Client userX, where X is a increasing counter reaching up to client count and wrapping around so that continuous tests can be ran 9 | # - html pages of this directory at /, like webrtc-client.html over https/https 10 | # 11 | # Two threads are used. One to serve RCML to Restcomm and the other to server the web app html page over http/https 12 | # 13 | # Example invocations: 14 | # $ server.py --client-count 10 --external-service-port 10512 --secure-web-app --web-app-port 10510 15 | # $ server.py --client-count 10 --external-service-port 10512 --secure-web-app --web-app-port 10511 16 | # 17 | 18 | import argparse 19 | import SocketServer 20 | from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer 21 | import SimpleHTTPServer 22 | import ssl 23 | import random 24 | import re 25 | from socket import * 26 | 27 | # To use multiple processes instead we should use: 28 | # import multiprocessing 29 | # And replace ThreadPool with Pool 30 | from multiprocessing.dummy import Pool as ThreadPool 31 | 32 | # Globals 33 | TAG = '[server.py] ' 34 | usernamePrefix = None 35 | CLIENT_COUNT = None 36 | rcmlClientId = 1 37 | 38 | # Define a handler for the RCML REST server 39 | class httpHandler(BaseHTTPRequestHandler): 40 | def do_GET(self): 41 | #if self.path != '/rcml': 42 | if re.search('^/rcml.*', self.path) == None: 43 | self.send_response(403) 44 | self.send_header('Content-type', 'text/xml') 45 | self.end_headers() 46 | return 47 | 48 | self.send_response(200) 49 | self.send_header('Content-type', 'text/xml') 50 | self.end_headers() 51 | 52 | global rcmlClientId 53 | print '[server.py] Handing client ' + str(rcmlClientId) 54 | rcml = ' ' 55 | rcml += usernamePrefix; 56 | rcml += str(rcmlClientId) 57 | rcml += ' ' 58 | 59 | if (rcmlClientId == CLIENT_COUNT): 60 | print '[server.py] Reached ' + str(rcmlClientId) + ', wrapping around' 61 | rcmlClientId = 0 62 | 63 | rcmlClientId += 1 64 | 65 | self.wfile.write(rcml) 66 | return 67 | 68 | 69 | def threadFunction(dictionary): 70 | if 'secure' in dictionary.keys(): 71 | print TAG + 'Starting: ' + dictionary['type'] + ' thread, port: ' + str(dictionary['port']) + ', secure: ' + str(dictionary['secure']) 72 | else: 73 | print TAG + 'Starting: ' + dictionary['type'] + ' thread, port: ' + str(dictionary['port']) 74 | 75 | httpd = None 76 | serverAddress = ('', dictionary['port']) 77 | 78 | if dictionary['type'] == 'external-service': 79 | httpd = HTTPServer(serverAddress, httpHandler) 80 | # for now external service is already cleartext. If we want secure at some point follow the steps below to implement 81 | 82 | if dictionary['type'] == 'app-web-server': 83 | httpd = SocketServer.TCPServer(("", dictionary['port']), SimpleHTTPServer.SimpleHTTPRequestHandler) 84 | if 'secure' in dictionary.keys() and dictionary['secure']: 85 | httpd.socket = ssl.wrap_socket(httpd.socket, keyfile='cert/key.pem', certfile='cert/cert.pem', server_side=True) 86 | 87 | httpd.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) 88 | httpd.serve_forever() 89 | 90 | 91 | ## --------------- Main code --------------- ## 92 | 93 | parser = argparse.ArgumentParser() 94 | parser.add_argument('-c', '--client-count', dest = 'count', default = 10, type = int, help = 'Count of Webrtc clients expected to be used for test. This is needed to know how many different Restcomm Clients the RCML returned will target') 95 | parser.add_argument('--external-service-port', dest = 'externalServicePort', default = 10512, type = int, help = 'Which port will be used to serve RCML to Restcomm') 96 | parser.add_argument('--external-service-client-prefix', dest = 'externalServiceClientPrefix', default = 'user', help = 'The prefix for the Client noun of the RCML, like \'user\'') 97 | parser.add_argument('--web-app-port', dest = 'webAppPort', default = 10510, type = int, help = 'Which port will be used to serve web app pages') 98 | parser.add_argument('--secure-web-app', dest = 'secureWebApp', action = 'store_true', default = False, help = 'Should we use https for the web app?') 99 | args = parser.parse_args() 100 | 101 | print TAG + 'External service settings: \n\tclient count: ' + str(args.count) + '\n\tport: ' + str(args.externalServicePort) + '\n\tclient prefix: ' + args.externalServiceClientPrefix 102 | print TAG + 'Web app server settings: \n\tport: ' + str(args.webAppPort) + '\n\tsecure: ' + str(args.secureWebApp) 103 | 104 | CLIENT_COUNT = args.count 105 | usernamePrefix = args.externalServiceClientPrefix 106 | 107 | # Populate a list with browser thread ids and URLs for each client thread that will be spawned 108 | poolArgs = [ 109 | { 'type': 'external-service', 'port': args.externalServicePort }, 110 | { 'type': 'app-web-server', 'secure': args.secureWebApp, 'port': args.webAppPort }, 111 | ] 112 | 113 | # Make the Pool of workers 114 | pool = ThreadPool(2) 115 | # Open the urls in their own threads and return the results 116 | results = pool.map(threadFunction, poolArgs) 117 | # close the pool and wait for the work to finish 118 | pool.close() 119 | pool.join() 120 | -------------------------------------------------------------------------------- /tools/webrtc-test.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | # Main webrtc test tool 4 | # 5 | # TODOs: 6 | # 7 | # - Fix the unprovisioning functionality also remove the Restcomm Clients and Restcomm Number 8 | # - Make accountSid and authToken not required since we have introduced the --test-modes where we can configure if we want provisioning to take place or not 9 | # 10 | 11 | import argparse 12 | import sys 13 | import json 14 | import time 15 | import ssl 16 | import subprocess 17 | import os 18 | import re 19 | import urllib 20 | import urlparse 21 | import signal 22 | import datetime 23 | from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer 24 | from socket import * 25 | from threading import Thread 26 | 27 | # Notice that we are using the dummy module which is implemented with threads, 28 | # not multiple processes, as processes might be overkill in our situation (in 29 | # case for example we want to spawn hundredths) 30 | # 31 | # To use multiple processes instead we should use: 32 | # import multiprocessing 33 | # And replace ThreadPool with Pool 34 | from multiprocessing.dummy import Pool as ThreadPool 35 | 36 | # Selenium imports 37 | from selenium import webdriver 38 | from selenium.webdriver.common.keys import Keys 39 | from selenium.webdriver.chrome.options import Options 40 | from selenium.webdriver.common.desired_capabilities import DesiredCapabilities 41 | from selenium.webdriver.support import expected_conditions 42 | from selenium.webdriver.support.ui import WebDriverWait 43 | from selenium.webdriver.common.by import By 44 | import selenium.common.exceptions 45 | 46 | # Globals 47 | # Version 48 | VERSION = "0.3.4" 49 | # TAG for console logs 50 | TAG = '[restcomm-test] ' 51 | # Keep the nodejs process in a global var so that we can reference it after the tests are over to shut it down 52 | httpProcess = None 53 | # Used in non-selenium runs 54 | browserProcesses = list() 55 | # restcomm test modes. Which parts of the tool do we want executed (bitmap): 56 | # - 001: Spawn webrtc browsers 57 | # - 010: Start HTTP server for external service & web app 58 | # - 100: Do Restcomm provisioning/unprovisioning 59 | testModes = None 60 | # Command line args 61 | args = None 62 | # list containing a dictionary for each webrtc client browser we are spawning 63 | clients = None 64 | # number of browsers spawned so far 65 | totalBrowserCount = 0 66 | # log index 67 | logIndex = 0 68 | 69 | def threadFunction(dictionary): 70 | try: 71 | print TAG + 'browser thread #' + str(dictionary['id']) + ' Running test for URL: ' + dictionary['url'] 72 | 73 | chromeOptions = Options() 74 | # important: don't request permission for media 75 | chromeOptions.add_argument("--use-fake-ui-for-media-stream") 76 | # enable browser logging 77 | caps = DesiredCapabilities.CHROME 78 | #caps['loggingPrefs'] = {'browser': 'ALL', 'client': 'ALL', 'driver': 'ALL', 'performance': 'ALL', 'server': 'ALL'} 79 | caps['loggingPrefs'] = { 'browser':'ALL' } 80 | #driver = webdriver.Chrome(chrome_options = chromeOptions, desired_capabilities = caps, service_args = ["--verbose", "--log-path=chrome.log"]) 81 | driver = webdriver.Chrome(chrome_options = chromeOptions, desired_capabilities = caps) 82 | 83 | # navigate to web page 84 | driver.get(dictionary['url']) 85 | #print driver.title 86 | 87 | #print 'Waiting for condition to be met' 88 | #WebDriverWait(driver, 30).until(expected_conditions.text_to_be_present_in_element((By.ID,'log'), 'Connection ended')) 89 | # this is actually a hack to keep the browser open for n seconds. Putting the thread to sleep doesn't work and so far I haven't found a nice way to do that in Selenium 90 | WebDriverWait(driver, 300).until(expected_conditions.text_to_be_present_in_element((By.ID,'log'), 'Non existing text')) 91 | 92 | 93 | except selenium.common.exceptions.TimeoutException as ex: 94 | print TAG + 'EXCEPTION: browser thread #' + str(dictionary['id']) + ' Test timed out' 95 | except: 96 | print TAG + 'EXCEPTION: browser thread #' + str(dictionary['id']) + ' Unexpected exception: ', sys.exc_info()[0] 97 | return 98 | 99 | # print messages 100 | print TAG + 'browser thread #' + str(dictionary['id']) + ' Saving the logs' 101 | logBuffer = '' 102 | for entry in driver.get_log('browser'): 103 | # entry is a dictionary 104 | logBuffer += json.dumps(entry, indent = 3) 105 | 106 | logFile = open('browser#' + str(dictionary['id']) + '.log', 'a') 107 | logFile.write(logBuffer) 108 | logFile.close() 109 | 110 | print TAG + 'browser thread #' + str(dictionary['id']) + ' Closing Driver' 111 | driver.close() 112 | 113 | def signalHandler(signal, frame): 114 | print('User interrupted testing with SIGINT; bailing out') 115 | stopServer() 116 | sys.exit(0) 117 | 118 | # take a url and break it in protocol and transport counterparts 119 | def breakUrl(url): 120 | matches = re.search('(^.*?:\/\/)(.*$)', url) 121 | protocol = matches.group(1) 122 | transport = matches.group(2) 123 | return protocol, transport 124 | 125 | # Return the account base Restcomm URL, like http://ACae6e420f425248d6a26948c17a9e2acf:0d01c95aac798602579fe08fc2461036@127.0.0.1:8080/restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf, 126 | # from base URL (i.e. http://127.0.0.1:8080), account sid and auth token 127 | def restBaseUrlFromCounterparts(accountSid, authToken, restcommUrl): 128 | # Need to break URL in protocol and transport parts so that we can put account sid and auth token in between 129 | matches = re.search('(^.*?:\/\/)(.*$)', restcommUrl) 130 | #protocol = matches.group(1) 131 | #transport = matches.group(2) 132 | protocol, transport = breakUrl(restcommUrl) 133 | return protocol + accountSid + ':' + authToken + '@' + transport + '/restcomm/2012-04-24/Accounts/' + accountSid 134 | 135 | # curl will break if we target an https server that has self signed certificate. Let's always use -k (avoid checks for cert) when targeting https 136 | def curlSecureOptionsIfApplicable(restcommUrl): 137 | protocol, transport = breakUrl(restcommUrl) 138 | if protocol == 'https://': 139 | return '-k' 140 | else: 141 | return '' 142 | 143 | # Provision Restcomm Number for external service via REST call 144 | def provisionPhoneNumber(phoneNumber, externalServiceUrl, accountSid, authToken, restcommUrl): 145 | print TAG + "Provisioning phone number " + phoneNumber + ' and linking it with Voice URL: ' + externalServiceUrl 146 | devnullFile = open(os.devnull, 'w') 147 | # Need to break URL in protocol and transport parts so that we can put account sid and auth token in between 148 | matches = re.search('(^.*?:\/\/)(.*$)', restcommUrl) 149 | protocol = matches.group(1) 150 | transport = matches.group(2) 151 | postData = { 152 | 'PhoneNumber': phoneNumber, 153 | 'VoiceUrl': externalServiceUrl, 154 | 'VoiceMethod': 'GET', 155 | 'FriendlyName': 'Load Testing App', 156 | 'isSIP' : 'true', 157 | } 158 | #cmd = 'curl -X POST ' + restBaseUrlFromCounterparts(accountSid, authToken, restcommUrl) + '/IncomingPhoneNumbers.json -d PhoneNumber=' + phoneNumber + ' -d VoiceUrl=' + externalServiceUrl + ' -d FriendlyName=LoadTestingApp -d isSIP=true' 159 | cmd = 'curl ' + curlSecureOptionsIfApplicable(restcommUrl) + ' -X POST ' + restBaseUrlFromCounterparts(accountSid, authToken, restcommUrl) + '/IncomingPhoneNumbers.json -d ' + urllib.urlencode(postData) 160 | print TAG + cmd 161 | #subprocess.call(cmd.split(), stdout = devnullFile, stderr = devnullFile) 162 | # remember this runs the command synchronously 163 | subprocess.call(cmd.split()) 164 | 165 | 166 | # Provision Restcomm Clients via REST call 167 | # count: number of Clients to provision 168 | # accountSid: Restcomm accountSid, like: ACae6e420f425248d6a26948c17a9e2acf 169 | # authToken: Restcomm authToken, like: 0a01c34aac72a432579fe08fc2461036 170 | # restcommUrl: Restcomm URL, like: http://127.0.0.1:8080 171 | def provisionClients(count, accountSid, authToken, restcommUrl, usernamePrefix, password): 172 | print TAG + "Provisioning " + str(count) + " Restcomm Clients" 173 | devnullFile = open(os.devnull, 'w') 174 | # Need to break URL in protocol and transport parts so that we can put account sid and auth token in between 175 | matches = re.search('(^.*?:\/\/)(.*$)', restcommUrl) 176 | protocol = matches.group(1) 177 | transport = matches.group(2) 178 | for i in range(1, count + 1): 179 | postData = { 180 | 'Login': usernamePrefix + str(i), 181 | 'Password': password, 182 | } 183 | #cmd = 'curl -X POST ' + restBaseUrlFromCounterparts(accountSid, authToken, restcommUrl) + '/Clients.json -d Login=user' + str(i) + ' -d Password=1234' 184 | cmd = 'curl ' + curlSecureOptionsIfApplicable(restcommUrl) + ' -X POST ' + restBaseUrlFromCounterparts(accountSid, authToken, restcommUrl) + '/Clients.json -d ' + urllib.urlencode(postData) 185 | #system(cmd) 186 | print TAG + cmd 187 | #subprocess.call(cmd.split(), stdout = devnullFile, stderr = devnullFile) 188 | subprocess.call(cmd.split()) 189 | 190 | def startServer(count, clientUrl, externalServiceUrl, usernamePrefix, clientWebAppDir, clientRole, recordMedia): 191 | print TAG + 'Starting http server to handle both http/https request for the webrtc-client web page, and RCML REST requests from Restcomm' 192 | 193 | externalServicePort = '80' 194 | externalServiceParsedUrl = urlparse.urlparse(externalServiceUrl); 195 | if externalServiceParsedUrl.port: 196 | externalServicePort = externalServiceParsedUrl.port 197 | 198 | webAppPort = '80' 199 | clientParsedUrl = urlparse.urlparse(clientUrl); 200 | if (clientParsedUrl.port): 201 | webAppPort = clientParsedUrl.port 202 | 203 | secureArg = '' 204 | if clientParsedUrl.scheme == 'https': 205 | secureArg = '--secure-web-app' 206 | 207 | recordMediaArg = '' 208 | if recordMedia: 209 | recordMediaArg = '--record-media' 210 | 211 | # Make a copy of the current environment 212 | envDictionary = dict(os.environ) 213 | # Add the nodejs path, as it isn't found when we run as root 214 | envDictionary['NODE_PATH'] = '/usr/local/lib/node_modules' 215 | #cmd = 'server.js ' + str(count) + ' 10512 10510 10511' 216 | cmd = 'node http-server.js --client-count ' + str(count) + ' --external-service-port ' + str(externalServicePort) + ' --external-service-client-prefix ' + usernamePrefix + ' --web-app-port ' + str(webAppPort) + ' ' + secureArg + ' --web-app-dir ' + clientWebAppDir + ' --client-role ' + clientRole + ' ' + recordMediaArg; 217 | # We want it to run in the background 218 | #os.system(cmd) 219 | #subprocess.call(cmd.split(), env = envDictionary) 220 | #print "--- CMD: " + cmd 221 | global httpProcess 222 | httpProcess = subprocess.Popen(cmd.split(), env = envDictionary) 223 | #httpProcess = subprocess.Popen(cmd.split()) 224 | print TAG + 'PID for http server: ' + str(httpProcess.pid) 225 | 226 | # TODO: Not finished yet 227 | def unprovisionClients(count, accountSid, authToken, restcommUrl): 228 | print TAG + "(Not implemented yet) Unprovisioning " + str(count) + " Restcomm Clients" 229 | #for i in range(1, count + 1): 230 | # cmd = 'curl ' + curlSecureOptionsIfApplicable(restcommUrl) + ' -X DELETE http://' + accountSid + ':' + authToken + '@' + transport + '/restcomm/2012-04-24/Accounts/' + accountSid + '/Clients.json -d Login=user' + str(i) + ' -d Password=1234' 231 | # ... 232 | 233 | def stopServer(): 234 | if httpProcess: 235 | print TAG + 'Stopping http server' 236 | httpProcess.terminate() 237 | 238 | def globalSetup(dictionary): 239 | print TAG + "Setting up tests" 240 | 241 | global testModes 242 | # if user asked for restcomm provisioning/unprovisioning (i.e. testModes = 001 binary) 243 | if testModes & 1: 244 | # Provision Restcomm with the needed Clients 245 | provisionPhoneNumber(dictionary['phone-number'], dictionary['external-service-url'], dictionary['account-sid'], dictionary['auth-token'], dictionary['restcomm-base-url']) 246 | 247 | if dictionary['client-role'] == 'passive': 248 | # Provision Restcomm with the needed Clients only when in passive mode 249 | provisionClients(dictionary['count'], dictionary['account-sid'], dictionary['auth-token'], dictionary['restcomm-base-url'], dictionary['username-prefix'], dictionary['password']) 250 | 251 | # if user asked for http server to be started (i.e. testModes = 010 binary) 252 | if testModes & 2: 253 | # Start the unified server script to serve both RCML (REST) and html page for webrtc clients to connect to 254 | startServer(dictionary['count'], dictionary['client-url'], dictionary['external-service-url'], dictionary['username-prefix'], dictionary['client-web-app-dir'], dictionary['client-role'], dictionary['record-media']) 255 | 256 | def globalTeardown(dictionary): 257 | print TAG + "Tearing down tests" 258 | 259 | global testModes 260 | # if user asked for restcomm provisioning/unprovisioning (i.e. testModes = 001 binary) 261 | if testModes & 1: 262 | # Provision Restcomm with the needed Clients 263 | unprovisionClients(dictionary['count'], dictionary['account-sid'], dictionary['auth-token'], dictionary['restcomm-base-url']) 264 | 265 | # if user asked for http server to be started (i.e. testModes = 010 binary) 266 | if testModes & 2: 267 | # Start the unified server script to serve both RCML (REST) and html page for webrtc clients to connect to 268 | stopServer() 269 | 270 | # Check if a command exists 271 | def commandExists(cmd): 272 | for path in os.environ["PATH"].split(os.pathsep): 273 | path = path.strip('"') 274 | execFile = os.path.join(path, cmd) 275 | if os.path.isfile(execFile) and os.access(execFile, os.X_OK): 276 | return True 277 | return False 278 | 279 | # Check if a process is running 280 | def processRunning(cmd): 281 | output = subprocess.check_output('ps ax'.split()) 282 | for line in output.splitlines(): 283 | if re.search('Xvfb', line): 284 | return True 285 | return False 286 | 287 | # Spawn browsers for all 'clients' 288 | def spawnBrowsers(browserCommand, clients, totalBrowserCount, logIndex, headless, display, threaded): 289 | envDictionary = None 290 | cmdList = None 291 | #global totalBrowserCount 292 | #global logIndex 293 | #totalBrowserCount += len(clients) 294 | 295 | # TODO: we could make work both in Linux/Darwin but we need extra handling here 296 | #osName = subprocess.check_output(['uname']) 297 | if re.search('chrom', browserCommand, re.IGNORECASE): 298 | envDictionary = None 299 | # Make a copy of the current environment 300 | envDictionary = dict(os.environ) 301 | # Set the chrome log file 302 | #envDictionary['CHROME_LOG_FILE'] = 'browser#' + str(client['id']) + '.log' 303 | #envDictionary['CHROME_LOG_FILE'] = 'chrome.log.' + str(datetime.datetime.utcnow()).replace(' ', '.') 304 | envDictionary['CHROME_LOG_FILE'] = 'chrome.log.' + str(logIndex) 305 | #logIndex += 1 306 | if headless: 307 | envDictionary['DISPLAY'] = display 308 | 309 | cmdList = [ 310 | browserCommand, 311 | #'--user-data-dir=' + str(client['id']), 312 | #'--incognito', 313 | #'--new-window', 314 | '--no-first-run', # even if it's the first time Chrome is starting up avoid showing the welcome message, which needs user intervention and causes issues on headless environment 315 | '--enable-logging', # enable logging at the specified file 316 | #'--vmodule=webrtc-client*', # not tested 317 | '--use-fake-ui-for-media-stream', # don't require user to grant permission for microphone and camera 318 | '--use-fake-device-for-media-stream', # don't use real microphone and camera for media, but generate fake media 319 | # Didn't work (no idea why): 320 | #'--use-file-for-fake-audio-capture=../resources/wav/audio_long16.wav', # use specified wave file for fake audio instead of default beeping sound 321 | # Didn't work: 322 | #'--use-file-for-fake-audio-capture=' + os.getcwd().rstrip() + '/../resources/wav/audio_long16.wav', # use specified wave file for fake audio instead of default beeping sound 323 | # Worked: 324 | '--use-file-for-fake-audio-capture=/home/ubuntu/Downloads/webrtc-test/resources/wav/audio_long16.wav', # use specified wave file for fake audio instead of default beeping sound 325 | '--ignore-certificate-errors', # don't check server certificate for validity, again to avoid user intervention 326 | #'--process-per-tab', # not tested 327 | ] 328 | 329 | else: 330 | # Make a copy of the current environment 331 | envDictionary = None 332 | envDictionary = dict(os.environ) 333 | # Set the chrome log file 334 | #envDictionary['NSPR_LOG_FILE'] = 'browser#' + str(client['id']) + '.log' 335 | envDictionary['NSPR_LOG_FILE'] = 'firefox.log.' + str(logIndex) 336 | # not sure why but this is the 'module' name for the web console and '5' to get all levels 337 | envDictionary['NSPR_LOG_MODULES'] = 'timestamp,textrun:5' 338 | #envDictionary['NSPR_LOG_MODULES'] = 'timestamp,all:3' 339 | if headless: 340 | envDictionary['DISPLAY'] = display 341 | # Firefox 342 | cmdList = [ 343 | browserCommand, 344 | '--jsconsole', # without this I'm not getting proper logs for some weird reason 345 | #'--args', 346 | #'--new-tab', 347 | #client['url'], 348 | ] 349 | 350 | # add all the links in the command after the options 351 | for client in clients: 352 | cmdList.append(client['url']) 353 | 354 | separator = ' ' 355 | print TAG + 'Spawning ' + str(len(clients)) + ' browsers (total: ' + str(totalBrowserCount) + '). Command: ' + separator.join(cmdList) 356 | devnullFile = open(os.devnull, 'w') 357 | # We want it to run in the background 358 | if threaded: 359 | subprocess.Popen(cmdList, env = envDictionary, stdout = devnullFile, stderr = devnullFile) 360 | else: 361 | browserProcess = subprocess.Popen(cmdList, env = envDictionary, stdout = devnullFile, stderr = devnullFile) 362 | 363 | # Define a handler for the respawn HTTP server 364 | class httpHandler(BaseHTTPRequestHandler): 365 | def do_GET(self): 366 | responseText = None 367 | if re.search('^/respawn-user.*', self.path) == None: 368 | self.send_response(501) 369 | responseText = 'Not Implemented, please use /respawn-user' 370 | else: 371 | self.send_response(200) 372 | # query string for the GET request 373 | qsDictionary = None 374 | if '?' in self.path: 375 | qsDictionary = urlparse.parse_qs(urlparse.urlparse(self.path).query) 376 | else: 377 | print '--- Not found ? in request' 378 | return 379 | 380 | print 'Received respawn request: ' + json.dumps(qsDictionary, indent = 3) 381 | 382 | global totalBrowserCount 383 | global logIndex 384 | # check which 'client' the request is for 385 | for client in clients: 386 | if client['id'] == qsDictionary['username'][0]: 387 | respawnClients = list() 388 | respawnClients.append(client) 389 | totalBrowserCount += len(respawnClients) 390 | spawnBrowserThread = Thread(target = spawnBrowsers, args = (args.clientBrowserExecutable, respawnClients, totalBrowserCount, logIndex, args.clientHeadless, args.clientHeadlessDisplay, False)) 391 | spawnBrowserThread.start() 392 | logIndex += 1 393 | #spawnBrowsers(args.clientBrowserExecutable, respawnClients, totalBrowserCount, logIndex, args.clientHeadless, args.clientHeadlessDisplay, True) 394 | responseText = 'Spawning new browser with username: ' + qsDictionary['username'][0] 395 | 396 | self.send_header('Content-type', 'text/html') 397 | # Allow requests from any origin (CORS) 398 | self.send_header("Access-Control-Allow-Origin", self.headers.get('Origin')) 399 | self.end_headers() 400 | self.wfile.write(responseText) 401 | 402 | return 403 | 404 | # HTTP server listening for AJAX requests and spawning new browsers when existing browsers finish with the call and close 405 | def startRespawnServer(respawnUrl): 406 | 407 | respawnPort = '80' 408 | respawnParsedUrl = urlparse.urlparse(respawnUrl); 409 | if respawnParsedUrl.port: 410 | respawnPort = respawnParsedUrl.port 411 | 412 | print TAG + 'Starting respawn HTTP server at port: ' + str(respawnPort) 413 | 414 | httpd = None 415 | serverAddress = ('', respawnPort) 416 | httpd = HTTPServer(serverAddress, httpHandler) 417 | if respawnParsedUrl.scheme == 'https': 418 | httpd.socket = ssl.wrap_socket(httpd.socket, keyfile='cert/key.pem', certfile='cert/cert.pem', server_side=True) 419 | httpd.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) 420 | 421 | size = httpd.socket.getsockopt(SOL_SOCKET, SO_RCVBUF) 422 | print 'Socket recv buffer size: ' + str(size) 423 | httpd.socket.setsockopt(SOL_SOCKET, SO_RCVBUF, size * 2) 424 | newSize = httpd.socket.getsockopt(SOL_SOCKET, SO_RCVBUF) 425 | print 'Socket recv buffer size after set: ' + str(newSize) 426 | 427 | httpd.serve_forever() 428 | 429 | 430 | ## --------------- Main code --------------- ## 431 | parser = argparse.ArgumentParser() 432 | parser.add_argument('-c', '--client-count', dest = 'count', default = 10, type = int, help = 'Count of Webrtc clients spawned for the test') 433 | parser.add_argument('--client-url', dest = 'clientUrl', default = 'http://127.0.0.1:10510/webrtc-client.html', help = 'Webrtc clients target URL, like \'http://127.0.0.1:10510/webrtc-client.html\'') 434 | parser.add_argument('--client-web-app-dir', dest = 'clientWebAppDir', default = '.', help = 'Directory where the web app resides, so that our http server knows what to serve, like \'../webrtc-load-tests\'') 435 | parser.add_argument('--client-register-ws-url', dest = 'registerWsUrl', default = 'ws://127.0.0.1:5082', help = 'Webrtc clients target websocket URL for registering, like \'ws://127.0.0.1:5082\'') 436 | parser.add_argument('--client-register-domain', dest = 'registerDomain', default = '127.0.0.1', help = 'Webrtc clients domain for registering, like \'127.0.0.1\'') 437 | parser.add_argument('--client-username-prefix', dest = 'usernamePrefix', default = 'user', help = 'User prefix for the clients, like \'user\'') 438 | parser.add_argument('--client-password', dest = 'password', default = '1234', help = 'Password for the clients, like \'1234\'') 439 | parser.add_argument('--client-browser-executable', dest = 'clientBrowserExecutable', default = 'chromium-browser', help = 'Browser executable for the test. Can be full path (if not in PATH), like \'/Applications/Firefox.app/Contents/MacOS/firefox-bin\', \'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\' (for OSX) or just executable, like \'firefox\', \'chromium-browser\' (for GNU/Linux), default is \'chromium-browser\'') 440 | parser.add_argument('--client-headless', dest = 'clientHeadless', action = 'store_true', default = False, help = 'Should we use a headless browser?') 441 | parser.add_argument('--client-respawn', dest = 'respawn', action = 'store_true', default = False, help = 'Should we use respawn browser logic? This means a. starting an http server to listen for respawn requests (see --client-respawn-url) and b. tell the clients to close the tabs after done with the call scenario') 442 | parser.add_argument('--client-respawn-url', dest = 'respawnUrl', default = 'http://127.0.0.1:10511/respawn-user', help = 'Webrtc clients respawn URL to be notified when the call is over, like \'http://127.0.0.1:10511/respawn-user\'') 443 | parser.add_argument('--client-headless-x-display', dest = 'clientHeadlessDisplay', default = ':99', help = 'When using headless, which virtual X display to use when setting DISPLAY env variable. Default is \':99\'') 444 | parser.add_argument('--client-role', dest = 'clientRole', default = 'passive', help = 'Role for the client. When \'active\' it makes a call to \'--target-sip-uri\'. When \'passive\' it waits for incoming call. Default is \'passive\'') 445 | parser.add_argument('--client-target-uri', dest = 'clientTargetUri', default = '+1234@127.0.0.1', help = 'Client target URI when \'--client-role\' is \'active\' (it\'s actually a SIP URI without the \'sip:\' part. Default is \'+1234@127.0.0.1\'') 446 | parser.add_argument('--restcomm-base-url', dest = 'restcommBaseUrl', default = 'http://127.0.0.1:8080', help = 'Restcomm instance base URL, like \'http://127.0.0.1:8080\'') 447 | parser.add_argument('--restcomm-account-sid', dest = 'accountSid', required = True, help = 'Restcomm accound Sid, like \'ACae6e420f425248d6a26948c17a9e2acf\'') 448 | parser.add_argument('--restcomm-auth-token', dest = 'authToken', required = True, help = 'Restcomm auth token, like \'0a01c34aac72a432579fe08fc2461036\'') 449 | parser.add_argument('--restcomm-phone-number', dest = 'phoneNumber', default = '+5556', help = 'Restcomm phone number to provision and link with external service, like \'+5556\'') 450 | parser.add_argument('--restcomm-external-service-url', dest = 'externalServiceUrl', default = 'http://127.0.0.1:10512/rcml', help = 'External service URL for Restcomm to get RCML from, like \'http://127.0.0.1:10512/rcml\'') 451 | parser.add_argument('--restcomm-record-media', dest = 'recordMedia', action = 'store_true', default = False, help = 'Should Restcomm create recordings for the calls? Default \'false\'') 452 | parser.add_argument('--test-modes', dest = 'testModes', default = 7, type = int, help = 'Testing modes for the load test. Which parts of the tool do we want to run? Provisioning, HTTP server, client browsers or any combination of those. This is a bitmap where binary 001 (i.e. 1) means to do provisioning unprovisioning, binary 010 (i.e. 2) means start HTTP(S) server and binary 100 (i.e. 4) means to spawn webrtb browsers. Default is binary 111 (i.e. 7) which means to do all the above') 453 | parser.add_argument('--version', action = 'version', version = 'restcomm-test.py ' + VERSION) 454 | 455 | args = parser.parse_args() 456 | 457 | print TAG + 'Webrtc clients settings: \n\tcount: ' + str(args.count) + '\n\ttarget URL: ' + args.clientUrl + '\n\tregister websocket url: ' + args.registerWsUrl + '\n\tregister domain: ' + args.registerDomain + '\n\tusername prefix: ' + args.usernamePrefix + '\n\tpassword: ' + args.password + '\n\tbrowser executable: ' + args.clientBrowserExecutable + '\n\theadless: ' + str(args.clientHeadless) + '\n\theadless X display: ' + args.clientHeadlessDisplay + '\n\trespawn client browsers: ' + str(args.respawn) + '\n\trespawn url: ' + args.respawnUrl + '\n\tclient role: ' + args.clientRole + '\n\tclient target SIP URI: ' + args.clientTargetUri 458 | print TAG + 'Restcomm instance settings: \n\tbase URL: ' + args.restcommBaseUrl + '\n\taccount sid: ' + args.accountSid + '\n\tauth token: ' + args.authToken + '\n\tphone number: ' + args.phoneNumber + '\n\texternal service URL: ' + args.externalServiceUrl 459 | print TAG + 'Testing modes: ' + str(args.testModes) 460 | 461 | # assign to global to be able to use from functions 462 | testModes = args.testModes 463 | 464 | # Let's handle sigint so the if testing is interrupted we still cleanup 465 | signal.signal(signal.SIGINT, signalHandler) 466 | 467 | globalSetup({ 468 | 'count': args.count, 469 | 'client-url': args.clientUrl, 470 | 'username-prefix': args.usernamePrefix, 471 | 'password': args.password, 472 | 'account-sid': args.accountSid, 473 | 'auth-token': args.authToken, 474 | 'restcomm-base-url': args.restcommBaseUrl, 475 | 'phone-number': args.phoneNumber, 476 | 'external-service-url': args.externalServiceUrl, 477 | 'client-web-app-dir': args.clientWebAppDir, 478 | 'client-role': args.clientRole, 479 | 'record-media': args.recordMedia, 480 | }) 481 | 482 | # Populate a list with browser thread ids and URLs for each client thread that will be spawned 483 | clients = list() 484 | for i in range(1, args.count + 1): 485 | GETData = { 486 | 'username': args.usernamePrefix + str(i), 487 | 'password': args.password, 488 | 'register-ws-url': args.registerWsUrl, 489 | 'register-domain': args.registerDomain, 490 | 'fake-media': str(args.clientHeadless).lower(), 491 | 'role': args.clientRole, 492 | } 493 | if args.respawn: 494 | GETData['respawn-url'] = args.respawnUrl; 495 | GETData['close-on-end'] = 'true'; 496 | #if args.clientRole == 'active': 497 | GETData['call-destination'] = args.clientTargetUri; 498 | 499 | clients.append({ 500 | 'id': GETData['username'], 501 | 'url' : args.clientUrl + '?' + urllib.urlencode(GETData) 502 | }) 503 | 504 | browserProcess = None 505 | # if user asked for browsers to be spawned (i.e. testModes = 100 binary) 506 | if testModes & 4: 507 | if args.clientHeadless: 508 | if not commandExists('Xvfb'): 509 | # Check if Xvfb exists 510 | print 'ERROR: Running in headless mode but Xvfb does not exist' 511 | stopServer() 512 | sys.exit(1) 513 | 514 | if not processRunning('Xvfb'): 515 | print 'ERROR: Running in headless mode but Xvfb is not running' 516 | stopServer() 517 | sys.exit(1) 518 | 519 | useSelenium = False; 520 | if useSelenium: 521 | print TAG + 'Spawning ' + str(args.count) + ' tester threads' 522 | # Make the Pool of workers 523 | pool = ThreadPool(args.count) 524 | # Open the urls in their own threads and return the results 525 | try: 526 | results = pool.map(threadFunction, clients) 527 | except: 528 | print TAG + 'EXCEPTION: pool.map() failed. Unexpected exception: ', sys.exc_info()[0] 529 | 530 | # Close the pool and wait for the work to finish 531 | pool.close() 532 | pool.join() 533 | else: 534 | # No selenium, spawn browsers manually (seems to scale better than selenium) 535 | #global totalBrowserCount 536 | #global logIndex 537 | # check which 'client' the request is for 538 | totalBrowserCount += len(clients) 539 | spawnBrowsers(args.clientBrowserExecutable, clients, totalBrowserCount, logIndex, args.clientHeadless, args.clientHeadlessDisplay, False) 540 | logIndex += 1 541 | 542 | # Start the respawn server which monitors if browsers are closing after handling call scenario and creates new in their place so that load testing can carry on 543 | if args.respawn: 544 | startRespawnServer(args.respawnUrl) 545 | 546 | print TAG + 'Please start call scenarios. Press Ctrl-C to stop ...' 547 | 548 | # raw_input doesn't exist in 3.0 and inputString issues an error in 2.7 549 | if (sys.version_info < (3, 0)): 550 | inputString = raw_input(TAG + 'Press any key to stop the test...\n') 551 | else: 552 | inputString = input(TAG + 'Press any key to stop the test...') 553 | 554 | # if user asked for browsers to be spawned (i.e. testModes = 100 binary) 555 | if testModes & 4: 556 | if not useSelenium: 557 | print TAG + "Stopping browser" 558 | browserProcess.kill() 559 | 560 | globalTeardown({ 561 | 'count': args.count, 562 | 'username': args.password, 563 | 'password': args.password, 564 | 'account-sid': args.accountSid, 565 | 'auth-token': args.authToken, 566 | 'restcomm-base-url': args.restcommBaseUrl, 567 | 'phone-number': args.phoneNumber, 568 | 'external-service-url': args.externalServiceUrl 569 | }) 570 | -------------------------------------------------------------------------------- /webrtc-load-tests/README.md: -------------------------------------------------------------------------------- 1 | ## Preparations ## 2 | 3 | Before starting sipp traffic you first need to start webrtc-test.py testing tool which will spawn the webrtc test app in the browsers and register webrtc clients that will be the recipients of the calls. Please refer to root README.md at https://github.com/RestComm/webrtc-test for more details 4 | 5 | ## How to execute test ## 6 | 7 | The way this works is that sipp forwards SIP traffic to a Restcomm number, in this example +5556 (notice that you can use any tool you like to generate traffic towards Restcomm; we are using Sipp as an example). That number is linked to a Restcomm App which distributes the calls to all registered webrtc clients. 8 | 9 | ``` 10 | $ sudo sipp -sf webrtc-sipp-client.xml -s : -mi : -l 50 -m 1000 -r 2 -trace_screen -trace_err -recv_timeout 5000 -nr -t u1 11 | ``` 12 | 13 | Example: 14 | 15 | ``` 16 | $ sudo sipp -sf webrtc-sipp-client.xml -s +5556 10.33.207.119:5080 -mi 10.33.207.119:5090 -l 50 -m 1000 -r 2 -trace_screen -trace_err -recv_timeout 5000 -nr -t u1 17 | ``` 18 | 19 | -------------------------------------------------------------------------------- /webrtc-load-tests/scripts/adapter.js: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014, The WebRTC project authors. All rights reserved. 2 | // 3 | // Redistribution and use in source and binary forms, with or without 4 | // modification, are permitted provided that the following conditions are 5 | // met: 6 | // 7 | // * Redistributions of source code must retain the above copyright 8 | // notice, this list of conditions and the following disclaimer. 9 | // 10 | // * Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in 12 | // the documentation and/or other materials provided with the 13 | // distribution. 14 | // 15 | // * Neither the name of Google nor the names of its contributors may 16 | // be used to endorse or promote products derived from this software 17 | // without specific prior written permission. 18 | // 19 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 20 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 21 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 22 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 23 | // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 24 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 25 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 26 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 27 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | 31 | /* More information about these options at jshint.com/docs/options */ 32 | /* jshint browser: true, camelcase: true, curly: true, devel: true, 33 | eqeqeq: true, forin: false, globalstrict: true, node: true, 34 | quotmark: single, undef: true, unused: strict */ 35 | /* global mozRTCIceCandidate, mozRTCPeerConnection, Promise, 36 | mozRTCSessionDescription, webkitRTCPeerConnection, MediaStreamTrack */ 37 | /* exported requestUserMedia */ 38 | 39 | 'use strict'; 40 | 41 | var getUserMedia = null; 42 | var attachMediaStream = null; 43 | var reattachMediaStream = null; 44 | var webrtcDetectedBrowser = null; 45 | var webrtcDetectedVersion = null; 46 | var webrtcMinimumVersion = null; 47 | var webrtcUtils = { 48 | log: function() { 49 | // suppress console.log output when being included as a module. 50 | if (typeof module !== 'undefined' || 51 | typeof require === 'function' && typeof define === 'function') { 52 | return; 53 | } 54 | console.log.apply(console, arguments); 55 | } 56 | }; 57 | 58 | if (typeof window === 'object') { 59 | if (window.HTMLMediaElement && 60 | !('srcObject' in window.HTMLMediaElement.prototype)) { 61 | // Shim the srcObject property, once, when HTMLMediaElement is found. 62 | Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', { 63 | get: function() { 64 | // If prefixed srcObject property exists, return it. 65 | // Otherwise use the shimmed property, _srcObject 66 | return 'mozSrcObject' in this ? this.mozSrcObject : this._srcObject; 67 | }, 68 | set: function(stream) { 69 | if ('mozSrcObject' in this) { 70 | this.mozSrcObject = stream; 71 | } else { 72 | // Use _srcObject as a private property for this shim 73 | this._srcObject = stream; 74 | // TODO: revokeObjectUrl(this.src) when !stream to release resources? 75 | this.src = URL.createObjectURL(stream); 76 | } 77 | } 78 | }); 79 | } 80 | // Proxy existing globals 81 | getUserMedia = window.navigator && window.navigator.getUserMedia; 82 | } 83 | 84 | // Attach a media stream to an element. 85 | attachMediaStream = function(element, stream) { 86 | element.srcObject = stream; 87 | }; 88 | 89 | reattachMediaStream = function(to, from) { 90 | to.srcObject = from.srcObject; 91 | }; 92 | 93 | if (typeof window === 'undefined' || !window.navigator) { 94 | webrtcUtils.log('This does not appear to be a browser'); 95 | webrtcDetectedBrowser = 'not a browser'; 96 | } else if (navigator.mozGetUserMedia && window.mozRTCPeerConnection) { 97 | webrtcUtils.log('This appears to be Firefox'); 98 | 99 | webrtcDetectedBrowser = 'firefox'; 100 | 101 | // the detected firefox version. 102 | webrtcDetectedVersion = 103 | parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10); 104 | 105 | // the minimum firefox version still supported by adapter. 106 | webrtcMinimumVersion = 31; 107 | 108 | // The RTCPeerConnection object. 109 | window.RTCPeerConnection = function(pcConfig, pcConstraints) { 110 | if (webrtcDetectedVersion < 38) { 111 | // .urls is not supported in FF < 38. 112 | // create RTCIceServers with a single url. 113 | if (pcConfig && pcConfig.iceServers) { 114 | var newIceServers = []; 115 | for (var i = 0; i < pcConfig.iceServers.length; i++) { 116 | var server = pcConfig.iceServers[i]; 117 | if (server.hasOwnProperty('urls')) { 118 | for (var j = 0; j < server.urls.length; j++) { 119 | var newServer = { 120 | url: server.urls[j] 121 | }; 122 | if (server.urls[j].indexOf('turn') === 0) { 123 | newServer.username = server.username; 124 | newServer.credential = server.credential; 125 | } 126 | newIceServers.push(newServer); 127 | } 128 | } else { 129 | newIceServers.push(pcConfig.iceServers[i]); 130 | } 131 | } 132 | pcConfig.iceServers = newIceServers; 133 | } 134 | } 135 | return new mozRTCPeerConnection(pcConfig, pcConstraints); // jscs:ignore requireCapitalizedConstructors 136 | }; 137 | 138 | // The RTCSessionDescription object. 139 | if (!window.RTCSessionDescription) { 140 | window.RTCSessionDescription = mozRTCSessionDescription; 141 | } 142 | 143 | // The RTCIceCandidate object. 144 | if (!window.RTCIceCandidate) { 145 | window.RTCIceCandidate = mozRTCIceCandidate; 146 | } 147 | 148 | // getUserMedia constraints shim. 149 | getUserMedia = function(constraints, onSuccess, onError) { 150 | var constraintsToFF37 = function(c) { 151 | if (typeof c !== 'object' || c.require) { 152 | return c; 153 | } 154 | var require = []; 155 | Object.keys(c).forEach(function(key) { 156 | if (key === 'require' || key === 'advanced' || key === 'mediaSource') { 157 | return; 158 | } 159 | var r = c[key] = (typeof c[key] === 'object') ? 160 | c[key] : {ideal: c[key]}; 161 | if (r.min !== undefined || 162 | r.max !== undefined || r.exact !== undefined) { 163 | require.push(key); 164 | } 165 | if (r.exact !== undefined) { 166 | if (typeof r.exact === 'number') { 167 | r.min = r.max = r.exact; 168 | } else { 169 | c[key] = r.exact; 170 | } 171 | delete r.exact; 172 | } 173 | if (r.ideal !== undefined) { 174 | c.advanced = c.advanced || []; 175 | var oc = {}; 176 | if (typeof r.ideal === 'number') { 177 | oc[key] = {min: r.ideal, max: r.ideal}; 178 | } else { 179 | oc[key] = r.ideal; 180 | } 181 | c.advanced.push(oc); 182 | delete r.ideal; 183 | if (!Object.keys(r).length) { 184 | delete c[key]; 185 | } 186 | } 187 | }); 188 | if (require.length) { 189 | c.require = require; 190 | } 191 | return c; 192 | }; 193 | if (webrtcDetectedVersion < 38) { 194 | webrtcUtils.log('spec: ' + JSON.stringify(constraints)); 195 | if (constraints.audio) { 196 | constraints.audio = constraintsToFF37(constraints.audio); 197 | } 198 | if (constraints.video) { 199 | constraints.video = constraintsToFF37(constraints.video); 200 | } 201 | webrtcUtils.log('ff37: ' + JSON.stringify(constraints)); 202 | } 203 | return navigator.mozGetUserMedia(constraints, onSuccess, onError); 204 | }; 205 | 206 | navigator.getUserMedia = getUserMedia; 207 | 208 | // Shim for mediaDevices on older versions. 209 | if (!navigator.mediaDevices) { 210 | navigator.mediaDevices = {getUserMedia: requestUserMedia, 211 | addEventListener: function() { }, 212 | removeEventListener: function() { } 213 | }; 214 | } 215 | navigator.mediaDevices.enumerateDevices = 216 | navigator.mediaDevices.enumerateDevices || function() { 217 | return new Promise(function(resolve) { 218 | var infos = [ 219 | {kind: 'audioinput', deviceId: 'default', label: '', groupId: ''}, 220 | {kind: 'videoinput', deviceId: 'default', label: '', groupId: ''} 221 | ]; 222 | resolve(infos); 223 | }); 224 | }; 225 | 226 | if (webrtcDetectedVersion < 41) { 227 | // Work around http://bugzil.la/1169665 228 | var orgEnumerateDevices = 229 | navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices); 230 | navigator.mediaDevices.enumerateDevices = function() { 231 | return orgEnumerateDevices().catch(function(e) { 232 | if (e.name === 'NotFoundError') { 233 | return []; 234 | } 235 | throw e; 236 | }); 237 | }; 238 | } 239 | } else if (navigator.webkitGetUserMedia && !!window.chrome) { 240 | webrtcUtils.log('This appears to be Chrome'); 241 | 242 | webrtcDetectedBrowser = 'chrome'; 243 | 244 | // the detected chrome version. 245 | webrtcDetectedVersion = 246 | parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10); 247 | 248 | // the minimum chrome version still supported by adapter. 249 | webrtcMinimumVersion = 38; 250 | 251 | // The RTCPeerConnection object. 252 | window.RTCPeerConnection = function(pcConfig, pcConstraints) { 253 | // Translate iceTransportPolicy to iceTransports, 254 | // see https://code.google.com/p/webrtc/issues/detail?id=4869 255 | if (pcConfig && pcConfig.iceTransportPolicy) { 256 | pcConfig.iceTransports = pcConfig.iceTransportPolicy; 257 | } 258 | 259 | var pc = new webkitRTCPeerConnection(pcConfig, pcConstraints); // jscs:ignore requireCapitalizedConstructors 260 | var origGetStats = pc.getStats.bind(pc); 261 | pc.getStats = function(selector, successCallback, errorCallback) { // jshint ignore: line 262 | var self = this; 263 | var args = arguments; 264 | 265 | // If selector is a function then we are in the old style stats so just 266 | // pass back the original getStats format to avoid breaking old users. 267 | if (arguments.length > 0 && typeof selector === 'function') { 268 | return origGetStats(selector, successCallback); 269 | } 270 | 271 | var fixChromeStats = function(response) { 272 | var standardReport = {}; 273 | var reports = response.result(); 274 | reports.forEach(function(report) { 275 | var standardStats = { 276 | id: report.id, 277 | timestamp: report.timestamp, 278 | type: report.type 279 | }; 280 | report.names().forEach(function(name) { 281 | standardStats[name] = report.stat(name); 282 | }); 283 | standardReport[standardStats.id] = standardStats; 284 | }); 285 | 286 | return standardReport; 287 | }; 288 | 289 | if (arguments.length >= 2) { 290 | var successCallbackWrapper = function(response) { 291 | args[1](fixChromeStats(response)); 292 | }; 293 | 294 | return origGetStats.apply(this, [successCallbackWrapper, arguments[0]]); 295 | } 296 | 297 | // promise-support 298 | return new Promise(function(resolve, reject) { 299 | if (args.length === 1 && selector === null) { 300 | origGetStats.apply(self, [ 301 | function(response) { 302 | resolve.apply(null, [fixChromeStats(response)]); 303 | }, reject]); 304 | } else { 305 | origGetStats.apply(self, [resolve, reject]); 306 | } 307 | }); 308 | }; 309 | 310 | return pc; 311 | }; 312 | 313 | // add promise support 314 | ['createOffer', 'createAnswer'].forEach(function(method) { 315 | var nativeMethod = webkitRTCPeerConnection.prototype[method]; 316 | webkitRTCPeerConnection.prototype[method] = function() { 317 | var self = this; 318 | if (arguments.length < 1 || (arguments.length === 1 && 319 | typeof(arguments[0]) === 'object')) { 320 | var opts = arguments.length === 1 ? arguments[0] : undefined; 321 | return new Promise(function(resolve, reject) { 322 | nativeMethod.apply(self, [resolve, reject, opts]); 323 | }); 324 | } else { 325 | return nativeMethod.apply(this, arguments); 326 | } 327 | }; 328 | }); 329 | 330 | ['setLocalDescription', 'setRemoteDescription', 331 | 'addIceCandidate'].forEach(function(method) { 332 | var nativeMethod = webkitRTCPeerConnection.prototype[method]; 333 | webkitRTCPeerConnection.prototype[method] = function() { 334 | var args = arguments; 335 | var self = this; 336 | return new Promise(function(resolve, reject) { 337 | nativeMethod.apply(self, [args[0], 338 | function() { 339 | resolve(); 340 | if (args.length >= 2) { 341 | args[1].apply(null, []); 342 | } 343 | }, 344 | function(err) { 345 | reject(err); 346 | if (args.length >= 3) { 347 | args[2].apply(null, [err]); 348 | } 349 | }] 350 | ); 351 | }); 352 | }; 353 | }); 354 | 355 | // getUserMedia constraints shim. 356 | var constraintsToChrome = function(c) { 357 | if (typeof c !== 'object' || c.mandatory || c.optional) { 358 | return c; 359 | } 360 | var cc = {}; 361 | Object.keys(c).forEach(function(key) { 362 | if (key === 'require' || key === 'advanced' || key === 'mediaSource') { 363 | return; 364 | } 365 | var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]}; 366 | if (r.exact !== undefined && typeof r.exact === 'number') { 367 | r.min = r.max = r.exact; 368 | } 369 | var oldname = function(prefix, name) { 370 | if (prefix) { 371 | return prefix + name.charAt(0).toUpperCase() + name.slice(1); 372 | } 373 | return (name === 'deviceId') ? 'sourceId' : name; 374 | }; 375 | if (r.ideal !== undefined) { 376 | cc.optional = cc.optional || []; 377 | var oc = {}; 378 | if (typeof r.ideal === 'number') { 379 | oc[oldname('min', key)] = r.ideal; 380 | cc.optional.push(oc); 381 | oc = {}; 382 | oc[oldname('max', key)] = r.ideal; 383 | cc.optional.push(oc); 384 | } else { 385 | oc[oldname('', key)] = r.ideal; 386 | cc.optional.push(oc); 387 | } 388 | } 389 | if (r.exact !== undefined && typeof r.exact !== 'number') { 390 | cc.mandatory = cc.mandatory || {}; 391 | cc.mandatory[oldname('', key)] = r.exact; 392 | } else { 393 | ['min', 'max'].forEach(function(mix) { 394 | if (r[mix] !== undefined) { 395 | cc.mandatory = cc.mandatory || {}; 396 | cc.mandatory[oldname(mix, key)] = r[mix]; 397 | } 398 | }); 399 | } 400 | }); 401 | if (c.advanced) { 402 | cc.optional = (cc.optional || []).concat(c.advanced); 403 | } 404 | return cc; 405 | }; 406 | 407 | getUserMedia = function(constraints, onSuccess, onError) { 408 | if (constraints.audio) { 409 | constraints.audio = constraintsToChrome(constraints.audio); 410 | } 411 | if (constraints.video) { 412 | constraints.video = constraintsToChrome(constraints.video); 413 | } 414 | webrtcUtils.log('chrome: ' + JSON.stringify(constraints)); 415 | return navigator.webkitGetUserMedia(constraints, onSuccess, onError); 416 | }; 417 | navigator.getUserMedia = getUserMedia; 418 | 419 | if (!navigator.mediaDevices) { 420 | navigator.mediaDevices = {getUserMedia: requestUserMedia, 421 | enumerateDevices: function() { 422 | return new Promise(function(resolve) { 423 | var kinds = {audio: 'audioinput', video: 'videoinput'}; 424 | return MediaStreamTrack.getSources(function(devices) { 425 | resolve(devices.map(function(device) { 426 | return {label: device.label, 427 | kind: kinds[device.kind], 428 | deviceId: device.id, 429 | groupId: ''}; 430 | })); 431 | }); 432 | }); 433 | }}; 434 | } 435 | 436 | // A shim for getUserMedia method on the mediaDevices object. 437 | // TODO(KaptenJansson) remove once implemented in Chrome stable. 438 | if (!navigator.mediaDevices.getUserMedia) { 439 | navigator.mediaDevices.getUserMedia = function(constraints) { 440 | return requestUserMedia(constraints); 441 | }; 442 | } else { 443 | // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia 444 | // function which returns a Promise, it does not accept spec-style 445 | // constraints. 446 | var origGetUserMedia = navigator.mediaDevices.getUserMedia. 447 | bind(navigator.mediaDevices); 448 | navigator.mediaDevices.getUserMedia = function(c) { 449 | webrtcUtils.log('spec: ' + JSON.stringify(c)); // whitespace for alignment 450 | c.audio = constraintsToChrome(c.audio); 451 | c.video = constraintsToChrome(c.video); 452 | webrtcUtils.log('chrome: ' + JSON.stringify(c)); 453 | return origGetUserMedia(c); 454 | }; 455 | } 456 | 457 | // Dummy devicechange event methods. 458 | // TODO(KaptenJansson) remove once implemented in Chrome stable. 459 | if (typeof navigator.mediaDevices.addEventListener === 'undefined') { 460 | navigator.mediaDevices.addEventListener = function() { 461 | webrtcUtils.log('Dummy mediaDevices.addEventListener called.'); 462 | }; 463 | } 464 | if (typeof navigator.mediaDevices.removeEventListener === 'undefined') { 465 | navigator.mediaDevices.removeEventListener = function() { 466 | webrtcUtils.log('Dummy mediaDevices.removeEventListener called.'); 467 | }; 468 | } 469 | 470 | // Attach a media stream to an element. 471 | attachMediaStream = function(element, stream) { 472 | if (webrtcDetectedVersion >= 43) { 473 | element.srcObject = stream; 474 | } else if (typeof element.src !== 'undefined') { 475 | element.src = URL.createObjectURL(stream); 476 | } else { 477 | webrtcUtils.log('Error attaching stream to element.'); 478 | } 479 | }; 480 | reattachMediaStream = function(to, from) { 481 | if (webrtcDetectedVersion >= 43) { 482 | to.srcObject = from.srcObject; 483 | } else { 484 | to.src = from.src; 485 | } 486 | }; 487 | 488 | } else if (navigator.mediaDevices && navigator.userAgent.match( 489 | /Edge\/(\d+).(\d+)$/)) { 490 | webrtcUtils.log('This appears to be Edge'); 491 | webrtcDetectedBrowser = 'edge'; 492 | 493 | webrtcDetectedVersion = 494 | parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10); 495 | 496 | // the minimum version still supported by adapter. 497 | webrtcMinimumVersion = 12; 498 | 499 | if (RTCIceGatherer) { 500 | window.RTCIceCandidate = function(args) { 501 | return args; 502 | }; 503 | window.RTCSessionDescription = function(args) { 504 | return args; 505 | }; 506 | 507 | window.RTCPeerConnection = function(config) { 508 | var self = this; 509 | 510 | this.onicecandidate = null; 511 | this.onaddstream = null; 512 | this.onremovestream = null; 513 | this.onsignalingstatechange = null; 514 | this.oniceconnectionstatechange = null; 515 | this.onnegotiationneeded = null; 516 | this.ondatachannel = null; 517 | 518 | this.localStreams = []; 519 | this.remoteStreams = []; 520 | this.getLocalStreams = function() { return self.localStreams; }; 521 | this.getRemoteStreams = function() { return self.remoteStreams; }; 522 | 523 | this.localDescription = new RTCSessionDescription({ 524 | type: '', 525 | sdp: '' 526 | }); 527 | this.remoteDescription = new RTCSessionDescription({ 528 | type: '', 529 | sdp: '' 530 | }); 531 | this.signalingState = 'stable'; 532 | this.iceConnectionState = 'new'; 533 | 534 | this.iceOptions = { 535 | gatherPolicy: 'all', 536 | iceServers: [] 537 | }; 538 | if (config && config.iceTransportPolicy) { 539 | switch (config.iceTransportPolicy) { 540 | case 'all': 541 | case 'relay': 542 | this.iceOptions.gatherPolicy = config.iceTransportPolicy; 543 | break; 544 | case 'none': 545 | // FIXME: remove once implementation and spec have added this. 546 | throw new TypeError('iceTransportPolicy "none" not supported'); 547 | } 548 | } 549 | if (config && config.iceServers) { 550 | this.iceOptions.iceServers = config.iceServers; 551 | } 552 | 553 | // per-track iceGathers etc 554 | this.mLines = []; 555 | 556 | this._iceCandidates = []; 557 | 558 | this._peerConnectionId = 'PC_' + Math.floor(Math.random() * 65536); 559 | 560 | // FIXME: Should be generated according to spec (guid?) 561 | // and be the same for all PCs from the same JS 562 | this._cname = Math.random().toString(36).substr(2, 10); 563 | }; 564 | 565 | window.RTCPeerConnection.prototype.addStream = function(stream) { 566 | // clone just in case we're working in a local demo 567 | // FIXME: seems to be fixed 568 | this.localStreams.push(stream.clone()); 569 | 570 | // FIXME: maybe trigger negotiationneeded? 571 | }; 572 | 573 | window.RTCPeerConnection.prototype.removeStream = function(stream) { 574 | var idx = this.localStreams.indexOf(stream); 575 | if (idx > -1) { 576 | this.localStreams.splice(idx, 1); 577 | } 578 | // FIXME: maybe trigger negotiationneeded? 579 | }; 580 | 581 | // SDP helper from sdp-jingle-json with modifications. 582 | window.RTCPeerConnection.prototype._toCandidateJSON = function(line) { 583 | var parts; 584 | if (line.indexOf('a=candidate:') === 0) { 585 | parts = line.substring(12).split(' '); 586 | } else { // no a=candidate 587 | parts = line.substring(10).split(' '); 588 | } 589 | 590 | var candidate = { 591 | foundation: parts[0], 592 | component: parts[1], 593 | protocol: parts[2].toLowerCase(), 594 | priority: parseInt(parts[3], 10), 595 | ip: parts[4], 596 | port: parseInt(parts[5], 10), 597 | // skip parts[6] == 'typ' 598 | type: parts[7] 599 | //generation: '0' 600 | }; 601 | 602 | for (var i = 8; i < parts.length; i += 2) { 603 | if (parts[i] === 'raddr') { 604 | candidate.relatedAddress = parts[i + 1]; // was: relAddr 605 | } else if (parts[i] === 'rport') { 606 | candidate.relatedPort = parseInt(parts[i + 1], 10); // was: relPort 607 | } else if (parts[i] === 'generation') { 608 | candidate.generation = parts[i + 1]; 609 | } else if (parts[i] === 'tcptype') { 610 | candidate.tcpType = parts[i + 1]; 611 | } 612 | } 613 | return candidate; 614 | }; 615 | 616 | // SDP helper from sdp-jingle-json with modifications. 617 | window.RTCPeerConnection.prototype._toCandidateSDP = function(candidate) { 618 | var sdp = []; 619 | sdp.push(candidate.foundation); 620 | sdp.push(candidate.component); 621 | sdp.push(candidate.protocol.toUpperCase()); 622 | sdp.push(candidate.priority); 623 | sdp.push(candidate.ip); 624 | sdp.push(candidate.port); 625 | 626 | var type = candidate.type; 627 | sdp.push('typ'); 628 | sdp.push(type); 629 | if (type === 'srflx' || type === 'prflx' || type === 'relay') { 630 | if (candidate.relatedAddress && candidate.relatedPort) { 631 | sdp.push('raddr'); 632 | sdp.push(candidate.relatedAddress); // was: relAddr 633 | sdp.push('rport'); 634 | sdp.push(candidate.relatedPort); // was: relPort 635 | } 636 | } 637 | if (candidate.tcpType && candidate.protocol.toUpperCase() === 'TCP') { 638 | sdp.push('tcptype'); 639 | sdp.push(candidate.tcpType); 640 | } 641 | return 'a=candidate:' + sdp.join(' '); 642 | }; 643 | 644 | // SDP helper from sdp-jingle-json with modifications. 645 | window.RTCPeerConnection.prototype._parseRtpMap = function(line) { 646 | var parts = line.substr(9).split(' '); 647 | var parsed = { 648 | payloadType: parseInt(parts.shift(), 10) // was: id 649 | }; 650 | 651 | parts = parts[0].split('/'); 652 | 653 | parsed.name = parts[0]; 654 | parsed.clockRate = parseInt(parts[1], 10); // was: clockrate 655 | parsed.numChannels = parts.length === 3 ? parseInt(parts[2], 10) : 1; // was: channels 656 | return parsed; 657 | }; 658 | 659 | // Parses SDP to determine capabilities. 660 | window.RTCPeerConnection.prototype._getRemoteCapabilities = 661 | function(section) { 662 | var remoteCapabilities = { 663 | codecs: [], 664 | headerExtensions: [], 665 | fecMechanisms: [] 666 | }; 667 | var i; 668 | var lines = section.split('\r\n'); 669 | var mline = lines[0].substr(2).split(' '); 670 | var rtpmapFilter = function(line) { 671 | return line.indexOf('a=rtpmap:' + mline[i]) === 0; 672 | }; 673 | var fmtpFilter = function(line) { 674 | return line.indexOf('a=fmtp:' + mline[i]) === 0; 675 | }; 676 | var parseFmtp = function(line) { 677 | var parsed = {}; 678 | var kv; 679 | var parts = line.substr(('a=fmtp:' + mline[i]).length + 1).split(';'); 680 | for (var j = 0; j < parts.length; j++) { 681 | kv = parts[j].split('='); 682 | parsed[kv[0].trim()] = kv[1]; 683 | } 684 | console.log('fmtp', mline[i], parsed); 685 | return parsed; 686 | }; 687 | var rtcpFbFilter = function(line) { 688 | return line.indexOf('a=rtcp-fb:' + mline[i]) === 0; 689 | }; 690 | var parseRtcpFb = function(line) { 691 | var parts = line.substr(('a=rtcp-fb:' + mline[i]).length + 1) 692 | .split(' '); 693 | return { 694 | type: parts.shift(), 695 | parameter: parts.join(' ') 696 | }; 697 | }; 698 | for (i = 3; i < mline.length; i++) { // find all codecs from mline[3..] 699 | var line = lines.filter(rtpmapFilter)[0]; 700 | if (line) { 701 | var codec = this._parseRtpMap(line); 702 | 703 | var fmtp = lines.filter(fmtpFilter); 704 | codec.parameters = fmtp.length ? parseFmtp(fmtp[0]) : {}; 705 | codec.rtcpFeedback = lines.filter(rtcpFbFilter).map(parseRtcpFb); 706 | 707 | remoteCapabilities.codecs.push(codec); 708 | } 709 | } 710 | return remoteCapabilities; 711 | }; 712 | 713 | // Serializes capabilities to SDP. 714 | window.RTCPeerConnection.prototype._capabilitiesToSDP = function(caps) { 715 | var sdp = ''; 716 | caps.codecs.forEach(function(codec) { 717 | var pt = codec.payloadType; 718 | if (codec.preferredPayloadType !== undefined) { 719 | pt = codec.preferredPayloadType; 720 | } 721 | sdp += 'a=rtpmap:' + pt + 722 | ' ' + codec.name + 723 | '/' + codec.clockRate + 724 | (codec.numChannels !== 1 ? '/' + codec.numChannels : '') + 725 | '\r\n'; 726 | if (codec.parameters && codec.parameters.length) { 727 | sdp += 'a=ftmp:' + pt + ' '; 728 | Object.keys(codec.parameters).forEach(function(param) { 729 | sdp += param + '=' + codec.parameters[param]; 730 | }); 731 | sdp += '\r\n'; 732 | } 733 | if (codec.rtcpFeedback) { 734 | // FIXME: special handling for trr-int? 735 | codec.rtcpFeedback.forEach(function(fb) { 736 | sdp += 'a=rtcp-fb:' + pt + ' ' + fb.type + ' ' + 737 | fb.parameter + '\r\n'; 738 | }); 739 | } 740 | }); 741 | return sdp; 742 | }; 743 | 744 | // Calculates the intersection of local and remote capabilities. 745 | window.RTCPeerConnection.prototype._getCommonCapabilities = 746 | function(localCapabilities, remoteCapabilities) { 747 | var commonCapabilities = { 748 | codecs: [], 749 | headerExtensions: [], 750 | fecMechanisms: [] 751 | }; 752 | localCapabilities.codecs.forEach(function(lCodec) { 753 | for (var i = 0; i < remoteCapabilities.codecs.length; i++) { 754 | var rCodec = remoteCapabilities.codecs[i]; 755 | if (lCodec.name === rCodec.name && 756 | lCodec.clockRate === rCodec.clockRate && 757 | lCodec.numChannels === rCodec.numChannels) { 758 | // push rCodec so we reply with offerer payload type 759 | commonCapabilities.codecs.push(rCodec); 760 | 761 | // FIXME: also need to calculate intersection between 762 | // .rtcpFeedback and .parameters 763 | break; 764 | } 765 | } 766 | }); 767 | 768 | localCapabilities.headerExtensions.forEach(function(lHeaderExtension) { 769 | for (var i = 0; i < remoteCapabilities.headerExtensions.length; i++) { 770 | var rHeaderExtension = remoteCapabilities.headerExtensions[i]; 771 | if (lHeaderExtension.uri === rHeaderExtension.uri) { 772 | commonCapabilities.headerExtensions.push(rHeaderExtension); 773 | break; 774 | } 775 | } 776 | }); 777 | 778 | // FIXME: fecMechanisms 779 | return commonCapabilities; 780 | }; 781 | 782 | // Parses DTLS parameters from SDP section or sessionpart. 783 | window.RTCPeerConnection.prototype._getDtlsParameters = 784 | function(section, session) { 785 | var lines = section.split('\r\n'); 786 | lines = lines.concat(session.split('\r\n')); // Search in session part, too. 787 | var fpLine = lines.filter(function(line) { 788 | return line.indexOf('a=fingerprint:') === 0; 789 | }); 790 | fpLine = fpLine[0].substr(14); 791 | var dtlsParameters = { 792 | role: 'auto', 793 | fingerprints: [{ 794 | algorithm: fpLine.split(' ')[0], 795 | value: fpLine.split(' ')[1] 796 | }] 797 | }; 798 | return dtlsParameters; 799 | }; 800 | 801 | // Serializes DTLS parameters to SDP. 802 | window.RTCPeerConnection.prototype._dtlsParametersToSDP = 803 | function(params, setupType) { 804 | var sdp = 'a=setup:' + setupType + '\r\n'; 805 | params.fingerprints.forEach(function(fp) { 806 | sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n'; 807 | }); 808 | return sdp; 809 | }; 810 | 811 | // Parses ICE information from SDP section or sessionpart. 812 | window.RTCPeerConnection.prototype._getIceParameters = 813 | function(section, session) { 814 | var lines = section.split('\r\n'); 815 | lines = lines.concat(session.split('\r\n')); // Search in session part, too. 816 | var iceParameters = { 817 | usernameFragment: lines.filter(function(line) { 818 | return line.indexOf('a=ice-ufrag:') === 0; 819 | })[0].substr(12), 820 | password: lines.filter(function(line) { 821 | return line.indexOf('a=ice-pwd:') === 0; 822 | })[0].substr(10), 823 | }; 824 | return iceParameters; 825 | }; 826 | 827 | // Serializes ICE parameters to SDP. 828 | window.RTCPeerConnection.prototype._iceParametersToSDP = function(params) { 829 | return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' + 830 | 'a=ice-pwd:' + params.password + '\r\n'; 831 | }; 832 | 833 | window.RTCPeerConnection.prototype._getEncodingParameters = function(ssrc) { 834 | return { 835 | ssrc: ssrc, 836 | codecPayloadType: 0, 837 | fec: 0, 838 | rtx: 0, 839 | priority: 1.0, 840 | maxBitrate: 2000000.0, 841 | minQuality: 0, 842 | framerateBias: 0.5, 843 | resolutionScale: 1.0, 844 | framerateScale: 1.0, 845 | active: true, 846 | dependencyEncodingId: undefined, 847 | encodingId: undefined 848 | }; 849 | }; 850 | 851 | // Create ICE gatherer, ICE transport and DTLS transport. 852 | window.RTCPeerConnection.prototype._createIceAndDtlsTransports = 853 | function(mid, sdpMLineIndex) { 854 | var self = this; 855 | var iceGatherer = new RTCIceGatherer(self.iceOptions); 856 | var iceTransport = new RTCIceTransport(iceGatherer); 857 | iceGatherer.onlocalcandidate = function(evt) { 858 | var event = {}; 859 | event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex}; 860 | 861 | var cand = evt.candidate; 862 | var isEndOfCandidates = !(cand && Object.keys(cand).length > 0); 863 | if (isEndOfCandidates) { 864 | event.candidate.candidate = 865 | 'candidate:1 1 udp 1 0.0.0.0 9 typ endOfCandidates'; 866 | } else { 867 | // RTCIceCandidate doesn't have a component, needs to be added 868 | cand.component = iceTransport.component === 'RTCP' ? 2 : 1; 869 | event.candidate.candidate = self._toCandidateSDP(cand); 870 | } 871 | if (self.onicecandidate !== null) { 872 | if (self.localDescription && self.localDescription.type === '') { 873 | self._iceCandidates.push(event); 874 | } else { 875 | self.onicecandidate(event); 876 | } 877 | } 878 | }; 879 | iceTransport.onicestatechange = function() { 880 | /* 881 | console.log(self._peerConnectionId, 882 | 'ICE state change', iceTransport.state); 883 | */ 884 | self._updateIceConnectionState(iceTransport.state); 885 | }; 886 | 887 | var dtlsTransport = new RTCDtlsTransport(iceTransport); 888 | dtlsTransport.ondtlsstatechange = function() { 889 | /* 890 | console.log(self._peerConnectionId, sdpMLineIndex, 891 | 'dtls state change', dtlsTransport.state); 892 | */ 893 | }; 894 | dtlsTransport.onerror = function(error) { 895 | console.error('dtls error', error); 896 | }; 897 | return { 898 | iceGatherer: iceGatherer, 899 | iceTransport: iceTransport, 900 | dtlsTransport: dtlsTransport 901 | }; 902 | }; 903 | 904 | window.RTCPeerConnection.prototype.setLocalDescription = 905 | function(description) { 906 | var self = this; 907 | if (description.type === 'offer') { 908 | if (!description.ortc) { 909 | // FIXME: throw? 910 | } else { 911 | this.mLines = description.ortc; 912 | } 913 | } else if (description.type === 'answer') { 914 | var sections = self.remoteDescription.sdp.split('\r\nm='); 915 | var sessionpart = sections.shift(); 916 | sections.forEach(function(section, sdpMLineIndex) { 917 | section = 'm=' + section; 918 | 919 | var iceGatherer = self.mLines[sdpMLineIndex].iceGatherer; 920 | var iceTransport = self.mLines[sdpMLineIndex].iceTransport; 921 | var dtlsTransport = self.mLines[sdpMLineIndex].dtlsTransport; 922 | var rtpSender = self.mLines[sdpMLineIndex].rtpSender; 923 | var localCapabilities = 924 | self.mLines[sdpMLineIndex].localCapabilities; 925 | var remoteCapabilities = 926 | self.mLines[sdpMLineIndex].remoteCapabilities; 927 | var sendSSRC = self.mLines[sdpMLineIndex].sendSSRC; 928 | var recvSSRC = self.mLines[sdpMLineIndex].recvSSRC; 929 | 930 | var remoteIceParameters = self._getIceParameters(section, 931 | sessionpart); 932 | iceTransport.start(iceGatherer, remoteIceParameters, 'controlled'); 933 | 934 | var remoteDtlsParameters = self._getDtlsParameters(section, 935 | sessionpart); 936 | dtlsTransport.start(remoteDtlsParameters); 937 | 938 | if (rtpSender) { 939 | // calculate intersection of capabilities 940 | var params = self._getCommonCapabilities(localCapabilities, 941 | remoteCapabilities); 942 | params.muxId = sendSSRC; 943 | params.encodings = [self._getEncodingParameters(sendSSRC)]; 944 | params.rtcp = { 945 | cname: self._cname, 946 | reducedSize: false, 947 | ssrc: recvSSRC, 948 | mux: true 949 | }; 950 | rtpSender.send(params); 951 | } 952 | }); 953 | } 954 | 955 | this.localDescription = description; 956 | switch (description.type) { 957 | case 'offer': 958 | this._updateSignalingState('have-local-offer'); 959 | break; 960 | case 'answer': 961 | this._updateSignalingState('stable'); 962 | break; 963 | } 964 | 965 | // FIXME: need to _reliably_ execute after args[1] or promise 966 | window.setTimeout(function() { 967 | // FIXME: need to apply ice candidates in a way which is async but in-order 968 | self._iceCandidates.forEach(function(event) { 969 | if (self.onicecandidate !== null) { 970 | self.onicecandidate(event); 971 | } 972 | }); 973 | self._iceCandidates = []; 974 | }, 50); 975 | if (arguments.length > 1 && typeof arguments[1] === 'function') { 976 | window.setTimeout(arguments[1], 0); 977 | } 978 | return new Promise(function(resolve) { 979 | resolve(); 980 | }); 981 | }; 982 | 983 | window.RTCPeerConnection.prototype.setRemoteDescription = 984 | function(description) { 985 | // FIXME: for type=offer this creates state. which should not 986 | // happen before SLD with type=answer but... we need the stream 987 | // here for onaddstream. 988 | var self = this; 989 | var sections = description.sdp.split('\r\nm='); 990 | var sessionpart = sections.shift(); 991 | var stream = new MediaStream(); 992 | sections.forEach(function(section, sdpMLineIndex) { 993 | section = 'm=' + section; 994 | var lines = section.split('\r\n'); 995 | var mline = lines[0].substr(2).split(' '); 996 | var kind = mline[0]; 997 | var line; 998 | 999 | var iceGatherer; 1000 | var iceTransport; 1001 | var dtlsTransport; 1002 | var rtpSender; 1003 | var rtpReceiver; 1004 | var sendSSRC; 1005 | var recvSSRC; 1006 | 1007 | var mid = lines.filter(function(line) { 1008 | return line.indexOf('a=mid:') === 0; 1009 | })[0].substr(6); 1010 | 1011 | var cname; 1012 | 1013 | var remoteCapabilities; 1014 | var params; 1015 | 1016 | if (description.type === 'offer') { 1017 | var transports = self._createIceAndDtlsTransports(mid, sdpMLineIndex); 1018 | 1019 | var localCapabilities = RTCRtpReceiver.getCapabilities(kind); 1020 | // determine remote caps from SDP 1021 | remoteCapabilities = self._getRemoteCapabilities(section); 1022 | 1023 | line = lines.filter(function(line) { 1024 | return line.indexOf('a=ssrc:') === 0 && 1025 | line.split(' ')[1].indexOf('cname:') === 0; 1026 | }); 1027 | sendSSRC = (2 * sdpMLineIndex + 2) * 1001; 1028 | if (line) { // FIXME: alot of assumptions here 1029 | recvSSRC = line[0].split(' ')[0].split(':')[1]; 1030 | cname = line[0].split(' ')[1].split(':')[1]; 1031 | } 1032 | rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind); 1033 | 1034 | // calculate intersection so no unknown caps get passed into the RTPReciver 1035 | params = self._getCommonCapabilities(localCapabilities, 1036 | remoteCapabilities); 1037 | 1038 | params.muxId = recvSSRC; 1039 | params.encodings = [self._getEncodingParameters(recvSSRC)]; 1040 | params.rtcp = { 1041 | cname: cname, 1042 | reducedSize: false, 1043 | ssrc: sendSSRC, 1044 | mux: true 1045 | }; 1046 | rtpReceiver.receive(params); 1047 | // FIXME: not correct when there are multiple streams but that is 1048 | // not currently supported. 1049 | stream.addTrack(rtpReceiver.track); 1050 | 1051 | // FIXME: honor a=sendrecv 1052 | if (self.localStreams.length > 0 && 1053 | self.localStreams[0].getTracks().length >= sdpMLineIndex) { 1054 | // FIXME: actually more complicated, needs to match types etc 1055 | var localtrack = self.localStreams[0].getTracks()[sdpMLineIndex]; 1056 | rtpSender = new RTCRtpSender(localtrack, transports.dtlsTransport); 1057 | } 1058 | 1059 | self.mLines[sdpMLineIndex] = { 1060 | iceGatherer: transports.iceGatherer, 1061 | iceTransport: transports.iceTransport, 1062 | dtlsTransport: transports.dtlsTransport, 1063 | localCapabilities: localCapabilities, 1064 | remoteCapabilities: remoteCapabilities, 1065 | rtpSender: rtpSender, 1066 | rtpReceiver: rtpReceiver, 1067 | kind: kind, 1068 | mid: mid, 1069 | sendSSRC: sendSSRC, 1070 | recvSSRC: recvSSRC 1071 | }; 1072 | } else { 1073 | iceGatherer = self.mLines[sdpMLineIndex].iceGatherer; 1074 | iceTransport = self.mLines[sdpMLineIndex].iceTransport; 1075 | dtlsTransport = self.mLines[sdpMLineIndex].dtlsTransport; 1076 | rtpSender = self.mLines[sdpMLineIndex].rtpSender; 1077 | rtpReceiver = self.mLines[sdpMLineIndex].rtpReceiver; 1078 | sendSSRC = self.mLines[sdpMLineIndex].sendSSRC; 1079 | recvSSRC = self.mLines[sdpMLineIndex].recvSSRC; 1080 | } 1081 | 1082 | var remoteIceParameters = self._getIceParameters(section, sessionpart); 1083 | var remoteDtlsParameters = self._getDtlsParameters(section, 1084 | sessionpart); 1085 | 1086 | // for answers we start ice and dtls here, otherwise this is done in SLD 1087 | if (description.type === 'answer') { 1088 | iceTransport.start(iceGatherer, remoteIceParameters, 'controlling'); 1089 | dtlsTransport.start(remoteDtlsParameters); 1090 | 1091 | // determine remote caps from SDP 1092 | remoteCapabilities = self._getRemoteCapabilities(section); 1093 | // FIXME: store remote caps? 1094 | 1095 | if (rtpSender) { 1096 | params = remoteCapabilities; 1097 | params.muxId = sendSSRC; 1098 | params.encodings = [self._getEncodingParameters(sendSSRC)]; 1099 | params.rtcp = { 1100 | cname: self._cname, 1101 | reducedSize: false, 1102 | ssrc: recvSSRC, 1103 | mux: true 1104 | }; 1105 | rtpSender.send(params); 1106 | } 1107 | 1108 | // FIXME: only if a=sendrecv 1109 | var bidi = lines.filter(function(line) { 1110 | return line.indexOf('a=ssrc:') === 0; 1111 | }).length > 0; 1112 | if (rtpReceiver && bidi) { 1113 | line = lines.filter(function(line) { 1114 | return line.indexOf('a=ssrc:') === 0 && 1115 | line.split(' ')[1].indexOf('cname:') === 0; 1116 | }); 1117 | if (line) { // FIXME: alot of assumptions here 1118 | recvSSRC = line[0].split(' ')[0].split(':')[1]; 1119 | cname = line[0].split(' ')[1].split(':')[1]; 1120 | } 1121 | params = remoteCapabilities; 1122 | params.muxId = recvSSRC; 1123 | params.encodings = [self._getEncodingParameters(recvSSRC)]; 1124 | params.rtcp = { 1125 | cname: cname, 1126 | reducedSize: false, 1127 | ssrc: sendSSRC, 1128 | mux: true 1129 | }; 1130 | rtpReceiver.receive(params, kind); 1131 | stream.addTrack(rtpReceiver.track); 1132 | self.mLines[sdpMLineIndex].recvSSRC = recvSSRC; 1133 | } 1134 | } 1135 | }); 1136 | 1137 | this.remoteDescription = description; 1138 | switch (description.type) { 1139 | case 'offer': 1140 | this._updateSignalingState('have-remote-offer'); 1141 | break; 1142 | case 'answer': 1143 | this._updateSignalingState('stable'); 1144 | break; 1145 | } 1146 | window.setTimeout(function() { 1147 | if (self.onaddstream !== null && stream.getTracks().length) { 1148 | self.remoteStreams.push(stream); 1149 | window.setTimeout(function() { 1150 | self.onaddstream({stream: stream}); 1151 | }, 0); 1152 | } 1153 | }, 0); 1154 | if (arguments.length > 1 && typeof arguments[1] === 'function') { 1155 | window.setTimeout(arguments[1], 0); 1156 | } 1157 | return new Promise(function(resolve) { 1158 | resolve(); 1159 | }); 1160 | }; 1161 | 1162 | window.RTCPeerConnection.prototype.close = function() { 1163 | this.mLines.forEach(function(mLine) { 1164 | /* not yet 1165 | if (mLine.iceGatherer) { 1166 | mLine.iceGatherer.close(); 1167 | } 1168 | */ 1169 | if (mLine.iceTransport) { 1170 | mLine.iceTransport.stop(); 1171 | } 1172 | if (mLine.dtlsTransport) { 1173 | mLine.dtlsTransport.stop(); 1174 | } 1175 | if (mLine.rtpSender) { 1176 | mLine.rtpSender.stop(); 1177 | } 1178 | if (mLine.rtpReceiver) { 1179 | mLine.rtpReceiver.stop(); 1180 | } 1181 | }); 1182 | // FIXME: clean up tracks, local streams, remote streams, etc 1183 | this._updateSignalingState('closed'); 1184 | this._updateIceConnectionState('closed'); 1185 | }; 1186 | 1187 | // Update the signaling state. 1188 | window.RTCPeerConnection.prototype._updateSignalingState = 1189 | function(newState) { 1190 | this.signalingState = newState; 1191 | if (this.onsignalingstatechange !== null) { 1192 | this.onsignalingstatechange(); 1193 | } 1194 | }; 1195 | 1196 | // Update the ICE connection state. 1197 | // FIXME: should be called 'updateConnectionState', also be called for 1198 | // DTLS changes and implement 1199 | // https://lists.w3.org/Archives/Public/public-webrtc/2015Sep/0033.html 1200 | window.RTCPeerConnection.prototype._updateIceConnectionState = 1201 | function(newState) { 1202 | var self = this; 1203 | if (this.iceConnectionState !== newState) { 1204 | var agreement = self.mLines.every(function(mLine) { 1205 | return mLine.iceTransport.state === newState; 1206 | }); 1207 | if (agreement) { 1208 | self.iceConnectionState = newState; 1209 | if (this.oniceconnectionstatechange !== null) { 1210 | this.oniceconnectionstatechange(); 1211 | } 1212 | } 1213 | } 1214 | }; 1215 | 1216 | window.RTCPeerConnection.prototype.createOffer = function() { 1217 | var self = this; 1218 | var offerOptions; 1219 | if (arguments.length === 1 && typeof arguments[0] !== 'function') { 1220 | offerOptions = arguments[0]; 1221 | } else if (arguments.length === 3) { 1222 | offerOptions = arguments[2]; 1223 | } 1224 | 1225 | var tracks = []; 1226 | var numAudioTracks = 0; 1227 | var numVideoTracks = 0; 1228 | // Default to sendrecv. 1229 | if (this.localStreams.length) { 1230 | numAudioTracks = this.localStreams[0].getAudioTracks().length; 1231 | numVideoTracks = this.localStreams[0].getAudioTracks().length; 1232 | } 1233 | // Determine number of audio and video tracks we need to send/recv. 1234 | if (offerOptions) { 1235 | // Deal with Chrome legacy constraints... 1236 | if (offerOptions.mandatory) { 1237 | if (offerOptions.mandatory.OfferToReceiveAudio) { 1238 | numAudioTracks = 1; 1239 | } else if (offerOptions.mandatory.OfferToReceiveAudio === false) { 1240 | numAudioTracks = 0; 1241 | } 1242 | if (offerOptions.mandatory.OfferToReceiveVideo) { 1243 | numVideoTracks = 1; 1244 | } else if (offerOptions.mandatory.OfferToReceiveVideo === false) { 1245 | numVideoTracks = 0; 1246 | } 1247 | } else { 1248 | if (offerOptions.offerToReceiveAudio !== undefined) { 1249 | numAudioTracks = offerOptions.offerToReceiveAudio; 1250 | } 1251 | if (offerOptions.offerToReceiveVideo !== undefined) { 1252 | numVideoTracks = offerOptions.offerToReceiveVideo; 1253 | } 1254 | } 1255 | } 1256 | if (this.localStreams.length) { 1257 | // Push local streams. 1258 | this.localStreams[0].getTracks().forEach(function(track) { 1259 | tracks.push({ 1260 | kind: track.kind, 1261 | track: track, 1262 | wantReceive: track.kind === 'audio' ? 1263 | numAudioTracks > 0 : numVideoTracks > 0 1264 | }); 1265 | if (track.kind === 'audio') { 1266 | numAudioTracks--; 1267 | } else if (track.kind === 'video') { 1268 | numVideoTracks--; 1269 | } 1270 | }); 1271 | } 1272 | // Create M-lines for recvonly streams. 1273 | while (numAudioTracks > 0 || numVideoTracks > 0) { 1274 | if (numAudioTracks > 0) { 1275 | tracks.push({ 1276 | kind: 'audio', 1277 | wantReceive: true 1278 | }); 1279 | numAudioTracks--; 1280 | } 1281 | if (numVideoTracks > 0) { 1282 | tracks.push({ 1283 | kind: 'video', 1284 | wantReceive: true 1285 | }); 1286 | numVideoTracks--; 1287 | } 1288 | } 1289 | 1290 | var sdp = 'v=0\r\n' + 1291 | 'o=thisisadapterortc 8169639915646943137 2 IN IP4 127.0.0.1\r\n' + 1292 | 's=-\r\n' + 1293 | 't=0 0\r\n'; 1294 | var mLines = []; 1295 | tracks.forEach(function(mline, sdpMLineIndex) { 1296 | // For each track, create an ice gatherer, ice transport, dtls transport, 1297 | // potentially rtpsender and rtpreceiver. 1298 | var track = mline.track; 1299 | var kind = mline.kind; 1300 | var mid = Math.random().toString(36).substr(2, 10); 1301 | 1302 | var transports = self._createIceAndDtlsTransports(mid, sdpMLineIndex); 1303 | 1304 | var localCapabilities = RTCRtpSender.getCapabilities(kind); 1305 | var rtpSender; 1306 | // generate an ssrc now, to be used later in rtpSender.send 1307 | var sendSSRC = (2 * sdpMLineIndex + 1) * 1001; //Math.floor(Math.random()*4294967295); 1308 | var recvSSRC; // don't know yet 1309 | if (track) { 1310 | rtpSender = new RTCRtpSender(track, transports.dtlsTransport); 1311 | } 1312 | 1313 | var rtpReceiver; 1314 | if (mline.wantReceive) { 1315 | rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind); 1316 | } 1317 | 1318 | mLines[sdpMLineIndex] = { 1319 | iceGatherer: transports.iceGatherer, 1320 | iceTransport: transports.iceTransport, 1321 | dtlsTransport: transports.dtlsTransport, 1322 | localCapabilities: localCapabilities, 1323 | remoteCapabilities: null, 1324 | rtpSender: rtpSender, 1325 | rtpReceiver: rtpReceiver, 1326 | kind: kind, 1327 | mid: mid, 1328 | sendSSRC: sendSSRC, 1329 | recvSSRC: recvSSRC 1330 | }; 1331 | 1332 | // Map things to SDP. 1333 | // Build the mline. 1334 | sdp += 'm=' + kind + ' 9 UDP/TLS/RTP/SAVPF '; 1335 | sdp += localCapabilities.codecs.map(function(codec) { 1336 | return codec.preferredPayloadType; 1337 | }).join(' ') + '\r\n'; 1338 | 1339 | sdp += 'c=IN IP4 0.0.0.0\r\n'; 1340 | sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n'; 1341 | 1342 | // Map ICE parameters (ufrag, pwd) to SDP. 1343 | sdp += self._iceParametersToSDP( 1344 | transports.iceGatherer.getLocalParameters()); 1345 | 1346 | // Map DTLS parameters to SDP. 1347 | sdp += self._dtlsParametersToSDP( 1348 | transports.dtlsTransport.getLocalParameters(), 'actpass'); 1349 | 1350 | sdp += 'a=mid:' + mid + '\r\n'; 1351 | 1352 | if (rtpSender && rtpReceiver) { 1353 | sdp += 'a=sendrecv\r\n'; 1354 | } else if (rtpSender) { 1355 | sdp += 'a=sendonly\r\n'; 1356 | } else if (rtpReceiver) { 1357 | sdp += 'a=recvonly\r\n'; 1358 | } else { 1359 | sdp += 'a=inactive\r\n'; 1360 | } 1361 | sdp += 'a=rtcp-mux\r\n'; 1362 | 1363 | // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb. 1364 | sdp += self._capabilitiesToSDP(localCapabilities); 1365 | 1366 | if (track) { 1367 | sdp += 'a=msid:' + self.localStreams[0].id + ' ' + track.id + '\r\n'; 1368 | sdp += 'a=ssrc:' + sendSSRC + ' ' + 'msid:' + 1369 | self.localStreams[0].id + ' ' + track.id + '\r\n'; 1370 | } 1371 | sdp += 'a=ssrc:' + sendSSRC + ' cname:' + self._cname + '\r\n'; 1372 | }); 1373 | 1374 | var desc = new RTCSessionDescription({ 1375 | type: 'offer', 1376 | sdp: sdp, 1377 | ortc: mLines 1378 | }); 1379 | if (arguments.length && typeof arguments[0] === 'function') { 1380 | window.setTimeout(arguments[0], 0, desc); 1381 | } 1382 | return new Promise(function(resolve) { 1383 | resolve(desc); 1384 | }); 1385 | }; 1386 | 1387 | window.RTCPeerConnection.prototype.createAnswer = function() { 1388 | var self = this; 1389 | var answerOptions; 1390 | if (arguments.length === 1 && typeof arguments[0] !== 'function') { 1391 | answerOptions = arguments[0]; 1392 | } else if (arguments.length === 3) { 1393 | answerOptions = arguments[2]; 1394 | } 1395 | 1396 | var sdp = 'v=0\r\n' + 1397 | 'o=thisisadapterortc 8169639915646943137 2 IN IP4 127.0.0.1\r\n' + 1398 | 's=-\r\n' + 1399 | 't=0 0\r\n'; 1400 | this.mLines.forEach(function(mLine/*, sdpMLineIndex*/) { 1401 | var iceGatherer = mLine.iceGatherer; 1402 | //var iceTransport = mLine.iceTransport; 1403 | var dtlsTransport = mLine.dtlsTransport; 1404 | var localCapabilities = mLine.localCapabilities; 1405 | var remoteCapabilities = mLine.remoteCapabilities; 1406 | var rtpSender = mLine.rtpSender; 1407 | var rtpReceiver = mLine.rtpReceiver; 1408 | var kind = mLine.kind; 1409 | var sendSSRC = mLine.sendSSRC; 1410 | //var recvSSRC = mLine.recvSSRC; 1411 | 1412 | // Calculate intersection of capabilities. 1413 | var commonCapabilities = self._getCommonCapabilities(localCapabilities, 1414 | remoteCapabilities); 1415 | 1416 | // Map things to SDP. 1417 | // Build the mline. 1418 | sdp += 'm=' + kind + ' 9 UDP/TLS/RTP/SAVPF '; 1419 | sdp += commonCapabilities.codecs.map(function(codec) { 1420 | return codec.payloadType; 1421 | }).join(' ') + '\r\n'; 1422 | 1423 | sdp += 'c=IN IP4 0.0.0.0\r\n'; 1424 | sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n'; 1425 | 1426 | // Map ICE parameters (ufrag, pwd) to SDP. 1427 | sdp += self._iceParametersToSDP(iceGatherer.getLocalParameters()); 1428 | 1429 | // Map DTLS parameters to SDP. 1430 | sdp += self._dtlsParametersToSDP(dtlsTransport.getLocalParameters(), 1431 | 'active'); 1432 | 1433 | sdp += 'a=mid:' + mLine.mid + '\r\n'; 1434 | 1435 | if (rtpSender && rtpReceiver) { 1436 | sdp += 'a=sendrecv\r\n'; 1437 | } else if (rtpReceiver) { 1438 | sdp += 'a=sendonly\r\n'; 1439 | } else if (rtpSender) { 1440 | sdp += 'a=sendonly\r\n'; 1441 | } else { 1442 | sdp += 'a=inactive\r\n'; 1443 | } 1444 | sdp += 'a=rtcp-mux\r\n'; 1445 | 1446 | // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb. 1447 | sdp += self._capabilitiesToSDP(commonCapabilities); 1448 | 1449 | if (rtpSender) { 1450 | // add a=ssrc lines from RTPSender 1451 | sdp += 'a=msid:' + self.localStreams[0].id + ' ' + 1452 | rtpSender.track.id + '\r\n'; 1453 | sdp += 'a=ssrc:' + sendSSRC + ' ' + 'msid:' + 1454 | self.localStreams[0].id + ' ' + rtpSender.track.id + '\r\n'; 1455 | } 1456 | sdp += 'a=ssrc:' + sendSSRC + ' cname:' + self._cname + '\r\n'; 1457 | }); 1458 | 1459 | var desc = new RTCSessionDescription({ 1460 | type: 'answer', 1461 | sdp: sdp 1462 | // ortc: tracks -- state is created in SRD already 1463 | }); 1464 | if (arguments.length && typeof arguments[0] === 'function') { 1465 | window.setTimeout(arguments[0], 0, desc); 1466 | } 1467 | return new Promise(function(resolve) { 1468 | resolve(desc); 1469 | }); 1470 | }; 1471 | 1472 | window.RTCPeerConnection.prototype.addIceCandidate = function(candidate) { 1473 | // TODO: lookup by mid 1474 | var mLine = this.mLines[candidate.sdpMLineIndex]; 1475 | if (mLine) { 1476 | var cand = Object.keys(candidate.candidate).length > 0 ? 1477 | this._toCandidateJSON(candidate.candidate) : {}; 1478 | // dirty hack to make simplewebrtc work. 1479 | // FIXME: need another dirty hack to avoid adding candidates after this 1480 | if (cand.type === 'endOfCandidates') { 1481 | cand = {}; 1482 | } 1483 | // dirty hack to make chrome work. 1484 | if (cand.protocol === 'tcp' && cand.port === 0) { 1485 | cand = {}; 1486 | } 1487 | mLine.iceTransport.addRemoteCandidate(cand); 1488 | } 1489 | if (arguments.length > 1 && typeof arguments[1] === 'function') { 1490 | window.setTimeout(arguments[1], 0); 1491 | } 1492 | return new Promise(function(resolve) { 1493 | resolve(); 1494 | }); 1495 | }; 1496 | 1497 | window.RTCPeerConnection.prototype.getStats = function() { 1498 | var promises = []; 1499 | this.mLines.forEach(function(mLine) { 1500 | ['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport', 1501 | 'dtlsTransport'].forEach(function(thing) { 1502 | if (mLine[thing]) { 1503 | promises.push(mLine[thing].getStats()); 1504 | } 1505 | }); 1506 | }); 1507 | var cb = arguments.length > 1 && typeof arguments[1] === 'function' && 1508 | arguments[1]; 1509 | return new Promise(function(resolve) { 1510 | var results = {}; 1511 | Promise.all(promises).then(function(res) { 1512 | res.forEach(function(result) { 1513 | Object.keys(result).forEach(function(id) { 1514 | results[id] = result[id]; 1515 | }); 1516 | }); 1517 | if (cb) { 1518 | window.setTimeout(cb, 0, results); 1519 | } 1520 | resolve(results); 1521 | }); 1522 | }); 1523 | }; 1524 | } 1525 | } else { 1526 | webrtcUtils.log('Browser does not appear to be WebRTC-capable'); 1527 | } 1528 | 1529 | // Returns the result of getUserMedia as a Promise. 1530 | function requestUserMedia(constraints) { 1531 | return new Promise(function(resolve, reject) { 1532 | getUserMedia(constraints, resolve, reject); 1533 | }); 1534 | } 1535 | 1536 | var webrtcTesting = {}; 1537 | Object.defineProperty(webrtcTesting, 'version', { 1538 | set: function(version) { 1539 | webrtcDetectedVersion = version; 1540 | } 1541 | }); 1542 | 1543 | if (typeof module !== 'undefined') { 1544 | var RTCPeerConnection; 1545 | if (typeof window !== 'undefined') { 1546 | RTCPeerConnection = window.RTCPeerConnection; 1547 | } 1548 | module.exports = { 1549 | RTCPeerConnection: RTCPeerConnection, 1550 | getUserMedia: getUserMedia, 1551 | attachMediaStream: attachMediaStream, 1552 | reattachMediaStream: reattachMediaStream, 1553 | webrtcDetectedBrowser: webrtcDetectedBrowser, 1554 | webrtcDetectedVersion: webrtcDetectedVersion, 1555 | webrtcMinimumVersion: webrtcMinimumVersion, 1556 | webrtcTesting: webrtcTesting 1557 | //requestUserMedia: not exposed on purpose. 1558 | }; 1559 | } else if ((typeof require === 'function') && (typeof define === 'function')) { 1560 | // Expose objects and functions when RequireJS is doing the loading. 1561 | define([], function() { 1562 | return { 1563 | RTCPeerConnection: window.RTCPeerConnection, 1564 | getUserMedia: getUserMedia, 1565 | attachMediaStream: attachMediaStream, 1566 | reattachMediaStream: reattachMediaStream, 1567 | webrtcDetectedBrowser: webrtcDetectedBrowser, 1568 | webrtcDetectedVersion: webrtcDetectedVersion, 1569 | webrtcMinimumVersion: webrtcMinimumVersion, 1570 | webrtcTesting: webrtcTesting 1571 | //requestUserMedia: not exposed on purpose. 1572 | }; 1573 | }); 1574 | } 1575 | -------------------------------------------------------------------------------- /webrtc-load-tests/scripts/restcomm-web-client.js: -------------------------------------------------------------------------------- 1 | /* 2 | * TeleStax, Open Source Cloud Communications 3 | * Copyright 2011-2015, Telestax Inc and individual contributors 4 | * by the @authors tag. 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * under the terms of the GNU Affero General Public License as 8 | * published by the Free Software Foundation; either version 3 of 9 | * the License, or (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Affero General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Affero General Public License 17 | * along with this program. If not, see 18 | */ 19 | 20 | var wrtcClient; 21 | var wrtcEventListener = undefined; 22 | var wrtcConfiguration = undefined; 23 | var localStream; 24 | var remoteMedia; 25 | var username; 26 | var inCall = false; 27 | 28 | // Trying to hide the .js dependencies from index.html. Here are some alternatives, but none of them worked 100% correctly for me. Let's keep them around in case we revisit in the future: 29 | /* This is supposed to be jquery's way to include .js from here, but I had to change the order or 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 |
Loading RestComm client...
38 |
39 | 40 | 381 | 382 | 383 | 384 | -------------------------------------------------------------------------------- /webrtc-load-tests/webrtc-sipp-client.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | ;tag=[call_number] 31 | To: sut 32 | Call-ID: [call_id] 33 | CSeq: 1 INVITE 34 | Contact: sip:sipp@[local_ip]:[local_port] 35 | Max-Forwards: 70 36 | Subject: Performance Test 37 | Content-Type: application/sdp 38 | X-ClientId: [$clientIdString] 39 | Content-Length: [len] 40 | 41 | v=0 42 | o=user1 53655765 2353687637 IN IP[local_ip_type] [local_ip] 43 | s=- 44 | c=IN IP[media_ip_type] [media_ip] 45 | t=0 0 46 | m=audio [media_port] RTP/AVP 8 47 | a=rtpmap:8 PCMA/8000 48 | ]]> 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | ;tag=[call_number] 71 | To: sut [peer_tag_param] 72 | Call-ID: [call_id] 73 | CSeq: 1 ACK 74 | Contact: sip:sipp@[local_ip]:[local_port] 75 | Max-Forwards: 70 76 | Subject: Performance Test 77 | Content-Length: 0 78 | ]]> 79 | 80 | 81 | 82 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 96 | 97 | 98 | 99 | 100 | 103 | 104 | 105 | 106 | ;tag=[call_number] 110 | To: sut [peer_tag_param] 111 | Call-ID: [call_id] 112 | Cseq: 2 BYE 113 | Contact: sip:sipp@[local_ip]:[local_port] 114 | Max-Forwards: 70 115 | Subject: Performance Test 116 | Content-Length: 0 117 | ]]> 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | --------------------------------------------------------------------------------