├── .gitignore ├── .vscode └── launch.json ├── LICENSE ├── README.md ├── config ├── cloudfront-REPLACE.txt ├── cloudfront-cache-policy.json ├── cloudfront-origin-request-policy.json ├── cloudwatch-lambda-policy.json ├── ddb-full-access-policy.json ├── ddb-read-access-policy.json ├── ec2-role-trust-policy.json ├── lambda-role-trust-policy.json ├── live-rest-api-REPLACE.txt ├── s3-allow-cloudfront-read-policy-REPLACE.txt ├── s3-cors.json ├── s3-full-access-policy.json ├── s3-lambda-trigger-REPLACE.txt ├── s3-lifecycle.json ├── s3-public-access.json └── system-config-5renditions-1080p-REPLACE.txt ├── docs ├── grant-s3-full-access-to-ec2.md ├── index.html ├── js │ └── readUrlVars.js ├── local-aws-cli-user-permissions.md ├── pics │ ├── common-concept.png │ ├── grant-local-user-IAM-access.png │ ├── lde-aws.png │ ├── lde-concept.png │ ├── lde-demo-video.png │ ├── lde-edge.png │ ├── lde-intro-video.jpg │ ├── lde-lambda-manifest.png │ └── lde-lambda-trans.png ├── player.html ├── setup-api-gateway.md ├── setup-cloudfront.md ├── setup-ddb.md ├── setup-edge.md ├── setup-lambda-transcode-trigger.md ├── setup-lambdas.md └── setup-s3.md ├── joc-lambda-chunk-transcoder ├── ffmpeg │ └── ffmpeg ├── fonts │ └── GeorgiaPro-Black.ttf ├── index.js ├── live-transcoder-chunk-data.js ├── live-transcoder-config.js ├── local-test.js ├── package-lock.json ├── package.json └── scripts │ └── upload-lambda.sh ├── joc-lambda-manifest-generator ├── index.js ├── live-transcoder-config.js ├── local-test.js ├── package-lock.json ├── package.json └── scripts │ └── upload-lambda.sh └── scripts ├── attach-instance-profile-to-ec2.sh ├── base.sh ├── create-cloudfront.sh ├── create-ddb.sh ├── create-manifest-lambda.sh ├── create-rest-api.sh ├── create-s3-bucket.sh ├── create-s3-full-access-for-ec2.sh ├── create-trancoder-lambda.sh ├── create-transcode-trigger.sh ├── emptyLambda ├── index.js └── index.zip ├── get-api-cdn-prepend.sh └── populate-ddb.sh /.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | logs/ 3 | results/ 4 | .DS_Store 5 | /secrets/* 6 | !/secrets/*.example 7 | */node_modules -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "node", 9 | "request": "launch", 10 | "name": "Chunk-Transcoder", 11 | "skipFiles": [ 12 | "/**" 13 | ], 14 | "program": "${workspaceFolder}/joc-lambda-chunk-transcoder/local-test.js" 15 | }, 16 | { 17 | "type": "node", 18 | "request": "launch", 19 | "name": "Manigest-Generator", 20 | "skipFiles": [ 21 | "/**" 22 | ], 23 | "program": "${workspaceFolder}/joc-lambda-manifest-generator/local-test.js" 24 | }, 25 | { 26 | "name": "Launch test webpage", 27 | "type": "chrome", 28 | "request": "launch", 29 | "file": "${workspaceFolder}/web-url-generator/index.html" 30 | }, 31 | { 32 | "name": "Launch test player", 33 | "type": "chrome", 34 | "request": "launch", 35 | "file": "${workspaceFolder}/web-url-generator/player.html" 36 | } 37 | ] 38 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Serverless distributed live platform 2 | 3 | This system allows you to stream SRT (h264 + AAC) and create the live ABR in a fully distributed way. This implementation uses [AWS Lambdas](https://aws.amazon.com/lambda/) to perform a segmented serverless transcoding, this allow us to instantly scale to any type of renditions and transcoding settings, tested up to 2160p@60fps (h264 - AAC). 4 | 5 | [![How it works video](/docs/pics/lde-intro-video.jpg)](https://youtu.be/f7TkdI4f3jU) 6 | 7 | This [player demo page](https://jordicenzano.github.io/serverless-distributed-live-platform/) allows you to simple create playback URLs for this platform, and also includes a player to facilitate testing (based on [VideoJS](https://videojs.com/)) 8 | 9 | **Disclaimer: This is just a proof of concept, it is not ready / designed to run in production environments** 10 | 11 | ## Introduction 12 | In this section we will compare the common approach of "single host linear live transcoding" vs the one presented in this repo "distributed live transcoding" 13 | 14 | ### Single host linear live transcoding 15 | 16 | Nowadays for livestreaming the most used architecture is to use single host to create [ABR ladder](https://en.wikipedia.org/wiki/Adaptive_bitrate_streaming) needed for distribution, see figure 2 17 | 18 | 19 | ![block diagram](./docs/pics/common-concept.png) 20 | *Figure 2: Single host linear live transcoding concept* 21 | 22 | This is a simple and good approach, but it some problems: **scalability**, **flexibility**, **reliability**. 23 | 24 | #### Scalability problem in linear transcoding 25 | 26 | When we ask the transcoding machine for more that it can handle, the machine starts transcoding **slower tan real time**, and this is a time bomb for live. The player will start stalling, and (depending on the implementation) that machine will OOM or drop data. 27 | Log story short: Awful user experience 28 | 29 | #### Flexibility problem in linear transcoding 30 | 31 | When the stream starts we can evaluate what are the best encoding params for each lane, but after this point it could be quite difficult to re-evaluate those encoding params. 32 | 33 | Imagine the situation where we are resource constrained when the stream starts and we decide to apply fast encoding presets (so low quality) to save some CPU capacity, but few minutes after we have a lot of free resources, in this approach is quite difficult to update those encoding params 34 | 35 | #### Reliability problem in linear transcoding 36 | 37 | We have one machine managing all the stream transcoding, if this **single** machine goes down, we lose the stream. 38 | We can always mitigate that risk duplicating the transcoding stage, it can be done but it has some synchronization challenges 39 | 40 | ### Distributed live transcoding 41 | 42 | In this approach the transcoding is performed in small temporal chunks. 43 | The 1st step is to slice the continuos input stream in small (playable) chunks, then we can send those chunks to stateless transcoders, and finally those transcoders can generate the renditions for each individual chunk. See figure 3 44 | 45 | ![LDE concept](./docs/pics/lde-concept.png) 46 | *Figure 3: Distributed live transcoding concept* 47 | 48 | #### Advantages of distributed live transcoding 49 | - **Reliability**: If any transcoder machine goes down the stream will not be affected. That chunk is retry-able, or we could double transcode for important streams 50 | 51 | - **Scalability**: You do not need to buy bigger machines to use more complex codecs / higher resolution - framerates, just use more of them (horizontal scaling for live transcoding) 52 | 53 | - **Flexibility**: You can reevaluate your decisions every few seconds, so you can update (some) encoding settings at any time to meet any criteria 54 | 55 | - **Deployability**: You can deploy any transcoding machine at any time without affecting the streams, this ability is "baked" into the architecture 56 | 57 | #### Problems of distributed live transcoding 58 | - **Decoder buffer size for VBV**: You will need to manage the decoder buffer size knowing that you will not have the data from previous chunk when you start the encoding 59 | - **GOP Size**: The transcoding time will be proportional that, so if you are interested in providing some target latency you need to be able to control (limit) the input GOP size. Remember the shortest playable unit is a GOP. Also you need closed GOPs. 60 | - **Audio priming**: In some audio codecs you need the last samples from previous chunk to be able to properly decode the current chunk audio, see this [post](https://developer.apple.com/library/archive/documentation/QuickTime/QTFF/QTFFAppenG/QTFFAppenG.html) for more info 61 | - **Latency**: If you are planning to use encoders / resolution that your transcoding machines can NOT handle in real time (for instance AV1 4K), then you should expect an increased latency. But in this case I think is totally OK, because you can NOT do that in linear approach, now you can totally do it and the price to pay is "just" latency 62 | 63 | ## Distributed live streaming based on AWS lambdas 64 | This is what we implemented in this repo 65 | 66 | ![LDE block diagram](./docs/pics/lde-aws.png) 67 | *Figure 4: Distributed live streaming based on AWS lambdas* 68 | 69 | ### Edge EC2 (ingest + slicer) 70 | ![LDE Edge EC2 contents](./docs/pics/lde-edge.png) 71 | *Figure 5: Distributed live Edge EC2 contents* 72 | 73 | - It terminates the [SRT protocol](https://github.com/Haivision/srt) and transmuxes the media to [Transport Stream (TS)](https://en.wikipedia.org/wiki/MPEG_transport_stream), all of these is done with a simple [ffmpeg](https://ffmpeg.org/) command 74 | 75 | ```bash 76 | # Start RTMP listener / transmuxer to TS 77 | ffmpeg -hide_banner -y \ 78 | -i "srt://0.0.0.0:1935?mode=listener" \ 79 | -c:v copy -c:a copy \ 80 | -f mpegts "tcp://localhost:2002" 81 | ``` 82 | 83 | - Uses this open source project [go-ts-segmenter](https://github.com/jordicenzano/go-ts-segmenter) to slice the input TS and upload the resulting chunks to [S3](https://aws.amazon.com/s3/). In these stage we also add the following info to each chunk in form of HTTP headers 84 | - Target suration in ms: `x-amz-meta-joc-hls-targetduration-ms` 85 | - Real duration in ms (for regular latency mode): `x-amz-meta-joc-hls-duration-ms` 86 | - Epoch time the chunk was created in the slicer in ns: `x-amz-meta-joc-hls-createdat-ns` 87 | - Sequence number of that chunk: `x-amz-meta-joc-hls-chunk-seq-number` 88 | 89 | ### Chunk transcoder lambda 90 | Every time a chunk is uploaded from ingest to S3, the [joc-lambda-chunk-transcoder](./joc-lambda-chunk-transcoder/index.js) is automatically invoked. 91 | This lambda contains an `ffmpeg` binary compiled to run inside of AWS Lambda environment 92 | 93 | One of the advantages of using Lambdas is that they provide a deterministic execution framework, meaning if we have a problem transcoding chunk N, it is really easy to repro that problem, using the same code version, and input. 94 | 95 | ![LDE lambda transcoding](./docs/pics/lde-lambda-trans.png) 96 | *Figure 5: Distributed live lambda transcoding* 97 | 98 | This stateless function performs the following actions: 99 | - Reads the current config for that stream from [DynamoDB](https://aws.amazon.com/dynamodb/), that includes the encoding params, see example of that config: 100 | ```json 101 | { 102 | "config-name": "default", 103 | "desc": "4K (7 renditions)", 104 | "value": { 105 | "copyOriginalContentTypeToABRChunks": true, 106 | "copyOriginalMetadataToABRChunks": true, 107 | "mediaCdnPrefix": "https://MY-ID.cloudfront.net", 108 | "overlayEncodingData": true, 109 | "overlayMessage": "Test-", 110 | "publicReadToABRChunks": false, 111 | "renditions": [ 112 | { 113 | "height": 2160, 114 | "ID": "2160p", 115 | "video_buffersize": 14000000, 116 | "video_crf": 23, 117 | "video_h264_bpyramid": "strict", 118 | "video_h264_preset": "slow", 119 | "video_h264_profile": "high", 120 | "video_maxrate": 7000000, 121 | "width": 3840 122 | }, 123 | ... 124 | { 125 | "height": 144, 126 | "ID": "144p", 127 | "video_buffersize": 200000, 128 | "video_crf": 23, 129 | "video_h264_bpyramid": "strict", 130 | "video_h264_preset": "slow", 131 | "video_h264_profile": "high", 132 | "video_maxrate": 100000, 133 | "width": 256 134 | } 135 | ], 136 | "s3OutputPrefix": "output/", 137 | "video_pix_fmt": "yuv420p" 138 | } 139 | } 140 | ``` 141 | Note: To tune h264 transcode you can add the item `video_x264_params` to each rendition 142 | 143 | - Applies that config and transcodes the input chunk (the one specified un the [S3 event](https://docs.aws.amazon.com/AmazonS3/latest/dev/notification-content-structure.html)) 144 | 145 | - It upload the resulting renditions S3, following the read config 146 | 147 | - It updates the DynamoDB chunks table with the recently created chunks info, see an entry example: 148 | ```json 149 | { 150 | "duration-ms": 2002, 151 | "file-path": "20210101222117/144p/source_00131.ts", 152 | "first-audio-ts": -1, 153 | "first-video-ts": -1, 154 | "rendition-id": "144p", 155 | "s3bucket": "live-dist-test", 156 | "s3objkey": "output/20210101222117/144p/source_00131.ts", 157 | "seq-number": 131, 158 | "stream-id": "20210101222117", 159 | "target-duration-ms": 2000, 160 | "uid": "0ef4a832-5c83-4c70-bf92-bdcdf6305e4e", 161 | "wallclock-epoch-ns": 1609539942573507463 162 | } 163 | ``` 164 | 165 | ### Manifest generator lambda 166 | To allow the playback of that live stream we implemented a "minimalist" manifest service inside a Lambda that creates an HLS manifest on the fly based on the info in DynamoDB. 167 | 168 | This function is invoked when a players asks for a manifest, so when a player `GET` a URL like this: 169 | 170 | ``` 171 | https://API-CDN-PREPEND/video/streamId/manifest.m3u8?SEE-QS-POSSIBILITIES 172 | ``` 173 | OR 174 | ``` 175 | https://API-CDN-PREPEND/video/streamId/renditionID/chunklist.m3u8?SEE-QS-POSSIBILITIES 176 | ``` 177 | 178 | Valid querystring (QS) parameters are: 179 | - `liveType` (default = `live`): Indicates what manifest we want (`live`, `event`, `vod`) 180 | - **This param allows you to create (chunk accurate) highlights before live ends (`vod`), or activate live rewind (`event`)** 181 | - `chunksNumber` (default = 3): Indicate how many chunks we want in the response 182 | - Only valid if `liveType == live` 183 | - `latency` (default = 20): Indicate how many seconds of latency you want to add. 184 | - This is recommended to be equal or bigger to the transcoding time for your longer / more complex chunk 185 | - `chunksLatency` (default = 0): Indicate how many chunks of latency you want to add, so the last chunk in your manifest will ne the last one generated - `chunksLatency` chunks 186 | - This is recommended to be equal or bigger to the last possible transcoding time for your longer chunk 187 | - If you set `latency` takes precedence over this 188 | - `fromEpochS` (default = -1): epoch time in seconds to start getting chunks 189 | - `toEpochS` (default = -1): epoch time in seconds to stop getting chunks 190 | - Only valid if `liveType == vod` 191 | - **Very useful to create VOD highlights from an ongoing live stream**, in combination with `fromEpochS` 192 | 193 | ![LDE lambda manifest](./docs/pics/lde-lambda-manifest.png) 194 | *Figure 6: Distributed live lambda manifest* 195 | 196 | - For the `manifest.m3u8` this Lambda 197 | - Gets stream config from DynamoDB and returns the chunklists copying the QS params 198 | - For the `chunklist.m3u8` 199 | - Reads the `streamId`, `renditionId`, and QS params 200 | - Creates a query to DynamoDB 201 | - Generated a valid [HLS](https://tools.ietf.org/html/draft-pantos-http-live-streaming-23) manifest based in the query results 202 | - API Gateway caches that result (cache key included QS) 203 | 204 | ### CDN + API Gateway cache 205 | To isolate our backend from the number of players we added a CDN that is used to serve the chunks. 206 | 207 | #### Chunks 208 | We added a Cloudfront file distribution with origin shield activated on top of the S3 209 | - TTL: Could be very large, they are NOT mutable, and they are the same for VOD (highlights) and LIVE 210 | - Cache key: It is the URL path 211 | 212 | The URL structure for the chunks is like: 213 | ``` 214 | https://CDN-PREPEND/streamID/reditionID/base_00000.ts 215 | ``` 216 | 217 | #### Manifests 218 | We we also activated the cache on [API Gateway](https://aws.amazon.com/api-gateway/) to serve the manifests. 219 | - TTL: We used short TTL because `chunklists.m3u8` is updated every `TARGET-DURATION` 220 | - Cache key: It is the URL path AND the querystring parameters 221 | 222 | ### Some metrics 223 | 224 | After proving the system works we gathered few basic metrics, for that we used 2 types of live streams: 225 | 226 | - **HM**: High motion stream, it is a professionally produced 4K HDR sports VOD stream (that we transcoded to the desired settings and converted into a live stream using transmuxing and loop) 227 | - 2160p@59.94 20Mbps h264-AAC, 2s GOP 228 | - **LM**: Low motion stream, generated from IPhone Xs with [Larix](https://softvelum.com/larix/) app 229 | - 2160p@30 12Mbps h264-AAC, 2s GOP 230 | - 1080p@30 12Mbps h264-AAC, 2s GOP 231 | 232 | For the following test we have used: 233 | - Lambda RAM: **10240MB (highest CPU)** 234 | - Cost per ms: $0.0000001667 235 | - Segmenter chunk size: **2s** 236 | - Encoding presets: 237 | - **SL7R**: 238 | - 7 renditions: 2160p, 1080p, 720p, 480p, 360p, 240p, 144p 239 | - h264 High, preset SLOW 240 | - **VF7R**: 241 | - 7 renditions: 2160p, 1080p, 720p, 480p, 360p, 240p, 144p 242 | - h264 High, preset VERYFAST 243 | - **SL6R**: 244 | - 6 renditions: 1080p, 720p, 480p, 360p, 240p, 144p 245 | - h264 High, preset SLOW 246 | 247 | In the following table you can see the avg and max transcoding Lambda execution time in ms. 248 | 249 | *Remember Lambdas are billed by execution time, so we can easily calculate the CPU transcoding cost from those values and segmenter chunk size: 250 | Number of lambdas invoked per hour = (60\*60)/ChunkLength(s)* 251 | 252 | | Video | Enc preset | Exec. time Avg (ms) | Exec. time Max (ms) | Transc. latency (s) | Transc. cost per 1h | 253 | | -------- |:----------:| --------:|---------:| -------------------:|--------------------:| 254 | | LM 1080p | SL6R | 4000 | 5000 | **5** | **$1.2** | 255 | | LM 4K | SL7R | 11000 | 14109 | **15** | **$3.3** | 256 | | HM 4K | VF7R | 14741 | 19828 | **20** | **$4.4** | 257 | | HM 4K | SL7R | 20000 | 32721 | **33** | **$6.0** | 258 | 259 | Note: Cost calculated based on: 260 | - Lambda 10240MB (max CPU) and price at 2021/02/15 in VA: $0.0000001667/ms 261 | - 2s chunk size -> 1800 invokes/hour 262 | 263 | #### Metrics takeaways 264 | - **Transcoding latency (Content dependency)**: In linear transcoders we are used to have a deterministic latency, probably around 1 GOP. Now we are adding another variable that is the source content complexity, and that is usually out of our control. 265 | 266 | - **Latency knob (Latency vs Quality)**: This system offers us the ability to reduce the induced transcoding latency decreasing the video quality (faster presets), and we can do that mid-stream 267 | 268 | - **Cost knob (Cost vs Quality)**: The transcoding time is our cost, so that means if we want more quality we just need to apply slower presets, then latency will go up and our cost too. 269 | The same works the other way, if we want to pay less just apply faster preset, then cost, quality, and latency will go down. 270 | 271 | *Note: For those takeaways we assumed the machine type (lambda type) is fixed, but in reality that is another know (machine size vs latency)* 272 | 273 | # Learnings and Challenges 274 | - Encoder rate - control 275 | - The next chunk N does NOT know about previous one (N-1), then we need to apply some constraints on the encoder rate - control algorithm to make sure the decoding buffer size is under control 276 | - Variable scene complexity 277 | - Scenes with different complexity would need different encoding times, in this approach we need predictable (or limited) encoding time 278 | - Variable input GOP size 279 | - Variable input GOP size is huge problem for this approach, since chunk transcoding times should be predictable (or limited) 280 | - Audio Priming 281 | - To properly decode audio, in some codecs we need samples from the previous chunks, see more info [here](https://developer.apple.com/library/archive/documentation/QuickTime/QTFF/QTFFAppenG/QTFFAppenG.html) 282 | 283 | # Set up the environment 284 | This part will help you to set up your AWS account to test this code. 285 | We are assuming you have [AWS CLI](https://aws.amazon.com/cli/) installed and configured properly in your system 286 | 287 | *Note: Please follow the order below, there are some dependencies on those steps* 288 | 289 | - Modify the vars `AWS_REGION` and `BASE_NAME` from [base.sh](./scripts/base.sh) with your region and base name 290 | - [Allow RW permissions to your local AWS CLI user](./doc/../docs/local-aws-cli-user-permissions.md) 291 | - [Set up edge machine](./docs/setup-edge.md) 292 | - [Set up S3 bucket](./docs/setup-s3.md) 293 | - [Give EC2 RW permissions to your S3](./docs/grant-s3-full-access-to-ec2.md) 294 | - [Set up Lambdas(create execution roles, lambdas, and upload code)](./docs/setup-lambdas.md) 295 | - [Set up transcode lambda trigger to new ingest files](./docs/setup-lambda-transcode-trigger.md) 296 | - [Set up CloudFront as media CDN](./docs/create-cloudfront.md) 297 | - [Set up and populate dynamoDB](./docs/setup-ddb.md) 298 | - [Set up API Gateway (and manifest lambda trigger)](./docs/setup-api-gateway.md) 299 | 300 | # Test / Demo 301 | This video will show you how to do some initial tests: 302 | [![Demo video](./docs/pics/lde-demo-video.png)](https://youtu.be/qRWk_fXULUE) 303 | 304 | Notes: 305 | - The API CDN prepend will have this format: `https://API-ID.execute-api.AWS-REGION.amazonaws.com/prod/video`. You can get the API CDN prepend doing: 306 | ``` 307 | cd scripts 308 | ./get-api-cdn-prepend.sh 309 | ``` 310 | - You can use this [player demo page](https://jordicenzano.github.io/serverless-distributed-live-platform/) to generate playback URLs 311 | 312 | # TODOs 313 | - Create a cloudformation template for AWS infrastructure. Or create a simple and better AWS CLI script 314 | - Use a storage more adequate for live streaming than S3 -------------------------------------------------------------------------------- /config/cloudfront-REPLACE.txt: -------------------------------------------------------------------------------- 1 | { 2 | "DistributionConfig": { 3 | "CallerReference": "20210221211400", 4 | "Aliases": { 5 | "Quantity": 0 6 | }, 7 | "DefaultRootObject": "", 8 | "Origins": { 9 | "Quantity": 1, 10 | "Items": [ 11 | { 12 | "Id": "S3-MediaOutput", 13 | "DomainName": "<>.s3.amazonaws.com", 14 | "OriginPath": "/output", 15 | "CustomHeaders": { 16 | "Quantity": 0 17 | }, 18 | "S3OriginConfig": { 19 | "OriginAccessIdentity": "origin-access-identity/cloudfront/<>" 20 | }, 21 | "ConnectionAttempts": 3, 22 | "ConnectionTimeout": 10, 23 | "OriginShield": { 24 | "Enabled": true, 25 | "OriginShieldRegion": "<>" 26 | } 27 | } 28 | ] 29 | }, 30 | "OriginGroups": { 31 | "Quantity": 0 32 | }, 33 | "DefaultCacheBehavior": { 34 | "TargetOriginId": "S3-MediaOutput", 35 | "TrustedSigners": { 36 | "Enabled": false, 37 | "Quantity": 0 38 | }, 39 | "TrustedKeyGroups": { 40 | "Enabled": false, 41 | "Quantity": 0 42 | }, 43 | "ViewerProtocolPolicy": "redirect-to-https", 44 | "AllowedMethods": { 45 | "Quantity": 3, 46 | "Items": [ 47 | "HEAD", 48 | "GET", 49 | "OPTIONS" 50 | ], 51 | "CachedMethods": { 52 | "Quantity": 3, 53 | "Items": [ 54 | "HEAD", 55 | "GET", 56 | "OPTIONS" 57 | ] 58 | } 59 | }, 60 | "SmoothStreaming": false, 61 | "Compress": false, 62 | "LambdaFunctionAssociations": { 63 | "Quantity": 0 64 | }, 65 | "FieldLevelEncryptionId": "", 66 | "CachePolicyId": "<>", 67 | "OriginRequestPolicyId": "<>" 68 | }, 69 | "CacheBehaviors": { 70 | "Quantity": 0 71 | }, 72 | "CustomErrorResponses": { 73 | "Quantity": 0 74 | }, 75 | "Comment": "", 76 | "Logging": { 77 | "Enabled": false, 78 | "IncludeCookies": false, 79 | "Bucket": "", 80 | "Prefix": "" 81 | }, 82 | "PriceClass": "PriceClass_All", 83 | "Enabled": true, 84 | "ViewerCertificate": { 85 | "CloudFrontDefaultCertificate": true, 86 | "MinimumProtocolVersion": "TLSv1", 87 | "CertificateSource": "cloudfront" 88 | }, 89 | "Restrictions": { 90 | "GeoRestriction": { 91 | "RestrictionType": "none", 92 | "Quantity": 0 93 | } 94 | }, 95 | "WebACLId": "", 96 | "HttpVersion": "http2", 97 | "IsIPV6Enabled": true 98 | }, 99 | "Tags": { 100 | "Items": [ 101 | { 102 | "Key": "Name", 103 | "Value": "<>" 104 | } 105 | ] 106 | } 107 | } -------------------------------------------------------------------------------- /config/cloudfront-cache-policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Comment": "HLS, uses path + QS for cache key", 3 | "Name": "lde-HLS-ALL-QS", 4 | "DefaultTTL": 86400, 5 | "MaxTTL": 31536000, 6 | "MinTTL": 1, 7 | "ParametersInCacheKeyAndForwardedToOrigin": { 8 | "EnableAcceptEncodingGzip": true, 9 | "EnableAcceptEncodingBrotli": true, 10 | "HeadersConfig": { 11 | "HeaderBehavior": "none" 12 | }, 13 | "CookiesConfig": { 14 | "CookieBehavior": "none" 15 | }, 16 | "QueryStringsConfig": { 17 | "QueryStringBehavior": "all" 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /config/cloudfront-origin-request-policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Comment": "Policy for S3 origin with CORS", 3 | "Name": "lde-S3Origin", 4 | "HeadersConfig": { 5 | "HeaderBehavior": "whitelist", 6 | "Headers": { 7 | "Quantity": 3, 8 | "Items": [ 9 | "origin", 10 | "access-control-request-headers", 11 | "access-control-request-method" 12 | ] 13 | } 14 | }, 15 | "CookiesConfig": { 16 | "CookieBehavior": "none" 17 | }, 18 | "QueryStringsConfig": { 19 | "QueryStringBehavior": "none" 20 | } 21 | } -------------------------------------------------------------------------------- /config/cloudwatch-lambda-policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": "logs:CreateLogGroup", 7 | "Resource": "*" 8 | }, 9 | { 10 | "Effect": "Allow", 11 | "Action": [ 12 | "logs:CreateLogStream", 13 | "logs:PutLogEvents" 14 | ], 15 | "Resource": [ 16 | "*" 17 | ] 18 | } 19 | ] 20 | } -------------------------------------------------------------------------------- /config/ddb-full-access-policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Action": [ 6 | "dynamodb:*", 7 | "dax:*", 8 | "application-autoscaling:DeleteScalingPolicy", 9 | "application-autoscaling:DeregisterScalableTarget", 10 | "application-autoscaling:DescribeScalableTargets", 11 | "application-autoscaling:DescribeScalingActivities", 12 | "application-autoscaling:DescribeScalingPolicies", 13 | "application-autoscaling:PutScalingPolicy", 14 | "application-autoscaling:RegisterScalableTarget", 15 | "cloudwatch:DeleteAlarms", 16 | "cloudwatch:DescribeAlarmHistory", 17 | "cloudwatch:DescribeAlarms", 18 | "cloudwatch:DescribeAlarmsForMetric", 19 | "cloudwatch:GetMetricStatistics", 20 | "cloudwatch:ListMetrics", 21 | "cloudwatch:PutMetricAlarm", 22 | "cloudwatch:GetMetricData", 23 | "datapipeline:ActivatePipeline", 24 | "datapipeline:CreatePipeline", 25 | "datapipeline:DeletePipeline", 26 | "datapipeline:DescribeObjects", 27 | "datapipeline:DescribePipelines", 28 | "datapipeline:GetPipelineDefinition", 29 | "datapipeline:ListPipelines", 30 | "datapipeline:PutPipelineDefinition", 31 | "datapipeline:QueryObjects", 32 | "ec2:DescribeVpcs", 33 | "ec2:DescribeSubnets", 34 | "ec2:DescribeSecurityGroups", 35 | "iam:GetRole", 36 | "iam:ListRoles", 37 | "kms:DescribeKey", 38 | "kms:ListAliases", 39 | "sns:CreateTopic", 40 | "sns:DeleteTopic", 41 | "sns:ListSubscriptions", 42 | "sns:ListSubscriptionsByTopic", 43 | "sns:ListTopics", 44 | "sns:Subscribe", 45 | "sns:Unsubscribe", 46 | "sns:SetTopicAttributes", 47 | "lambda:CreateFunction", 48 | "lambda:ListFunctions", 49 | "lambda:ListEventSourceMappings", 50 | "lambda:CreateEventSourceMapping", 51 | "lambda:DeleteEventSourceMapping", 52 | "lambda:GetFunctionConfiguration", 53 | "lambda:DeleteFunction", 54 | "resource-groups:ListGroups", 55 | "resource-groups:ListGroupResources", 56 | "resource-groups:GetGroup", 57 | "resource-groups:GetGroupQuery", 58 | "resource-groups:DeleteGroup", 59 | "resource-groups:CreateGroup", 60 | "tag:GetResources", 61 | "kinesis:ListStreams", 62 | "kinesis:DescribeStream", 63 | "kinesis:DescribeStreamSummary" 64 | ], 65 | "Effect": "Allow", 66 | "Resource": "*" 67 | }, 68 | { 69 | "Action": "cloudwatch:GetInsightRuleReport", 70 | "Effect": "Allow", 71 | "Resource": "arn:aws:cloudwatch:*:*:insight-rule/DynamoDBContributorInsights*" 72 | }, 73 | { 74 | "Action": [ 75 | "iam:PassRole" 76 | ], 77 | "Effect": "Allow", 78 | "Resource": "*", 79 | "Condition": { 80 | "StringLike": { 81 | "iam:PassedToService": [ 82 | "application-autoscaling.amazonaws.com", 83 | "application-autoscaling.amazonaws.com.cn", 84 | "dax.amazonaws.com" 85 | ] 86 | } 87 | } 88 | }, 89 | { 90 | "Effect": "Allow", 91 | "Action": [ 92 | "iam:CreateServiceLinkedRole" 93 | ], 94 | "Resource": "*", 95 | "Condition": { 96 | "StringEquals": { 97 | "iam:AWSServiceName": [ 98 | "replication.dynamodb.amazonaws.com", 99 | "dax.amazonaws.com", 100 | "dynamodb.application-autoscaling.amazonaws.com", 101 | "contributorinsights.dynamodb.amazonaws.com", 102 | "kinesisreplication.dynamodb.amazonaws.com" 103 | ] 104 | } 105 | } 106 | } 107 | ] 108 | } -------------------------------------------------------------------------------- /config/ddb-read-access-policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Action": [ 6 | "application-autoscaling:DescribeScalableTargets", 7 | "application-autoscaling:DescribeScalingActivities", 8 | "application-autoscaling:DescribeScalingPolicies", 9 | "cloudwatch:DescribeAlarmHistory", 10 | "cloudwatch:DescribeAlarms", 11 | "cloudwatch:DescribeAlarmsForMetric", 12 | "cloudwatch:GetMetricStatistics", 13 | "cloudwatch:ListMetrics", 14 | "cloudwatch:GetMetricData", 15 | "datapipeline:DescribeObjects", 16 | "datapipeline:DescribePipelines", 17 | "datapipeline:GetPipelineDefinition", 18 | "datapipeline:ListPipelines", 19 | "datapipeline:QueryObjects", 20 | "dynamodb:BatchGetItem", 21 | "dynamodb:Describe*", 22 | "dynamodb:List*", 23 | "dynamodb:GetItem", 24 | "dynamodb:Query", 25 | "dynamodb:Scan", 26 | "dynamodb:PartiQLSelect", 27 | "dax:Describe*", 28 | "dax:List*", 29 | "dax:GetItem", 30 | "dax:BatchGetItem", 31 | "dax:Query", 32 | "dax:Scan", 33 | "ec2:DescribeVpcs", 34 | "ec2:DescribeSubnets", 35 | "ec2:DescribeSecurityGroups", 36 | "iam:GetRole", 37 | "iam:ListRoles", 38 | "kms:DescribeKey", 39 | "kms:ListAliases", 40 | "sns:ListSubscriptionsByTopic", 41 | "sns:ListTopics", 42 | "lambda:ListFunctions", 43 | "lambda:ListEventSourceMappings", 44 | "lambda:GetFunctionConfiguration", 45 | "resource-groups:ListGroups", 46 | "resource-groups:ListGroupResources", 47 | "resource-groups:GetGroup", 48 | "resource-groups:GetGroupQuery", 49 | "tag:GetResources", 50 | "kinesis:ListStreams", 51 | "kinesis:DescribeStream", 52 | "kinesis:DescribeStreamSummary" 53 | ], 54 | "Effect": "Allow", 55 | "Resource": "*" 56 | }, 57 | { 58 | "Action": "cloudwatch:GetInsightRuleReport", 59 | "Effect": "Allow", 60 | "Resource": "arn:aws:cloudwatch:*:*:insight-rule/DynamoDBContributorInsights*" 61 | } 62 | ] 63 | } -------------------------------------------------------------------------------- /config/ec2-role-trust-policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Principal": { "Service": "ec2.amazonaws.com"}, 7 | "Action": "sts:AssumeRole" 8 | } 9 | ] 10 | } -------------------------------------------------------------------------------- /config/lambda-role-trust-policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Principal": { 7 | "Service": "lambda.amazonaws.com" 8 | }, 9 | "Action": "sts:AssumeRole" 10 | } 11 | ] 12 | } -------------------------------------------------------------------------------- /config/live-rest-api-REPLACE.txt: -------------------------------------------------------------------------------- 1 | { 2 | "swagger" : "2.0", 3 | "info" : { 4 | "description" : "Live distributed transcoding", 5 | "version" : "2021-01-03T20:10:33Z", 6 | "title" : "<>" 7 | }, 8 | "schemes" : [ "https" ], 9 | "paths" : { 10 | "/video" : { 11 | "options" : { 12 | "consumes" : [ "application/json" ], 13 | "produces" : [ "application/json" ], 14 | "responses" : { 15 | "200" : { 16 | "description" : "200 response", 17 | "schema" : { 18 | "$ref" : "#/definitions/Empty" 19 | }, 20 | "headers" : { 21 | "Access-Control-Allow-Origin" : { 22 | "type" : "string" 23 | }, 24 | "Access-Control-Allow-Methods" : { 25 | "type" : "string" 26 | }, 27 | "Access-Control-Allow-Headers" : { 28 | "type" : "string" 29 | } 30 | } 31 | } 32 | }, 33 | "x-amazon-apigateway-integration" : { 34 | "type" : "mock", 35 | "responses" : { 36 | "default" : { 37 | "statusCode" : "200", 38 | "responseParameters" : { 39 | "method.response.header.Access-Control-Allow-Methods" : "'OPTIONS'", 40 | "method.response.header.Access-Control-Allow-Headers" : "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'", 41 | "method.response.header.Access-Control-Allow-Origin" : "'*'" 42 | } 43 | } 44 | }, 45 | "requestTemplates" : { 46 | "application/json" : "{\"statusCode\": 200}" 47 | }, 48 | "passthroughBehavior" : "when_no_match" 49 | } 50 | } 51 | }, 52 | "/video/{streamID}" : { 53 | "options" : { 54 | "consumes" : [ "application/json" ], 55 | "produces" : [ "application/json" ], 56 | "responses" : { 57 | "200" : { 58 | "description" : "200 response", 59 | "schema" : { 60 | "$ref" : "#/definitions/Empty" 61 | }, 62 | "headers" : { 63 | "Access-Control-Allow-Origin" : { 64 | "type" : "string" 65 | }, 66 | "Access-Control-Allow-Methods" : { 67 | "type" : "string" 68 | }, 69 | "Access-Control-Allow-Headers" : { 70 | "type" : "string" 71 | } 72 | } 73 | } 74 | }, 75 | "x-amazon-apigateway-integration" : { 76 | "type" : "mock", 77 | "responses" : { 78 | "default" : { 79 | "statusCode" : "200", 80 | "responseParameters" : { 81 | "method.response.header.Access-Control-Allow-Methods" : "'OPTIONS'", 82 | "method.response.header.Access-Control-Allow-Headers" : "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'", 83 | "method.response.header.Access-Control-Allow-Origin" : "'*'" 84 | } 85 | } 86 | }, 87 | "requestTemplates" : { 88 | "application/json" : "{\"statusCode\": 200}" 89 | }, 90 | "passthroughBehavior" : "when_no_match" 91 | } 92 | } 93 | }, 94 | "/video/{streamID}/manifest.m3u8" : { 95 | "get" : { 96 | "consumes" : [ "application/json" ], 97 | "produces" : [ "application/vnd.apple.mpegurl" ], 98 | "parameters" : [ { 99 | "name" : "latency", 100 | "in" : "query", 101 | "required" : false, 102 | "type" : "string" 103 | }, { 104 | "name" : "fromEpochS", 105 | "in" : "query", 106 | "required" : false, 107 | "type" : "string" 108 | }, { 109 | "name" : "liveType", 110 | "in" : "query", 111 | "required" : false, 112 | "type" : "string" 113 | }, { 114 | "name" : "chunksLatency", 115 | "in" : "query", 116 | "required" : false, 117 | "type" : "string" 118 | }, { 119 | "name" : "chunksNumber", 120 | "in" : "query", 121 | "required" : false, 122 | "type" : "string" 123 | }, { 124 | "name" : "alternateChunkStreamID", 125 | "in" : "query", 126 | "required" : false, 127 | "type" : "string" 128 | }, { 129 | "name" : "streamID", 130 | "in" : "path", 131 | "required" : true, 132 | "type" : "string" 133 | } ], 134 | "responses" : { 135 | "200" : { 136 | "description" : "200 response", 137 | "schema" : { 138 | "$ref" : "#/definitions/Empty" 139 | }, 140 | "headers" : { 141 | "Access-Control-Allow-Origin" : { 142 | "type" : "string" 143 | } 144 | } 145 | }, 146 | "400" : { 147 | "description" : "400 response" 148 | }, 149 | "500" : { 150 | "description" : "500 response" 151 | } 152 | }, 153 | "x-amazon-apigateway-integration" : { 154 | "type" : "aws", 155 | "uri" : "arn:aws:apigateway:<>:lambda:path/2015-03-31/functions/<>/invocations", 156 | "httpMethod" : "POST", 157 | "responses" : { 158 | "default" : { 159 | "statusCode" : "200", 160 | "responseParameters" : { 161 | "method.response.header.Access-Control-Allow-Origin" : "'*'" 162 | }, 163 | "responseTemplates" : { 164 | "application/json" : "$input.path('$.body')\n#set($context.responseOverride.header.Cache-Control = $input.path('$.headers.Cache-Control'))\n#set($context.responseOverride.status = $input.path('$.statusCode'))\n#set($context.responseOverride.header.Access-Control-Allow-Headers = 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token')\n#set($context.responseOverride.header.Access-Control-Allow-Methods = 'GET,OPTIONS')\n#set($context.responseOverride.header.Access-Control-Allow-Origin = '*')" 165 | } 166 | } 167 | }, 168 | "requestTemplates" : { 169 | "application/json" : "{\n \"pathParameters\": {\n \"streamID\": \"$input.params('streamID')\",\n \"renditionID\": \"$input.params('renditionID')\"\n },\n \"queryStringParameters\": {\n \"liveType\": \"$input.params('liveType')\", \n \"chunksLatency\": \"$input.params('chunksLatency')\",\n \"fromEpochS\": \"$input.params('fromEpochS')\",\n \"chunksNumber\": \"$input.params('chunksNumber')\",\n \"alternateChunkStreamID\": \"$input.params('alternateChunkStreamID')\",\n \"toEpochS\": \"$input.params('toEpochS')\",\n \"latency\": \"$input.params('latency')\"\n }\n}" 170 | }, 171 | "passthroughBehavior" : "when_no_templates", 172 | "cacheNamespace" : "ap2wsj", 173 | "cacheKeyParameters" : [ "method.request.path.streamID", "method.request.querystring.chunksLatency", "method.request.querystring.chunksNumber", "method.request.querystring.alternateChunkStreamID", "method.request.querystring.fromEpochS", "method.request.querystring.liveType", "method.request.querystring.latency" ], 174 | "contentHandling" : "CONVERT_TO_TEXT" 175 | } 176 | }, 177 | "options" : { 178 | "consumes" : [ "application/json" ], 179 | "produces" : [ "application/json" ], 180 | "responses" : { 181 | "200" : { 182 | "description" : "200 response", 183 | "schema" : { 184 | "$ref" : "#/definitions/Empty" 185 | }, 186 | "headers" : { 187 | "Access-Control-Allow-Origin" : { 188 | "type" : "string" 189 | }, 190 | "Access-Control-Allow-Methods" : { 191 | "type" : "string" 192 | }, 193 | "Access-Control-Allow-Headers" : { 194 | "type" : "string" 195 | } 196 | } 197 | } 198 | }, 199 | "x-amazon-apigateway-integration" : { 200 | "type" : "mock", 201 | "responses" : { 202 | "default" : { 203 | "statusCode" : "200", 204 | "responseParameters" : { 205 | "method.response.header.Access-Control-Allow-Methods" : "'GET,OPTIONS'", 206 | "method.response.header.Access-Control-Allow-Headers" : "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'", 207 | "method.response.header.Access-Control-Allow-Origin" : "'*'" 208 | } 209 | } 210 | }, 211 | "requestTemplates" : { 212 | "application/json" : "{\"statusCode\": 200}" 213 | }, 214 | "passthroughBehavior" : "when_no_match" 215 | } 216 | } 217 | }, 218 | "/video/{streamID}/{renditionID}" : { 219 | "options" : { 220 | "consumes" : [ "application/json" ], 221 | "produces" : [ "application/json" ], 222 | "responses" : { 223 | "200" : { 224 | "description" : "200 response", 225 | "schema" : { 226 | "$ref" : "#/definitions/Empty" 227 | }, 228 | "headers" : { 229 | "Access-Control-Allow-Origin" : { 230 | "type" : "string" 231 | }, 232 | "Access-Control-Allow-Methods" : { 233 | "type" : "string" 234 | }, 235 | "Access-Control-Allow-Headers" : { 236 | "type" : "string" 237 | } 238 | } 239 | } 240 | }, 241 | "x-amazon-apigateway-integration" : { 242 | "type" : "mock", 243 | "responses" : { 244 | "default" : { 245 | "statusCode" : "200", 246 | "responseParameters" : { 247 | "method.response.header.Access-Control-Allow-Methods" : "'OPTIONS'", 248 | "method.response.header.Access-Control-Allow-Headers" : "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'", 249 | "method.response.header.Access-Control-Allow-Origin" : "'*'" 250 | } 251 | } 252 | }, 253 | "requestTemplates" : { 254 | "application/json" : "{\"statusCode\": 200}" 255 | }, 256 | "passthroughBehavior" : "when_no_match" 257 | } 258 | } 259 | }, 260 | "/video/{streamID}/{renditionID}/chunklist.m3u8" : { 261 | "get" : { 262 | "consumes" : [ "application/json" ], 263 | "produces" : [ "application/vnd.apple.mpegurl" ], 264 | "parameters" : [ { 265 | "name" : "latency", 266 | "in" : "query", 267 | "required" : false, 268 | "type" : "string" 269 | }, { 270 | "name" : "fromEpochS", 271 | "in" : "query", 272 | "required" : false, 273 | "type" : "string" 274 | }, { 275 | "name" : "toEpochS", 276 | "in" : "query", 277 | "required" : false, 278 | "type" : "string" 279 | }, { 280 | "name" : "liveType", 281 | "in" : "query", 282 | "required" : false, 283 | "type" : "string" 284 | }, { 285 | "name" : "chunksLatency", 286 | "in" : "query", 287 | "required" : false, 288 | "type" : "string" 289 | }, { 290 | "name" : "renditionID", 291 | "in" : "path", 292 | "required" : true, 293 | "type" : "string" 294 | }, { 295 | "name" : "chunksNumber", 296 | "in" : "query", 297 | "required" : false, 298 | "type" : "string" 299 | }, { 300 | "name" : "alternateChunkStreamID", 301 | "in" : "query", 302 | "required" : false, 303 | "type" : "string" 304 | }, { 305 | "name" : "streamID", 306 | "in" : "path", 307 | "required" : true, 308 | "type" : "string" 309 | } ], 310 | "responses" : { 311 | "200" : { 312 | "description" : "200 response", 313 | "schema" : { 314 | "$ref" : "#/definitions/Empty" 315 | }, 316 | "headers" : { 317 | "Access-Control-Allow-Origin" : { 318 | "type" : "string" 319 | } 320 | } 321 | } 322 | }, 323 | "x-amazon-apigateway-integration" : { 324 | "type" : "aws", 325 | "uri" : "arn:aws:apigateway:<>:lambda:path/2015-03-31/functions/<>/invocations", 326 | "httpMethod" : "POST", 327 | "responses" : { 328 | "default" : { 329 | "statusCode" : "200", 330 | "responseParameters" : { 331 | "method.response.header.Access-Control-Allow-Origin" : "'*'" 332 | }, 333 | "responseTemplates" : { 334 | "application/json" : "$input.path('$.body')\n#set($context.responseOverride.header.Cache-Control = $input.path('$.headers.Cache-Control'))\n#set($context.responseOverride.status = $input.path('$.statusCode'))" 335 | } 336 | } 337 | }, 338 | "requestTemplates" : { 339 | "application/json" : "{\n \"pathParameters\": {\n \"streamID\": \"$input.params('streamID')\",\n \"renditionID\": \"$input.params('renditionID')\"\n },\n \"queryStringParameters\": {\n \"liveType\": \"$input.params('liveType')\", \n \"chunksLatency\": \"$input.params('chunksLatency')\",\n \"fromEpochS\": \"$input.params('fromEpochS')\",\n \"chunksNumber\": \"$input.params('chunksNumber')\",\n \"alternateChunkStreamID\": \"$input.params('alternateChunkStreamID')\",\n \"toEpochS\": \"$input.params('toEpochS')\",\n \"latency\": \"$input.params('latency')\"\n }\n}" 340 | }, 341 | "passthroughBehavior" : "when_no_templates", 342 | "cacheNamespace" : "zr3nnh", 343 | "cacheKeyParameters" : [ "method.request.path.renditionID", "method.request.path.streamID", "method.request.path.renditionID", "method.request.path.streamID", "method.request.querystring.chunksLatency", "method.request.querystring.chunksNumber", "method.request.querystring.alternateChunkStreamID", "method.request.querystring.fromEpochS", "method.request.querystring.liveType", "method.request.querystring.toEpochS", "method.request.querystring.latency" ], 344 | "contentHandling" : "CONVERT_TO_TEXT" 345 | } 346 | }, 347 | "options" : { 348 | "consumes" : [ "application/json" ], 349 | "produces" : [ "application/json" ], 350 | "responses" : { 351 | "200" : { 352 | "description" : "200 response", 353 | "schema" : { 354 | "$ref" : "#/definitions/Empty" 355 | }, 356 | "headers" : { 357 | "Access-Control-Allow-Origin" : { 358 | "type" : "string" 359 | }, 360 | "Access-Control-Allow-Methods" : { 361 | "type" : "string" 362 | }, 363 | "Access-Control-Allow-Headers" : { 364 | "type" : "string" 365 | } 366 | } 367 | } 368 | }, 369 | "x-amazon-apigateway-integration" : { 370 | "type" : "mock", 371 | "responses" : { 372 | "default" : { 373 | "statusCode" : "200", 374 | "responseParameters" : { 375 | "method.response.header.Access-Control-Allow-Methods" : "'GET,OPTIONS'", 376 | "method.response.header.Access-Control-Allow-Headers" : "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'", 377 | "method.response.header.Access-Control-Allow-Origin" : "'*'" 378 | } 379 | } 380 | }, 381 | "requestTemplates" : { 382 | "application/json" : "{\"statusCode\": 200}" 383 | }, 384 | "passthroughBehavior" : "when_no_match" 385 | } 386 | } 387 | } 388 | }, 389 | "definitions" : { 390 | "Empty" : { 391 | "type" : "object", 392 | "title" : "Empty Schema" 393 | } 394 | } 395 | } -------------------------------------------------------------------------------- /config/s3-allow-cloudfront-read-policy-REPLACE.txt: -------------------------------------------------------------------------------- 1 | { 2 | "Statement": [ 3 | { 4 | "Sid": "1", 5 | "Effect": "Allow", 6 | "Principal": { 7 | "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity <>" 8 | }, 9 | "Action": "s3:GetObject", 10 | "Resource": "arn:aws:s3:::<>/*" 11 | } 12 | ] 13 | } -------------------------------------------------------------------------------- /config/s3-cors.json: -------------------------------------------------------------------------------- 1 | { 2 | "CORSRules": [ 3 | { 4 | "AllowedHeaders": [], 5 | "AllowedMethods": ["GET"], 6 | "AllowedOrigins": ["*"], 7 | "ExposeHeaders": [] 8 | } 9 | ] 10 | } -------------------------------------------------------------------------------- /config/s3-full-access-policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": "s3:*", 7 | "Resource": "*" 8 | } 9 | ] 10 | } -------------------------------------------------------------------------------- /config/s3-lambda-trigger-REPLACE.txt: -------------------------------------------------------------------------------- 1 | { 2 | "LambdaFunctionConfigurations": [ 3 | { 4 | "LambdaFunctionArn": "<>", 5 | "Events": [ 6 | "s3:ObjectCreated:*" 7 | ], 8 | "Filter": { 9 | "Key": { 10 | "FilterRules": [ 11 | { 12 | "Name": "Prefix", 13 | "Value": "ingest/" 14 | }, 15 | { 16 | "Name": "Suffix", 17 | "Value": ".ts" 18 | } 19 | ] 20 | } 21 | } 22 | } 23 | ] 24 | } -------------------------------------------------------------------------------- /config/s3-lifecycle.json: -------------------------------------------------------------------------------- 1 | { 2 | "Rules": [ 3 | { 4 | "ID": "delete-older-files-2d", 5 | "Expiration": { 6 | "Days": 2 7 | }, 8 | "Filter": {}, 9 | "Status": "Enabled", 10 | "AbortIncompleteMultipartUpload": { 11 | "DaysAfterInitiation": 2 12 | } 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /config/s3-public-access.json: -------------------------------------------------------------------------------- 1 | { 2 | "BlockPublicAcls": true, 3 | "IgnorePublicAcls": true, 4 | "BlockPublicPolicy": true, 5 | "RestrictPublicBuckets": true 6 | } -------------------------------------------------------------------------------- /config/system-config-5renditions-1080p-REPLACE.txt: -------------------------------------------------------------------------------- 1 | { 2 | "config-name": { 3 | "S": "default" 4 | }, 5 | "desc": { 6 | "S": "1080p SLOW (Premium 5 renditions)" 7 | }, 8 | "value": { 9 | "M": { 10 | "copyOriginalContentTypeToABRChunks": { 11 | "BOOL": true 12 | }, 13 | "copyOriginalMetadataToABRChunks": { 14 | "BOOL": true 15 | }, 16 | "mediaCdnPrefix": { 17 | "S": "https://<>" 18 | }, 19 | "overlayEncodingData": { 20 | "BOOL": true 21 | }, 22 | "overlayMessage": { 23 | "S": "Test-" 24 | }, 25 | "publicReadToABRChunks": { 26 | "BOOL": false 27 | }, 28 | "renditions": { 29 | "L": [ 30 | { 31 | "M": { 32 | "height": { 33 | "N": "1080" 34 | }, 35 | "ID": { 36 | "S": "1080p" 37 | }, 38 | "video_buffersize": { 39 | "N": "12000000" 40 | }, 41 | "video_crf": { 42 | "N": "23" 43 | }, 44 | "video_h264_bpyramid": { 45 | "S": "strict" 46 | }, 47 | "video_h264_preset": { 48 | "S": "slow" 49 | }, 50 | "video_h264_profile": { 51 | "S": "high" 52 | }, 53 | "video_maxrate": { 54 | "N": "6000000" 55 | }, 56 | "width": { 57 | "N": "1920" 58 | } 59 | } 60 | }, 61 | { 62 | "M": { 63 | "height": { 64 | "N": "720" 65 | }, 66 | "ID": { 67 | "S": "720p" 68 | }, 69 | "video_buffersize": { 70 | "N": "8000000" 71 | }, 72 | "video_crf": { 73 | "N": "23" 74 | }, 75 | "video_h264_bpyramid": { 76 | "S": "strict" 77 | }, 78 | "video_h264_preset": { 79 | "S": "slow" 80 | }, 81 | "video_h264_profile": { 82 | "S": "high" 83 | }, 84 | "video_maxrate": { 85 | "N": "4000000" 86 | }, 87 | "width": { 88 | "N": "1280" 89 | } 90 | } 91 | }, 92 | { 93 | "M": { 94 | "height": { 95 | "N": "540" 96 | }, 97 | "ID": { 98 | "S": "540p" 99 | }, 100 | "video_buffersize": { 101 | "N": "4000000" 102 | }, 103 | "video_crf": { 104 | "N": "23" 105 | }, 106 | "video_h264_bpyramid": { 107 | "S": "strict" 108 | }, 109 | "video_h264_preset": { 110 | "S": "slow" 111 | }, 112 | "video_h264_profile": { 113 | "S": "high" 114 | }, 115 | "video_maxrate": { 116 | "N": "2000000" 117 | }, 118 | "width": { 119 | "N": "960" 120 | } 121 | } 122 | }, 123 | { 124 | "M": { 125 | "height": { 126 | "N": "360" 127 | }, 128 | "ID": { 129 | "S": "360p" 130 | }, 131 | "video_buffersize": { 132 | "N": "730000" 133 | }, 134 | "video_crf": { 135 | "N": "23" 136 | }, 137 | "video_h264_bpyramid": { 138 | "S": "strict" 139 | }, 140 | "video_h264_preset": { 141 | "S": "slow" 142 | }, 143 | "video_h264_profile": { 144 | "S": "high" 145 | }, 146 | "video_maxrate": { 147 | "N": "365000" 148 | }, 149 | "width": { 150 | "N": "640" 151 | } 152 | } 153 | }, 154 | { 155 | "M": { 156 | "height": { 157 | "N": "234" 158 | }, 159 | "ID": { 160 | "S": "234p" 161 | }, 162 | "video_buffersize": { 163 | "N": "290000" 164 | }, 165 | "video_crf": { 166 | "N": "23" 167 | }, 168 | "video_h264_bpyramid": { 169 | "S": "strict" 170 | }, 171 | "video_h264_preset": { 172 | "S": "slow" 173 | }, 174 | "video_h264_profile": { 175 | "S": "high" 176 | }, 177 | "video_maxrate": { 178 | "N": "145000" 179 | }, 180 | "width": { 181 | "N": "416" 182 | } 183 | } 184 | } 185 | ] 186 | }, 187 | "s3OutputPrefix": { 188 | "S": "output/" 189 | }, 190 | "video_pix_fmt": { 191 | "S": "yuv420p" 192 | } 193 | } 194 | } 195 | } -------------------------------------------------------------------------------- /docs/grant-s3-full-access-to-ec2.md: -------------------------------------------------------------------------------- 1 | # Grant EC2 edge full access to your S3 2 | Your EC2 edge machine need to upload (write) chunks to S3, so it needs write rights. To allow that: 3 | 4 | - Create an IAM role with S3 full access 5 | ```bash 6 | ./create-s3-full-access-for-ec2.sh 7 | ``` 8 | - Verify your edge machine is running and assign that created role to your Edge EC2 machine 9 | ```bash 10 | # It will ask you for the instanceID of your edge machine, replace i-XXXXXXXX for the right InstanceID 11 | ./attach-role-to-ec2.sh i-XXXXXXXX 12 | ``` 13 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Playback LDT URL generator 12 | 13 | 14 |
15 |
16 |

Live distributed transcoding playback URL generator

17 |

This for will create playback URL for LDT demo

18 |
19 |
20 | 21 | 22 |
23 |
24 | 25 | 26 |
27 |
28 | 29 | 34 |
35 |
36 | 37 |
38 | 39 |
40 | seconds 41 |
42 |
43 |
44 |
45 | 46 |
47 | 48 |
49 | 50 |
51 |
52 |
53 |
54 | 55 |
56 | 57 |
58 | 59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
Resulting playback URL
68 |
69 |
70 |
71 | 72 |
73 | 74 | 75 |
76 |
77 |
78 |
79 |
80 |
81 | 82 | 83 | 84 | 85 | 86 | 130 | 131 | -------------------------------------------------------------------------------- /docs/js/readUrlVars.js: -------------------------------------------------------------------------------- 1 | /* 2 | (c) Jordi Cenzano 2018 3 | */ 4 | 5 | 'use strict'; 6 | /* jshint esversion: 6 */ 7 | /* jslint browser: true */ 8 | /* jshint devel: true */ 9 | /* global window */ 10 | 11 | let url_vars = {}; 12 | 13 | function readUrlVars(){ 14 | url_vars = getUrlVars(); 15 | 16 | console.log(`Vars read from URL: ${JSON.stringify(url_vars)}`); 17 | 18 | if ( (typeof (url_vars.m) != 'undefined') && (url_vars.m != "") ) { 19 | const manifest_url = url_vars.m; 20 | console.log("Detected manifest url: " + manifest_url); 21 | } 22 | } 23 | 24 | function getUrlVars() { 25 | const ret = {}; 26 | // Use m in the last position if the querystring 27 | let m_is_set = false; 28 | window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { 29 | if (m_is_set) { 30 | ret.m = ret.m + '&' + key + '=' + value; 31 | } 32 | else { 33 | ret[key] = value; 34 | } 35 | 36 | if (key === 'm') { 37 | m_is_set = true; 38 | } 39 | }); 40 | 41 | return ret; 42 | } -------------------------------------------------------------------------------- /docs/local-aws-cli-user-permissions.md: -------------------------------------------------------------------------------- 1 | ## Set permissions to local AWS CLI user 2 | You should allow your local AWS CLI user to perform some actions on your AWS resources, since this user will be creating / updating those resources 3 | 4 | ![Local user needed policies](/docs/pics/grant-local-user-IAM-access.png) 5 | 6 | *Note: I recommend remove some of those policies after the initial set up (specially IAM full access policy). This is just an easy and unsafe way to avoid a permissions hassle* 7 | -------------------------------------------------------------------------------- /docs/pics/common-concept.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jordicenzano/serverless-distributed-live-platform/6bbfc5d520d9a0e874beb9c370a670097ca626ec/docs/pics/common-concept.png -------------------------------------------------------------------------------- /docs/pics/grant-local-user-IAM-access.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jordicenzano/serverless-distributed-live-platform/6bbfc5d520d9a0e874beb9c370a670097ca626ec/docs/pics/grant-local-user-IAM-access.png -------------------------------------------------------------------------------- /docs/pics/lde-aws.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jordicenzano/serverless-distributed-live-platform/6bbfc5d520d9a0e874beb9c370a670097ca626ec/docs/pics/lde-aws.png -------------------------------------------------------------------------------- /docs/pics/lde-concept.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jordicenzano/serverless-distributed-live-platform/6bbfc5d520d9a0e874beb9c370a670097ca626ec/docs/pics/lde-concept.png -------------------------------------------------------------------------------- /docs/pics/lde-demo-video.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jordicenzano/serverless-distributed-live-platform/6bbfc5d520d9a0e874beb9c370a670097ca626ec/docs/pics/lde-demo-video.png -------------------------------------------------------------------------------- /docs/pics/lde-edge.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jordicenzano/serverless-distributed-live-platform/6bbfc5d520d9a0e874beb9c370a670097ca626ec/docs/pics/lde-edge.png -------------------------------------------------------------------------------- /docs/pics/lde-intro-video.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jordicenzano/serverless-distributed-live-platform/6bbfc5d520d9a0e874beb9c370a670097ca626ec/docs/pics/lde-intro-video.jpg -------------------------------------------------------------------------------- /docs/pics/lde-lambda-manifest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jordicenzano/serverless-distributed-live-platform/6bbfc5d520d9a0e874beb9c370a670097ca626ec/docs/pics/lde-lambda-manifest.png -------------------------------------------------------------------------------- /docs/pics/lde-lambda-trans.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jordicenzano/serverless-distributed-live-platform/6bbfc5d520d9a0e874beb9c370a670097ca626ec/docs/pics/lde-lambda-trans.png -------------------------------------------------------------------------------- /docs/player.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /docs/setup-api-gateway.md: -------------------------------------------------------------------------------- 1 | # Set API Gateway 2 | 3 | - We need to create the API gateway and connect the entry points with manifest lambda 4 | - Create API gateway via OpenAPI definition 5 | - Grant permissions to API Gateway to execute lambda manifest (get Manifest and get Chunklist) 6 | - Create `prod` stage and deploy the API there 7 | - Activate cache in `prod` stage 8 | ```bash 9 | cd scripts 10 | ./create-rest-api.sh 11 | ``` 12 | 13 | *Note: remember to modify [./scripts/base.sh](../scripts/base.sh) with the names and region you want* -------------------------------------------------------------------------------- /docs/setup-cloudfront.md: -------------------------------------------------------------------------------- 1 | # Set Cloudfront as media CDN 2 | 3 | - Create CloudFront global CDN layer on top of S3 4 | - You can do that by executing: 5 | ```bash 6 | cd scripts 7 | ./create-cloudfront.sh 8 | ``` 9 | 10 | *Note: remember to modify [./scripts/base.sh](../scripts/base.sh) with the names and region you want* -------------------------------------------------------------------------------- /docs/setup-ddb.md: -------------------------------------------------------------------------------- 1 | # Set up Dynamo DB 2 | 3 | - Create table for configurations 4 | - Create table for chunks metadata with its GSI (used by manifest creation) 5 | - Populate `config` table 6 | 7 | You can do that by executing: 8 | ```bash 9 | cd scripts 10 | ./create-ddb.sh 11 | ./populate-ddb.sh 12 | ``` 13 | 14 | *Note: remember to modify [./scripts/base.sh](../scripts/base.sh) with the names and region you want* -------------------------------------------------------------------------------- /docs/setup-edge.md: -------------------------------------------------------------------------------- 1 | # Set up Edge machine 2 | 3 | - Start an EC2 machine 4 | - OS: Amazon Linux 5 | - Type: `t3.small` (or similar) 6 | - Instance Details: Default 7 | - Disc: SSD GP2 30GB 8 | - Security group 9 | - Inbound 10 | - 1935 0.0.0.0/0 TCP/UDP (SRT) 11 | - 22 0.0.0.0/0 TCP (SSH) 12 | - Outbound 13 | - ALL 0.0.0.0/0 14 | 15 | - SSH into that machine: 16 | ```bash 17 | ssh -i yourKey.pem ec2-user@EC2-IP` 18 | ``` 19 | 20 | - (optional) Install [tmux](https://github.com/tmux/tmux/wiki) 21 | ```bash 22 | sudo yum install -y tmux 23 | ``` 24 | 25 | - Install `ffmpeg` in EC2 26 | ```bash 27 | sudo yum -y update 28 | sudo yum -y install git 29 | git clone https://github.com/jordicenzano/ffmpeg-compile-centos-amazon-linux.git 30 | cd ffmpeg-compile-centos-amazon-linux 31 | ./compile-ffmpeg.sh 32 | ``` 33 | 34 | - Install go 35 | ```bash 36 | sudo yum install -y golang 37 | ``` 38 | 39 | - Install & Compile `go-ts-segmenter` 40 | ```bash 41 | cd ~ 42 | go get github.com/jordicenzano/go-ts-segmenter 43 | cd go/src/github.com/jordicenzano/go-ts-segmenter 44 | go get 45 | make 46 | ``` 47 | 48 | Note: Next steps require to have en S3 bucket already configured. Strongly recommended use a bucket in the same region the EC2 machine is 49 | 50 | - (Optional) From your laptop, upload some test media 51 | ```bash 52 | scp -i ~/.ssh/KEY.pem test.mp4 ec2-user@IP:/home/ec2-user/test.mp4 53 | ``` 54 | 55 | - (Optional) Test with file 56 | ```bash 57 | cd ~/go/src/github.com/jordicenzano/go-ts-segmenter/scripts 58 | ./transmuxed-file-to-s3.sh ~/test.mp4 S3BUCKET S3REGION 59 | ``` 60 | 61 | - (Optional) Test with srt 62 | ```bash 63 | cd ~/go/src/github.com/jordicenzano/go-ts-segmenter/scripts 64 | ./transmuxed-srt-to-s3.sh live-dist-test us-east-1 65 | ``` 66 | 67 | - Use SRT client to stream to this server. Configure video codec = h264 and audio = AAC 68 | - Example: [OBS](https://obsproject.com/) for desktop or [Larix](https://softvelum.com/larix/) for mobile 69 | - To configure your encoder you need to use the public IP of your edge EC2 machine as destination and 1935 as port -------------------------------------------------------------------------------- /docs/setup-lambda-transcode-trigger.md: -------------------------------------------------------------------------------- 1 | # Set up trigger for lambda transcode 2 | 3 | - Every time a new file is uploaded (at the end) to `/ingest` in our S3 media bucket execute a transcode lambda. **Be careful with filters, if not you will create a very expensive infinite loop** 4 | 5 | You can do that by executing: 6 | ```bash 7 | cd scripts 8 | ./create-transcode-trigger.sh 9 | ``` 10 | 11 | *Note: remember to modify [./scripts/base.sh](../scripts/base.sh) with the names and region you want* -------------------------------------------------------------------------------- /docs/setup-lambdas.md: -------------------------------------------------------------------------------- 1 | # Set up lambdas 2 | 3 | - We need to create Lambda transcode, that means: 4 | - Create execution role 5 | - Create execution policies (permissions) 6 | - Attach permissions to role 7 | - Create lambda with env options 8 | ```bash 9 | cd scripts 10 | ./create-trancode-lambda.sh 11 | ``` 12 | - Upload the code to the lambda 13 | ```bash 14 | cd joc-lambda-chunk-transcoder/scripts 15 | ./upload-lambda.sh 16 | ``` 17 | 18 | - We need to create Lambda manifest, that means: 19 | - Create execution role 20 | - Create execution policies (permissions) 21 | - Attach permissions to role 22 | - Create lambda with env options 23 | ```bash 24 | cd scripts 25 | ./create-manifest-lambda.sh 26 | ``` 27 | - Upload the code to the lambda 28 | ```bash 29 | cd joc-lambda-chunk-transcoder/scripts 30 | ./upload-lambda.sh 31 | ``` 32 | 33 | *Note: remember to modify [./scripts/base.sh](../scripts/base.sh) with the names and region you want* -------------------------------------------------------------------------------- /docs/setup-s3.md: -------------------------------------------------------------------------------- 1 | # Set up S3 bucket 2 | 3 | - Create S3 bucket (if it does not exists) 4 | - (Optional) Add a lifecycle expiration policy to avoid monotonically increasing costs 5 | 6 | You can do that by executing: 7 | ```bash 8 | cd scripts 9 | ./create-s3-bucket.sh 10 | ``` 11 | 12 | *Note: remember to modify [./scripts/base.sh](../scripts/base.sh) with the names and region you want* -------------------------------------------------------------------------------- /joc-lambda-chunk-transcoder/ffmpeg/ffmpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jordicenzano/serverless-distributed-live-platform/6bbfc5d520d9a0e874beb9c370a670097ca626ec/joc-lambda-chunk-transcoder/ffmpeg/ffmpeg -------------------------------------------------------------------------------- /joc-lambda-chunk-transcoder/fonts/GeorgiaPro-Black.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jordicenzano/serverless-distributed-live-platform/6bbfc5d520d9a0e874beb9c370a670097ca626ec/joc-lambda-chunk-transcoder/fonts/GeorgiaPro-Black.ttf -------------------------------------------------------------------------------- /joc-lambda-chunk-transcoder/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Jordi Cenzano 2020/12/06 3 | */ 4 | 5 | const child_process = require('child_process'); 6 | const aws = require('aws-sdk'); 7 | const fs = require('fs'); 8 | const path = require('path'); 9 | const { v4: uuidv4 } = require('uuid'); 10 | const tempy = require('tempy'); 11 | const LiveTranscoderConfig = require('./live-transcoder-config'); 12 | const {LiveTranscoderChunkData, ChunkData} = require('./live-transcoder-chunk-data'); 13 | 14 | const s3 = new aws.S3({ apiVersion: '2006-03-01' }); 15 | 16 | const ffmpegData = { 17 | LAMBDA_SRC: './ffmpeg/ffmpeg', 18 | LAMBDA_DST: '/tmp/ffmpeg.linux64', 19 | LOCAL: 'ffmpeg', 20 | path: '' 21 | } 22 | 23 | const fontData = { 24 | LAMBDA_SRC: './fonts/GeorgiaPro-Black.ttf', 25 | LAMBDA_DST: '/tmp/GeorgiaPro-Black.ttf', 26 | LOCAL: './fonts/GeorgiaPro-Black.ttf', 27 | path: '' 28 | } 29 | 30 | const CMD_OUT_STDERR = 'stderr'; 31 | const CMD_OUT_STDOUT = 'stdout'; 32 | 33 | const s3MetadataHeaders = { 34 | SEQ_NUMBER: 'joc-hls-chunk-seq-number', 35 | TARGET_DURATION_MS: 'joc-hls-targetduration-ms', 36 | DURATION_MS: 'joc-hls-duration-ms', 37 | WALL_CLOCK_NS: 'joc-hls-createdat-ns' 38 | } 39 | 40 | const dbbConfigDataDefault = { 41 | // General 42 | region: 'us-east-1', 43 | 44 | // Config 45 | configName: 'default', 46 | tableName: 'joc-dist-live-config', 47 | } 48 | const dbbChunksDataDefault = { 49 | // General 50 | region: 'us-east-1', 51 | 52 | // Chunks 53 | tableName: 'joc-dist-live-chunks', 54 | } 55 | 56 | // ABR data manipulation 57 | class ABRData { 58 | constructor(s3Bucket, srcS3ObjectKey, srcLocalFilePath) { 59 | this._s3Bucket = s3Bucket; 60 | this._srcS3ObjectKey = srcS3ObjectKey; 61 | this._srcLocalFilePath = srcLocalFilePath; 62 | this._srcS3Metadata = {}; 63 | this._renditionsData = []; 64 | this._ffmpegArgs = []; 65 | } 66 | 67 | get s3Bucket() { return this._s3Bucket; } 68 | get srcS3ObjectKey() { return this._srcS3ObjectKey; } 69 | get srcLocalFilePath() { return this._srcLocalFilePath; } 70 | get srcS3Metadata() { return this._srcS3Metadata; } 71 | get renditionsData() { return this._renditionsData; } 72 | get ffmpegArgs() { return this._ffmpegArgs; } 73 | 74 | set srcS3Metadata(v) { this._srcS3Metadata = v; } 75 | set ffmpegArgs(v) { this._ffmpegArgs = v; } 76 | 77 | addRenditionData(dstLocalFilePath, dstS3Bucket, srcS3ObjectKey, s3OutputPrefix, rendition) { 78 | this._renditionsData.push({ 79 | localFilePath: dstLocalFilePath, 80 | dstS3Bucket: dstS3Bucket, 81 | dstS3ObjectKey: createDstS3ObjectKey(srcS3ObjectKey, s3OutputPrefix, rendition.ID), 82 | rendition: rendition 83 | }); 84 | } 85 | } 86 | 87 | const logType = { 88 | INFO: 'info', 89 | WARN: 'warn', 90 | ERR: 'err' 91 | }; 92 | // Log function 93 | function logData(type, msg, streamID, objKey, durationMs, data) { 94 | let dataStr = `[${msg}] [${streamID}] [${objKey}] [${durationMs}]`; 95 | if (typeof(data) != 'undefined') { 96 | dataStr = dataStr + ` ${JSON.stringify(data, null, 2)}`; 97 | } 98 | if (type === logType.WARN) { 99 | console.warn(dataStr); 100 | } else if (type === logType.ERR) { 101 | console.error(dataStr); 102 | } 103 | else { 104 | console.log(dataStr); 105 | } 106 | } 107 | 108 | // Lambda is new 109 | const lambdaGUID = uuidv4(); 110 | logData(logType.INFO, 'Loading function', '', '', 0, lambdaGUID); 111 | 112 | // Entry point 113 | exports.handler = async (event, context) => { 114 | logData(logType.INFO, 'Received event', '', '', 0, event); 115 | 116 | context.ffmpegData = ffmpegData; 117 | context.fontData = fontData; 118 | 119 | // Prepare ffmpeg if necessary 120 | prepareFfmpeg(context); 121 | testFfmpeg(context); 122 | 123 | // Update DDB configs 124 | const dbbConfigData = parseDDBConfig(process.env, dbbConfigDataDefault); 125 | const dbbChunksData = parseDDBChunks(process.env, dbbChunksDataDefault); 126 | 127 | // Fetch config and return it 128 | const transcoderConfig = new LiveTranscoderConfig() 129 | await transcoderConfig.loadFromDDB(dbbConfigData.region, dbbConfigData.tableName, dbbConfigData.configName); 130 | logData(logType.INFO, 'Fetched config', '', '', 0, transcoderConfig.toString()); 131 | 132 | const ret = []; 133 | const numRecords = event.Records.length; 134 | if (numRecords <= 0) { 135 | logData(logType.WARN, 'No records to process' , '', '' , 0); 136 | } 137 | else { 138 | for (let r = 0; r < numRecords; r++) { 139 | // Process one after the other 140 | logData(logType.INFO, 'Processing record', '', '', 0, `${r}/${numRecords}`); 141 | retRecord = await processRecord(event.Records[r], dbbChunksData, transcoderConfig, context) 142 | ret.push(retRecord); 143 | } 144 | } 145 | 146 | event.returnedResult = ret; 147 | 148 | return event; 149 | } 150 | 151 | async function processRecord(record, dbbChunksData, transcoderConfig, context) { 152 | return new Promise( (resolutionFunc, rejectionFunc) => { 153 | const timers = { 154 | 'start': 0, 155 | 'downloadFromS3': 0, 156 | 'getMetadataS3': 0, 157 | 'localTranscode': 0, 158 | 'uploadedToS3': 0, 159 | 'updatedDDB': 0, 160 | 'final': 0 161 | }; 162 | timers.start = getTimeInMilliseconds(); 163 | 164 | const bucket = getBucket(record); 165 | const objectKey = getObjectKey(record); 166 | const streamID = getStreamIDFromObjectKey(objectKey); 167 | const localTmpFilePathInput = tempy.file(); 168 | 169 | logData(logType.INFO, 'Downloading from s3', streamID, objectKey, 0, {s3: `s3://${bucket}/${objectKey}`, dst: localTmpFilePathInput}); 170 | 171 | // Object to store transcoding output data 172 | const abrData = new ABRData(bucket, objectKey, localTmpFilePathInput); 173 | 174 | // Download from S3 175 | downloadS3Object(bucket, objectKey, localTmpFilePathInput) 176 | .then(res => { 177 | timers.downloadFromS3 = getTimeInMilliseconds(); 178 | logData(logType.INFO, 'Downloaded from s3', streamID, objectKey, timers.downloadFromS3 - timers.start, {s3: `s3://${bucket}/${objectKey}`, dst: localTmpFilePathInput}); 179 | 180 | // Get S3 obj metadata 181 | return getS3ObjectMetadata(bucket, objectKey); 182 | }) 183 | .then(s3ObjMetadata => { 184 | abrData.srcS3Metadata = s3ObjMetadata; 185 | 186 | timers.getMetadataS3 = getTimeInMilliseconds(); 187 | logData(logType.INFO, 'Got metadata from s3', streamID, objectKey, timers.getMetadataS3 - timers.downloadFromS3, {s3: `s3://${bucket}/${objectKey}`, dst: localTmpFilePathInput}); 188 | 189 | // Decide destination bucket (if not configured use source bucket) 190 | let dstS3Bucket = transcoderConfig.getParamDefault('dstS3Bucket', bucket); 191 | 192 | // Create transcoding settings 193 | const transcodeData = createTranscodeData(abrData.srcLocalFilePath, transcoderConfig, context, abrData.srcS3Metadata); 194 | abrData.ffmpegArgs = transcodeData.ffmpegArgs; 195 | transcodeData.dstFilesData.forEach(dstFileData => { 196 | abrData.addRenditionData(dstFileData.dstLocalFilePath, dstS3Bucket, abrData.srcS3ObjectKey, transcoderConfig.getParam('s3OutputPrefix'), dstFileData.rendition); 197 | }); 198 | 199 | // Transcode locally 200 | return createChunkABR(abrData.ffmpegArgs, context); 201 | }) 202 | .then(res => { 203 | timers.localTranscode = getTimeInMilliseconds(); 204 | 205 | const transcodedLocalFiles = abrData.renditionsData.map(rendition => {return rendition.localFilePath;}); 206 | logData(logType.INFO, 'Locally transcoded', streamID, objectKey, timers.localTranscode - timers.downloadFromS3, {src: abrData.srcLocalFilePath, dst: transcodedLocalFiles}); 207 | 208 | // Upload ABR to S3 209 | let uploadMetadata = {}; 210 | if (transcoderConfig.getParam('copyOriginalMetadataToABRChunks')) { 211 | uploadMetadata = abrData.srcS3Metadata; 212 | } 213 | return uploadS3Objects(bucket, abrData, uploadMetadata, transcoderConfig.getParam('publicReadToABRChunks'), transcoderConfig.getParam('copyOriginalContentTypeToABRChunks')); 214 | }) 215 | .then(res => { 216 | timers.uploadedToS3 = getTimeInMilliseconds(); 217 | 218 | const transcodedLocalFiles = abrData.renditionsData.map(rendition => {return rendition.localFilePath;}); 219 | const uploadedKeys = abrData.renditionsData.map(rendition => {return rendition.dstS3ObjectKey;}); 220 | logData(logType.INFO, 'Uploaded to S3', streamID, objectKey, timers.uploadedToS3 - timers.localTranscode, {src: transcodedLocalFiles, dst: uploadedKeys}); 221 | 222 | return ddbUpdateChunks(dbbChunksData, abrData); 223 | }) 224 | .then(res => { 225 | timers.updatedDDB = getTimeInMilliseconds(); 226 | logData(logType.INFO, 'Updated DDB', streamID, objectKey, timers.updatedDDB - timers.uploadedToS3); 227 | 228 | // Clean up 229 | fileCleanupSync(abrData); 230 | 231 | timers.final = getTimeInMilliseconds(); 232 | logData(logType.INFO, 'SUCCEEDED', streamID, objectKey, timers.final - timers.start); 233 | return resolutionFunc(abrData); 234 | }) 235 | .catch(err => { 236 | fileCleanupSync(abrData); 237 | 238 | timers.final = getTimeInMilliseconds(); 239 | logData(logType.ERR, 'ERROR', streamID, objectKey, timers.final - timers.start); 240 | return rejectionFunc(err); 241 | }) 242 | }); 243 | } 244 | 245 | async function createChunkABR(ffmpegArgs, context) { 246 | return new Promise( (resolutionFunc, rejectionFunc) => { 247 | try { 248 | execInternalSync(context.ffmpegData.path, ffmpegArgs); 249 | 250 | return resolutionFunc(true); 251 | } 252 | catch(e) { 253 | return rejectionFunc(e); 254 | } 255 | }); 256 | } 257 | 258 | function createDstS3ObjectKey(srcS3ObjectKey, s3ABRPath, renditionID) { 259 | const srcObjPath = path.dirname(srcS3ObjectKey); 260 | const srcObjFile = path.basename(srcS3ObjectKey); 261 | 262 | // From: 263 | // input/1234/A/a.ts 264 | // To: 265 | // output/1234/A/a.ts 266 | 267 | // Remove initial directory 268 | const dirs = srcObjPath.split('/'); 269 | if (dirs.length >= 1) { 270 | delete dirs[0]; 271 | } 272 | return path.join(s3ABRPath, dirs.join('/'), renditionID, srcObjFile); 273 | } 274 | 275 | // Creates transcode command args 276 | function createTranscodeData(srcLocalFilePath, transcoderConfig, context, srcS3Metadata) { 277 | const ffmpegArgs = []; 278 | const dstFilesData = []; 279 | 280 | // Base options (sync) 281 | ffmpegInitSyncArgs = ['-hide_banner', '-y', '-i', srcLocalFilePath, '-vsync', '0', '-copyts']; 282 | 283 | // Add pix_fmt for processing 284 | ffmpegInitSyncArgs.push('-pix_fmt', transcoderConfig.getParam('video_pix_fmt')); 285 | 286 | ffmpegArgs.push(...ffmpegInitSyncArgs); 287 | 288 | ffmpegRenditionArgs = []; 289 | for (let n = 0; n < transcoderConfig.getParam('renditions').length; n++) { 290 | const rendition = transcoderConfig.getParam('renditions')[n]; 291 | 292 | // Overlay options 293 | ffmpegOverlayArgs = []; 294 | if (transcoderConfig.getParam('overlayEncodingData')) { 295 | const fontPath = getFontPath(context); 296 | let overlayString = `Lane ${rendition.width}x${rendition.height}@${rendition.video_h264_preset}-${rendition.video_h264_profile}-${rendition.video_crf}-${Math.floor(rendition.video_maxrate/1024)}Kbps`; 297 | let ffmpegOverlayArgStr = 'drawtext=fontfile=' + fontPath + ':text=\'' + overlayString + '\':x=20:y=20:fontsize=60:fontcolor=pink:box=1:boxcolor=0x00000099' 298 | 299 | if (typeof(srcS3Metadata === 'object') && typeof(srcS3Metadata.Metadata === 'object')) { 300 | const seqNum = extractFromMetadataHeader(srcS3Metadata.Metadata, s3MetadataHeaders.SEQ_NUMBER); 301 | const wallClockNs = extractFromMetadataHeader(srcS3Metadata.Metadata, s3MetadataHeaders.WALL_CLOCK_NS); 302 | const durationMs = extractFromMetadataHeader(srcS3Metadata.Metadata, s3MetadataHeaders.DURATION_MS); 303 | 304 | const overlayStringChunkData = `nSeq ${seqNum}-Dur ${(durationMs / 1000).toFixed(3)}-Ingested at ${new Date(wallClockNs/1000000).toUTCString()}`; 305 | ffmpegOverlayArgStr = ffmpegOverlayArgStr + ',' + 'drawtext=fontfile=' + fontPath + ':text=\'' + overlayStringChunkData.replace(/:/g, '') + '\':x=20:y=85:fontsize=60:fontcolor=pink:box=1:boxcolor=0x00000099' 306 | } 307 | ffmpegOverlayArgs = ['-vf', ffmpegOverlayArgStr]; 308 | } 309 | 310 | // Video encoding & scale 311 | ffmpegVideoEncArgs = ['-s', `${rendition.width}x${rendition.height}`, '-c:v', 'libx264', '-preset', rendition.video_h264_preset, '-profile:v', rendition.video_h264_profile, '-crf', rendition.video_crf, '-maxrate', rendition.video_maxrate, '-bufsize', rendition.video_buffersize, '-b-pyramid', rendition.video_h264_bpyramid]; 312 | 313 | //x264-params 314 | ffmpegx264ParamsArgs = []; 315 | if (typeof(rendition.video_x264_params) === 'string') { 316 | ffmpegx264ParamsArgs.push('-x264-params', rendition.video_x264_params) 317 | } 318 | 319 | // Audio encoding 320 | // TODO: 321 | // The audio is transmuxed due to a problem in ffmpeg re-encoding 322 | // If we transcode the audio it creates small timestamp misalignment 323 | // between original and transcoded version 324 | // Also it is a workaround for audio primming 325 | ffmpegAudioEncArgs = ['-c:a', 'copy']; 326 | 327 | // Muxer 328 | ffmpegMuxArgs = ['-f', 'mpegts', '-mpegts_copyts', '1'] 329 | 330 | // Output 331 | // input A/B/file.ts 332 | // output A/B/file.ts-480p 333 | const dstLocalFilePath = srcLocalFilePath + '-' + rendition.ID; 334 | ffmpegOutputArgs = [dstLocalFilePath]; 335 | dstFilesData.push({dstLocalFilePath: dstLocalFilePath, rendition: rendition}); 336 | 337 | // Adds all args 338 | ffmpegArgs.push(...ffmpegOverlayArgs); 339 | ffmpegArgs.push(...ffmpegVideoEncArgs); 340 | ffmpegArgs.push(...ffmpegx264ParamsArgs); 341 | ffmpegArgs.push(...ffmpegAudioEncArgs); 342 | ffmpegArgs.push(...ffmpegMuxArgs); 343 | ffmpegArgs.push(...ffmpegOutputArgs); 344 | } 345 | 346 | return {ffmpegArgs: ffmpegArgs, dstFilesData: dstFilesData}; 347 | } 348 | 349 | function getFontPath(context) { 350 | return context.fontData.path; 351 | } 352 | 353 | function fileCleanupSync(abrData) { 354 | if (fs.existsSync(abrData.srcLocalFilePath)) { 355 | fs.unlinkSync(abrData.srcLocalFilePath); 356 | } 357 | for (var i = 0; i < abrData.renditionsData.length; i++) { 358 | const rendition = abrData.renditionsData[i]; 359 | if (fs.existsSync(rendition.localFilePath)) { 360 | fs.unlinkSync(rendition.localFilePath); 361 | } 362 | } 363 | } 364 | 365 | async function uploadS3Objects(bucket, abrData, metadata, publicRead, copyContentType) { 366 | const promisesS3Uploads = []; 367 | for (let n = 0; n < abrData.renditionsData.length; n++) { 368 | const srcFilePath = abrData.renditionsData[n].localFilePath; 369 | const objKey = abrData.renditionsData[n].dstS3ObjectKey; 370 | 371 | const p = uploadS3Object(bucket, objKey, srcFilePath, metadata, publicRead, copyContentType); 372 | promisesS3Uploads.push(p); 373 | } 374 | return Promise.all(promisesS3Uploads); 375 | } 376 | 377 | // S3 functions 378 | 379 | async function uploadS3Object(bucket, objectKey, localFilePath, metadata, publicRead, copyContentType) { 380 | // Setting up S3 upload parameters 381 | const params = { 382 | Bucket: bucket, 383 | Key: objectKey, 384 | Body: fs.readFileSync(localFilePath) 385 | }; 386 | if (publicRead) { 387 | params.ACL = 'public-read'; 388 | } 389 | if (Object.entries(metadata.Metadata).length > 0) { 390 | params.Metadata = metadata.Metadata; 391 | } 392 | if (copyContentType) { 393 | params.ContentType = metadata.ContentType; 394 | } 395 | // Uploading files to the bucket 396 | return s3.upload(params).promise(); 397 | } 398 | 399 | async function getS3ObjectMetadata(bucket, objectKey) { 400 | return await s3.headObject({Bucket: bucket, Key: objectKey}).promise(); 401 | } 402 | 403 | async function downloadS3Object(bucket, objectKey, localPathFile) { 404 | return new Promise( (resolutionFunc,rejectionFunc) => { 405 | try { 406 | const fileStream = fs.createWriteStream(localPathFile); 407 | const s3Stream = s3.getObject({ 408 | Bucket: bucket, 409 | Key: objectKey} 410 | ).createReadStream(); 411 | 412 | // Listen for errors returned by the service 413 | s3Stream.on('error', function(err) { 414 | throw err; 415 | }); 416 | s3Stream.pipe(fileStream).on('error', function(err) { 417 | throw err; 418 | }).on('close', function() { 419 | return resolutionFunc(localPathFile); 420 | }); 421 | } catch (e) { 422 | return rejectionFunc(err); 423 | } 424 | }); 425 | } 426 | 427 | // Helper functions 428 | 429 | function parseDDBConfig(envVars, defaultDBBConfig) { 430 | ret = defaultDBBConfig; 431 | if ((typeof(envVars.AWS_REGION) === 'string') && (envVars.AWS_REGION != "")) { 432 | ret.region = envVars.AWS_REGION; 433 | } 434 | if ((typeof(envVars.DDB_CONFIG_TABLE_NAME) === 'string') && (envVars.DDB_CONFIG_TABLE_NAME != "")) { 435 | ret.tableName = envVars.DDB_CONFIG_TABLE_NAME; 436 | } 437 | 438 | console.log(`Dynamo table config data: ${JSON.stringify(ret)}`); 439 | 440 | return ret; 441 | } 442 | 443 | function parseDDBChunks(envVars, defaultDBBChunks) { 444 | ret = defaultDBBChunks; 445 | if ((typeof(envVars.AWS_REGION) === 'string') && (envVars.AWS_REGION != "")) { 446 | ret.region = envVars.AWS_REGION; 447 | } 448 | if ((typeof(envVars.DDB_CONFIG_TABLE_CHUNKS) === 'string') && (envVars.DDB_CONFIG_TABLE_CHUNKS != "")) { 449 | ret.tableName = envVars.DDB_CONFIG_TABLE_CHUNKS; 450 | } 451 | 452 | console.log(`Dynamo table chunks data: ${JSON.stringify(ret)}`); 453 | 454 | return ret; 455 | } 456 | 457 | function extractFromMetadataHeader(srcMetadata, name) { 458 | if (!(name in srcMetadata)) { 459 | throw new Error(`Error extracting ${name} from metadata: ${JSON.stringify(srcMetadata)}`); 460 | } 461 | return srcMetadata[name]; 462 | } 463 | 464 | function getPlaybackPathFromObjectKey(s3ObjKey) { 465 | // We assume is the 1nd directory 466 | // Ingest 467 | // input/streamID/chunk.ts 468 | // Output 469 | // output/streamID/chunk.ts 470 | // Playback 471 | // https://CDN-preprend/streamID/chunk.ts (FilePath = streamID/chunk.ts) 472 | const dirItems = s3ObjKey.split('/'); 473 | if (dirItems.length < 1) { 474 | throw new Error (`Could not extract playback path from ${s3ObjKey}`); 475 | } 476 | dirItems.shift(); 477 | return dirItems.join("/"); 478 | } 479 | 480 | function getStreamIDFromObjectKey(s3ObjKey) { 481 | // We assume is the 2nd directory 482 | // Ingest 483 | // input/streamID/chunk.ts\ 484 | const dirItems = s3ObjKey.split('/'); 485 | if (dirItems.length < 2) { 486 | throw new Error (`Could not extract streamID from ${s3ObjKey}`); 487 | } 488 | return dirItems[1]; 489 | } 490 | 491 | function getTimeInMilliseconds() { 492 | const hrTime = process.hrtime() 493 | return hrTime[0] * 1000 + hrTime[1] / 1000000; 494 | } 495 | 496 | function isLocalDebug(context) { 497 | if (('isLocalDebug' in context) && (context.isLocalDebug)) { 498 | return true; 499 | } 500 | return false; 501 | } 502 | 503 | function getBucket(record) { 504 | return record.s3.bucket.name; 505 | } 506 | 507 | function getObjectKey(record) { 508 | return decodeURIComponent(record.s3.object.key.replace(/\+/g, ' ')); 509 | } 510 | 511 | function execInternalSync(cmd, args, verbose_level) { 512 | var verbose_level = typeof (verbose_level) !== 'undefined' ? verbose_level : 1; 513 | 514 | // Keeping low level logs not structured 515 | if (verbose_level >= 1) { 516 | console.log(`${cmd} ${args.join(" ")}`); 517 | } 518 | 519 | const process = child_process.spawnSync(cmd, args); 520 | if (process == null) 521 | throw new Error("process null"); 522 | 523 | if (verbose_level >= 1) { 524 | console.log("StdOut: " + getOutputFromProcess(CMD_OUT_STDOUT, process)); 525 | console.log("StdErr: " + getOutputFromProcess(CMD_OUT_STDERR, process)); 526 | } 527 | if (process.status != 0) { 528 | throw new Error(getOutputFromProcess(CMD_OUT_STDERR, process), process.status); 529 | } 530 | return process.status; 531 | } 532 | 533 | function getOutputFromProcess(type, process) { 534 | let ret = ''; 535 | if (process != null) { 536 | if ((type in process) && (process[type] != null) && (process[type].toString() != "")) { 537 | ret = process[type].toString(); 538 | } 539 | } 540 | return ret; 541 | } 542 | 543 | // Lambda ffmpeg helpers 544 | 545 | function testFfmpeg(context) { 546 | if (context.testFfmpeg) { 547 | execInternalSync(context.ffmpegData.path, ['-h']); 548 | } 549 | } 550 | 551 | function prepareFfmpeg(context) { 552 | if (!isLocalDebug(context)) { 553 | // Copy ffmpeg if does NOT exists in dst 554 | if (fs.existsSync(context.ffmpegData.LAMBDA_DST) == false) { 555 | execInternalSync('cp', [context.ffmpegData.LAMBDA_SRC, context.ffmpegData.LAMBDA_DST]); 556 | execInternalSync('chmod', ['+x', context.ffmpegData.LAMBDA_DST]); 557 | 558 | } 559 | context.ffmpegData.path = context.ffmpegData.LAMBDA_DST; 560 | 561 | if (fs.existsSync(context.fontData.LAMBDA_DST) == false) { 562 | execInternalSync('cp', [context.fontData.LAMBDA_SRC, context.fontData.LAMBDA_DST]); 563 | } 564 | context.fontData.path = context.fontData.LAMBDA_DST; 565 | } 566 | else { 567 | context.ffmpegData.path = context.ffmpegData.LOCAL; 568 | context.fontData.path = context.fontData.LOCAL; 569 | } 570 | } 571 | 572 | // Chunks helper 573 | async function ddbUpdateChunks(dbbChunksData, abrData) { 574 | const chunkData = new LiveTranscoderChunkData(); 575 | 576 | chunkData.setDDB(dbbChunksData.region, dbbChunksData.tableName); 577 | 578 | dbbUpdatePromises = []; 579 | const srcMetadata = abrData.srcS3Metadata.Metadata; 580 | const seqNum = extractFromMetadataHeader(srcMetadata, s3MetadataHeaders.SEQ_NUMBER); 581 | const wallClockNs = extractFromMetadataHeader(srcMetadata, s3MetadataHeaders.WALL_CLOCK_NS); 582 | const durationMs = extractFromMetadataHeader(srcMetadata, s3MetadataHeaders.DURATION_MS); 583 | const targetDurationMs = extractFromMetadataHeader(srcMetadata, s3MetadataHeaders.TARGET_DURATION_MS); 584 | 585 | for (let n = 0; n < abrData.renditionsData.length; n++) { 586 | const renditionData = abrData.renditionsData[n]; 587 | const chunk = new ChunkData( 588 | renditionData.dstS3Bucket, 589 | renditionData.dstS3ObjectKey, 590 | getPlaybackPathFromObjectKey(renditionData.dstS3ObjectKey), 591 | getStreamIDFromObjectKey(renditionData.dstS3ObjectKey), 592 | seqNum, 593 | renditionData.rendition.ID, 594 | wallClockNs, 595 | targetDurationMs, 596 | durationMs); 597 | 598 | const p = chunkData.saveChunk(chunk); 599 | dbbUpdatePromises.push(p); 600 | } 601 | return Promise.all(dbbUpdatePromises); 602 | } -------------------------------------------------------------------------------- /joc-lambda-chunk-transcoder/live-transcoder-chunk-data.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Jordi Cenzano 2020/12/06 3 | */ 4 | 5 | const aws = require('aws-sdk'); 6 | const { v4: uuidv4 } = require('uuid'); 7 | 8 | class ChunkData { 9 | constructor(s3Bucket, s3ObjKey, filePath, streamId, seqNumber, renditionId, wallClockEpochNs, targetDurationMs, durationMs) { 10 | this._uid = uuidv4(); 11 | this._s3Bucket = s3Bucket; 12 | this._s3ObjKey = s3ObjKey; 13 | this._filePath = filePath; 14 | this._streamId = streamId; 15 | this._seqNumber = seqNumber; 16 | this._renditionId = renditionId; 17 | this._wallClockEpochNs = wallClockEpochNs; 18 | this._targetDurationMs = targetDurationMs; 19 | this._durationMs = durationMs; 20 | } 21 | 22 | get uid() { return this._uid; } 23 | get s3Bucket() { return this._s3Bucket; } 24 | get s3ObjKey() { return this._s3ObjKey; } 25 | get filePath() { return this._filePath; } 26 | get streamId() { return this._streamId; } 27 | get seqNumber() { return this._seqNumber; } 28 | get renditionId() { return this._renditionId; } 29 | get wallClockEpochNs() { return this._wallClockEpochNs; } 30 | get targetDurationMs() { return this._targetDurationMs; } 31 | get durationMs() { return this._durationMs; } 32 | } 33 | 34 | class LiveTranscoderChunkData { 35 | constructor() { 36 | this.DDB_MAX_RETRIES_DEF = 3; 37 | 38 | this.ddb = null; 39 | this.tableName = ''; 40 | this.region = ''; 41 | } 42 | 43 | setDDB(region, tableName) { 44 | this.region = region; 45 | this.tableName = tableName; 46 | } 47 | 48 | async saveChunk(chunkData) { 49 | // Create DDB object 50 | if (this.ddb === null) { 51 | this.ddb = new aws.DynamoDB({region: this.region, maxRetries: this.DDB_MAX_RETRIES_DEF}); 52 | } 53 | const params = { 54 | TableName: this.tableName, 55 | Item: { 56 | 'uid' : {S: chunkData.uid}, 57 | 'stream-id' : {S: chunkData.streamId}, 58 | 's3bucket': {S: chunkData.s3Bucket}, 59 | 's3objkey': {S: chunkData.s3ObjKey}, 60 | 'file-path': {S: chunkData.filePath}, 61 | 'seq-number': {N: chunkData.seqNumber.toString()}, 62 | 'rendition-id': {S: chunkData.renditionId}, 63 | 'wallclock-epoch-ns': {N: chunkData.wallClockEpochNs.toString()}, 64 | 'first-video-ts': {N: '-1'}, 65 | 'first-audio-ts': {N: '-1'}, 66 | 'target-duration-ms': {N: chunkData.targetDurationMs.toString()}, 67 | 'duration-ms': {N: chunkData.durationMs.toString()} 68 | } 69 | }; 70 | // Call DynamoDB to add the item to the table 71 | return await this.ddb.putItem(params).promise(); 72 | } 73 | } 74 | 75 | module.exports = {LiveTranscoderChunkData, ChunkData}; -------------------------------------------------------------------------------- /joc-lambda-chunk-transcoder/live-transcoder-config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Jordi Cenzano 2020/12/06 3 | */ 4 | 5 | const aws = require('aws-sdk'); 6 | 7 | // Example config object 8 | /* 9 | { 10 | "config-name": "default", 11 | "desc": "1080p (Premium 6 renditions)", 12 | "value": { 13 | "copyOriginalContentTypeToABRChunks": true, 14 | "copyOriginalMetadataToABRChunks": true, 15 | "mediaCdnPrefix": "https://XXXXXXXXXXXXXX.cloudfront.net", 16 | "overlayEncodingData": true, 17 | "overlayMessage": "Test-", 18 | "publicReadToABRChunks": false, 19 | "renditions": [ 20 | { 21 | "height": 1080, 22 | "ID": "1080p", 23 | "video_buffersize": 7000000, 24 | "video_crf": 23, 25 | "video_h264_bpyramid": "strict", 26 | "video_h264_preset": "slow", 27 | "video_h264_profile": "high", 28 | "video_maxrate": 3500000, 29 | "width": 1920 30 | }, 31 | { 32 | "height": 144, 33 | "ID": "144p", 34 | "video_buffersize": 200000, 35 | "video_crf": 23, 36 | "video_h264_bpyramid": "strict", 37 | "video_h264_preset": "slow", 38 | "video_h264_profile": "high", 39 | "video_maxrate": 100000, 40 | "video_pix_fmt": "yuv420p", 41 | "width": 256 42 | } 43 | ], 44 | "s3OutputPrefix": "output/", 45 | "video_pix_fmt": "yuv420p" 46 | } 47 | } 48 | */ 49 | 50 | class LiveTranscoderConfig { 51 | constructor() { 52 | this.DDB_MAX_RETRIES_DEF = 3; 53 | 54 | this.loaded = false; 55 | this.config = {}; 56 | this.ddb = null; 57 | } 58 | 59 | async loadFromDDB(region, tableName, configName) { 60 | // Create DDB object 61 | if (this.ddb === null) { 62 | this.ddb = new aws.DynamoDB({region: region, maxRetries: this.DDB_MAX_RETRIES_DEF}); 63 | } 64 | 65 | // Read Item 66 | const params = { 67 | Key: {"config-name": {S: configName}}, 68 | TableName: tableName 69 | }; 70 | const dbbData = await this.ddb.getItem(params).promise(); 71 | this.config = aws.DynamoDB.Converter.unmarshall(dbbData.Item).value; 72 | this.loaded = true; 73 | 74 | return this.loaded; 75 | } 76 | 77 | // Get data 78 | getParam(name) { 79 | return this.checkIntegrityAndReturn(name); 80 | } 81 | getParamDefault(name, defaultValue) { 82 | try { 83 | return this.checkIntegrityAndReturn(name); 84 | } 85 | catch(e) { 86 | return defaultValue; 87 | } 88 | } 89 | 90 | toString() { 91 | return JSON.stringify(this.config); 92 | } 93 | 94 | checkIntegrityAndReturn(name) { 95 | if (!this.loaded) { 96 | throw new Error (`Tried to access to a non loaded transcoding config`); 97 | } 98 | if (!(name in this.config)) { 99 | throw new Error (`Property ${name} not found in transcoding config`); 100 | } 101 | return this.config[name]; 102 | } 103 | } 104 | 105 | module.exports = LiveTranscoderConfig; -------------------------------------------------------------------------------- /joc-lambda-chunk-transcoder/local-test.js: -------------------------------------------------------------------------------- 1 | const underTest = require('./index.js'); 2 | 3 | const testEvent = { 4 | Records: [{ 5 | "eventVersion": "2.0", 6 | "eventSource": "aws:s3", 7 | "awsRegion": "us-east-1", 8 | "eventTime": "1970-01-01T00:00:00.000Z", 9 | "eventName": "ObjectCreated:Put", 10 | "userIdentity": { 11 | "principalId": "EXAMPLE" 12 | }, 13 | "requestParameters": { 14 | "sourceIPAddress": "127.0.0.1" 15 | }, 16 | "responseElements": { 17 | "x-amz-request-id": "EXAMPLE123456789", 18 | "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" 19 | }, 20 | "s3": { 21 | "s3SchemaVersion": "1.0", 22 | "configurationId": "testConfigRule", 23 | "bucket": { 24 | "name": "live-dist-test", 25 | "ownerIdentity": { 26 | "principalId": "EXAMPLE" 27 | }, 28 | "arn": "arn:aws:s3:::live-dist-test" 29 | }, 30 | "object": { 31 | "key": "test/streamID/source_00000.ts", 32 | "size": 330000, 33 | "eTag": "0123456789abcdef0123456789abcdef", 34 | "sequencer": "0A1B2C3D4E5F678901" 35 | } 36 | } 37 | }] 38 | }; 39 | 40 | const context = { 41 | isLocalDebug: true, 42 | testFfmpeg: false 43 | }; 44 | 45 | async function main() { 46 | console.log('[LOCAL] Start') 47 | const ret = await underTest.handler(testEvent, context); 48 | console.log('[LOCAL] end. Ret: ' + JSON.stringify(ret)); 49 | } 50 | 51 | main(); 52 | 53 | -------------------------------------------------------------------------------- /joc-lambda-chunk-transcoder/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "joc-lambda-chunk-transcoder", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "@nodelib/fs.scandir": { 8 | "version": "2.1.3", 9 | "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.3.tgz", 10 | "integrity": "sha512-eGmwYQn3gxo4r7jdQnkrrN6bY478C3P+a/y72IJukF8LjB6ZHeB3c+Ehacj3sYeSmUXGlnA67/PmbM9CVwL7Dw==", 11 | "requires": { 12 | "@nodelib/fs.stat": "2.0.3", 13 | "run-parallel": "^1.1.9" 14 | } 15 | }, 16 | "@nodelib/fs.stat": { 17 | "version": "2.0.3", 18 | "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.3.tgz", 19 | "integrity": "sha512-bQBFruR2TAwoevBEd/NWMoAAtNGzTRgdrqnYCc7dhzfoNvqPzLyqlEQnzZ3kVnNrSp25iyxE00/3h2fqGAGArA==" 20 | }, 21 | "@nodelib/fs.walk": { 22 | "version": "1.2.4", 23 | "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.4.tgz", 24 | "integrity": "sha512-1V9XOY4rDW0rehzbrcqAmHnz8e7SKvX27gh8Gt2WgB0+pdzdiLV83p72kZPU+jvMbS1qU5mauP2iOvO8rhmurQ==", 25 | "requires": { 26 | "@nodelib/fs.scandir": "2.1.3", 27 | "fastq": "^1.6.0" 28 | } 29 | }, 30 | "aggregate-error": { 31 | "version": "3.1.0", 32 | "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", 33 | "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", 34 | "requires": { 35 | "clean-stack": "^2.0.0", 36 | "indent-string": "^4.0.0" 37 | } 38 | }, 39 | "array-union": { 40 | "version": "2.1.0", 41 | "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", 42 | "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==" 43 | }, 44 | "aws-sdk": { 45 | "version": "2.809.0", 46 | "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.809.0.tgz", 47 | "integrity": "sha512-wPmb3DbS2+jXzj3aBV9nbRY/rsTqceriXZBsLM9VOGknkULfcnM0vCpm9psgAR87DvevO+NhPoc2kNAEdFkvzg==", 48 | "requires": { 49 | "buffer": "4.9.2", 50 | "events": "1.1.1", 51 | "ieee754": "1.1.13", 52 | "jmespath": "0.15.0", 53 | "querystring": "0.2.0", 54 | "sax": "1.2.1", 55 | "url": "0.10.3", 56 | "uuid": "3.3.2", 57 | "xml2js": "0.4.19" 58 | }, 59 | "dependencies": { 60 | "uuid": { 61 | "version": "3.3.2", 62 | "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", 63 | "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==" 64 | } 65 | } 66 | }, 67 | "balanced-match": { 68 | "version": "1.0.0", 69 | "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", 70 | "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" 71 | }, 72 | "base64-js": { 73 | "version": "1.5.1", 74 | "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", 75 | "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==" 76 | }, 77 | "brace-expansion": { 78 | "version": "1.1.11", 79 | "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", 80 | "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", 81 | "requires": { 82 | "balanced-match": "^1.0.0", 83 | "concat-map": "0.0.1" 84 | } 85 | }, 86 | "braces": { 87 | "version": "3.0.2", 88 | "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", 89 | "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", 90 | "requires": { 91 | "fill-range": "^7.0.1" 92 | } 93 | }, 94 | "buffer": { 95 | "version": "4.9.2", 96 | "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.2.tgz", 97 | "integrity": "sha512-xq+q3SRMOxGivLhBNaUdC64hDTQwejJ+H0T/NB1XMtTVEwNTrfFF3gAxiyW0Bu/xWEGhjVKgUcMhCrUy2+uCWg==", 98 | "requires": { 99 | "base64-js": "^1.0.2", 100 | "ieee754": "^1.1.4", 101 | "isarray": "^1.0.0" 102 | } 103 | }, 104 | "clean-stack": { 105 | "version": "2.2.0", 106 | "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", 107 | "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==" 108 | }, 109 | "concat-map": { 110 | "version": "0.0.1", 111 | "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", 112 | "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" 113 | }, 114 | "crypto-random-string": { 115 | "version": "2.0.0", 116 | "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-2.0.0.tgz", 117 | "integrity": "sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA==" 118 | }, 119 | "del": { 120 | "version": "6.0.0", 121 | "resolved": "https://registry.npmjs.org/del/-/del-6.0.0.tgz", 122 | "integrity": "sha512-1shh9DQ23L16oXSZKB2JxpL7iMy2E0S9d517ptA1P8iw0alkPtQcrKH7ru31rYtKwF499HkTu+DRzq3TCKDFRQ==", 123 | "requires": { 124 | "globby": "^11.0.1", 125 | "graceful-fs": "^4.2.4", 126 | "is-glob": "^4.0.1", 127 | "is-path-cwd": "^2.2.0", 128 | "is-path-inside": "^3.0.2", 129 | "p-map": "^4.0.0", 130 | "rimraf": "^3.0.2", 131 | "slash": "^3.0.0" 132 | } 133 | }, 134 | "dir-glob": { 135 | "version": "3.0.1", 136 | "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", 137 | "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", 138 | "requires": { 139 | "path-type": "^4.0.0" 140 | } 141 | }, 142 | "events": { 143 | "version": "1.1.1", 144 | "resolved": "https://registry.npmjs.org/events/-/events-1.1.1.tgz", 145 | "integrity": "sha1-nr23Y1rQmccNzEwqH1AEKI6L2SQ=" 146 | }, 147 | "fast-glob": { 148 | "version": "3.2.4", 149 | "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.4.tgz", 150 | "integrity": "sha512-kr/Oo6PX51265qeuCYsyGypiO5uJFgBS0jksyG7FUeCyQzNwYnzrNIMR1NXfkZXsMYXYLRAHgISHBz8gQcxKHQ==", 151 | "requires": { 152 | "@nodelib/fs.stat": "^2.0.2", 153 | "@nodelib/fs.walk": "^1.2.3", 154 | "glob-parent": "^5.1.0", 155 | "merge2": "^1.3.0", 156 | "micromatch": "^4.0.2", 157 | "picomatch": "^2.2.1" 158 | } 159 | }, 160 | "fastq": { 161 | "version": "1.9.0", 162 | "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.9.0.tgz", 163 | "integrity": "sha512-i7FVWL8HhVY+CTkwFxkN2mk3h+787ixS5S63eb78diVRc1MCssarHq3W5cj0av7YDSwmaV928RNag+U1etRQ7w==", 164 | "requires": { 165 | "reusify": "^1.0.4" 166 | } 167 | }, 168 | "fill-range": { 169 | "version": "7.0.1", 170 | "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", 171 | "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", 172 | "requires": { 173 | "to-regex-range": "^5.0.1" 174 | } 175 | }, 176 | "fs.realpath": { 177 | "version": "1.0.0", 178 | "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", 179 | "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" 180 | }, 181 | "glob": { 182 | "version": "7.1.6", 183 | "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", 184 | "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", 185 | "requires": { 186 | "fs.realpath": "^1.0.0", 187 | "inflight": "^1.0.4", 188 | "inherits": "2", 189 | "minimatch": "^3.0.4", 190 | "once": "^1.3.0", 191 | "path-is-absolute": "^1.0.0" 192 | } 193 | }, 194 | "glob-parent": { 195 | "version": "5.1.1", 196 | "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.1.tgz", 197 | "integrity": "sha512-FnI+VGOpnlGHWZxthPGR+QhR78fuiK0sNLkHQv+bL9fQi57lNNdquIbna/WrfROrolq8GK5Ek6BiMwqL/voRYQ==", 198 | "requires": { 199 | "is-glob": "^4.0.1" 200 | } 201 | }, 202 | "globby": { 203 | "version": "11.0.1", 204 | "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.1.tgz", 205 | "integrity": "sha512-iH9RmgwCmUJHi2z5o2l3eTtGBtXek1OYlHrbcxOYugyHLmAsZrPj43OtHThd62Buh/Vv6VyCBD2bdyWcGNQqoQ==", 206 | "requires": { 207 | "array-union": "^2.1.0", 208 | "dir-glob": "^3.0.1", 209 | "fast-glob": "^3.1.1", 210 | "ignore": "^5.1.4", 211 | "merge2": "^1.3.0", 212 | "slash": "^3.0.0" 213 | } 214 | }, 215 | "graceful-fs": { 216 | "version": "4.2.4", 217 | "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.4.tgz", 218 | "integrity": "sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw==" 219 | }, 220 | "ieee754": { 221 | "version": "1.1.13", 222 | "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.13.tgz", 223 | "integrity": "sha512-4vf7I2LYV/HaWerSo3XmlMkp5eZ83i+/CDluXi/IGTs/O1sejBNhTtnxzmRZfvOUqj7lZjqHkeTvpgSFDlWZTg==" 224 | }, 225 | "ignore": { 226 | "version": "5.1.8", 227 | "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.8.tgz", 228 | "integrity": "sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw==" 229 | }, 230 | "indent-string": { 231 | "version": "4.0.0", 232 | "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", 233 | "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==" 234 | }, 235 | "inflight": { 236 | "version": "1.0.6", 237 | "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", 238 | "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", 239 | "requires": { 240 | "once": "^1.3.0", 241 | "wrappy": "1" 242 | } 243 | }, 244 | "inherits": { 245 | "version": "2.0.4", 246 | "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", 247 | "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" 248 | }, 249 | "is-extglob": { 250 | "version": "2.1.1", 251 | "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", 252 | "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=" 253 | }, 254 | "is-glob": { 255 | "version": "4.0.1", 256 | "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", 257 | "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", 258 | "requires": { 259 | "is-extglob": "^2.1.1" 260 | } 261 | }, 262 | "is-number": { 263 | "version": "7.0.0", 264 | "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", 265 | "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==" 266 | }, 267 | "is-path-cwd": { 268 | "version": "2.2.0", 269 | "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-2.2.0.tgz", 270 | "integrity": "sha512-w942bTcih8fdJPJmQHFzkS76NEP8Kzzvmw92cXsazb8intwLqPibPPdXf4ANdKV3rYMuuQYGIWtvz9JilB3NFQ==" 271 | }, 272 | "is-path-inside": { 273 | "version": "3.0.2", 274 | "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.2.tgz", 275 | "integrity": "sha512-/2UGPSgmtqwo1ktx8NDHjuPwZWmHhO+gj0f93EkhLB5RgW9RZevWYYlIkS6zePc6U2WpOdQYIwHe9YC4DWEBVg==" 276 | }, 277 | "is-stream": { 278 | "version": "2.0.0", 279 | "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz", 280 | "integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==" 281 | }, 282 | "isarray": { 283 | "version": "1.0.0", 284 | "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", 285 | "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" 286 | }, 287 | "jmespath": { 288 | "version": "0.15.0", 289 | "resolved": "https://registry.npmjs.org/jmespath/-/jmespath-0.15.0.tgz", 290 | "integrity": "sha1-o/Iiqarp+Wb10nx5ZRDigJF2Qhc=" 291 | }, 292 | "merge2": { 293 | "version": "1.4.1", 294 | "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", 295 | "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==" 296 | }, 297 | "micromatch": { 298 | "version": "4.0.2", 299 | "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.2.tgz", 300 | "integrity": "sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q==", 301 | "requires": { 302 | "braces": "^3.0.1", 303 | "picomatch": "^2.0.5" 304 | } 305 | }, 306 | "minimatch": { 307 | "version": "3.0.4", 308 | "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", 309 | "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", 310 | "requires": { 311 | "brace-expansion": "^1.1.7" 312 | } 313 | }, 314 | "once": { 315 | "version": "1.4.0", 316 | "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", 317 | "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", 318 | "requires": { 319 | "wrappy": "1" 320 | } 321 | }, 322 | "p-map": { 323 | "version": "4.0.0", 324 | "resolved": "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz", 325 | "integrity": "sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==", 326 | "requires": { 327 | "aggregate-error": "^3.0.0" 328 | } 329 | }, 330 | "path-is-absolute": { 331 | "version": "1.0.1", 332 | "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", 333 | "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" 334 | }, 335 | "path-type": { 336 | "version": "4.0.0", 337 | "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", 338 | "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==" 339 | }, 340 | "picomatch": { 341 | "version": "2.2.2", 342 | "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz", 343 | "integrity": "sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==" 344 | }, 345 | "punycode": { 346 | "version": "1.3.2", 347 | "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", 348 | "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=" 349 | }, 350 | "querystring": { 351 | "version": "0.2.0", 352 | "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", 353 | "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=" 354 | }, 355 | "reusify": { 356 | "version": "1.0.4", 357 | "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", 358 | "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==" 359 | }, 360 | "rimraf": { 361 | "version": "3.0.2", 362 | "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", 363 | "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", 364 | "requires": { 365 | "glob": "^7.1.3" 366 | } 367 | }, 368 | "run-parallel": { 369 | "version": "1.1.10", 370 | "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.1.10.tgz", 371 | "integrity": "sha512-zb/1OuZ6flOlH6tQyMPUrE3x3Ulxjlo9WIVXR4yVYi4H9UXQaeIsPbLn2R3O3vQCnDKkAl2qHiuocKKX4Tz/Sw==" 372 | }, 373 | "sax": { 374 | "version": "1.2.1", 375 | "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.1.tgz", 376 | "integrity": "sha1-e45lYZCyKOgaZq6nSEgNgozS03o=" 377 | }, 378 | "slash": { 379 | "version": "3.0.0", 380 | "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", 381 | "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==" 382 | }, 383 | "temp-dir": { 384 | "version": "2.0.0", 385 | "resolved": "https://registry.npmjs.org/temp-dir/-/temp-dir-2.0.0.tgz", 386 | "integrity": "sha512-aoBAniQmmwtcKp/7BzsH8Cxzv8OL736p7v1ihGb5e9DJ9kTwGWHrQrVB5+lfVDzfGrdRzXch+ig7LHaY1JTOrg==" 387 | }, 388 | "tempy": { 389 | "version": "1.0.0", 390 | "resolved": "https://registry.npmjs.org/tempy/-/tempy-1.0.0.tgz", 391 | "integrity": "sha512-eLXG5B1G0mRPHmgH2WydPl5v4jH35qEn3y/rA/aahKhIa91Pn119SsU7n7v/433gtT9ONzC8ISvNHIh2JSTm0w==", 392 | "requires": { 393 | "del": "^6.0.0", 394 | "is-stream": "^2.0.0", 395 | "temp-dir": "^2.0.0", 396 | "type-fest": "^0.16.0", 397 | "unique-string": "^2.0.0" 398 | } 399 | }, 400 | "to-regex-range": { 401 | "version": "5.0.1", 402 | "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", 403 | "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", 404 | "requires": { 405 | "is-number": "^7.0.0" 406 | } 407 | }, 408 | "type-fest": { 409 | "version": "0.16.0", 410 | "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.16.0.tgz", 411 | "integrity": "sha512-eaBzG6MxNzEn9kiwvtre90cXaNLkmadMWa1zQMs3XORCXNbsH/OewwbxC5ia9dCxIxnTAsSxXJaa/p5y8DlvJg==" 412 | }, 413 | "unique-string": { 414 | "version": "2.0.0", 415 | "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-2.0.0.tgz", 416 | "integrity": "sha512-uNaeirEPvpZWSgzwsPGtU2zVSTrn/8L5q/IexZmH0eH6SA73CmAA5U4GwORTxQAZs95TAXLNqeLoPPNO5gZfWg==", 417 | "requires": { 418 | "crypto-random-string": "^2.0.0" 419 | } 420 | }, 421 | "url": { 422 | "version": "0.10.3", 423 | "resolved": "https://registry.npmjs.org/url/-/url-0.10.3.tgz", 424 | "integrity": "sha1-Ah5NnHcF8hu/N9A861h2dAJ3TGQ=", 425 | "requires": { 426 | "punycode": "1.3.2", 427 | "querystring": "0.2.0" 428 | } 429 | }, 430 | "uuid": { 431 | "version": "8.3.2", 432 | "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", 433 | "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==" 434 | }, 435 | "wrappy": { 436 | "version": "1.0.2", 437 | "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", 438 | "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" 439 | }, 440 | "xml2js": { 441 | "version": "0.4.19", 442 | "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.19.tgz", 443 | "integrity": "sha512-esZnJZJOiJR9wWKMyuvSE1y6Dq5LCuJanqhxslH2bxM6duahNZ+HMpCLhBQGZkbX6xRf8x1Y2eJlgt2q3qo49Q==", 444 | "requires": { 445 | "sax": ">=0.6.0", 446 | "xmlbuilder": "~9.0.1" 447 | } 448 | }, 449 | "xmlbuilder": { 450 | "version": "9.0.7", 451 | "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-9.0.7.tgz", 452 | "integrity": "sha1-Ey7mPS7FVlxVfiD0wi35rKaGsQ0=" 453 | } 454 | } 455 | } 456 | -------------------------------------------------------------------------------- /joc-lambda-chunk-transcoder/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "joc-lambda-chunk-transcoder", 3 | "version": "1.0.0", 4 | "description": "Lambda that transcodes chunks of video", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [ 10 | "video", 11 | "live", 12 | "transcoder", 13 | "distributed" 14 | ], 15 | "author": "Jordi Cenzano", 16 | "license": "GPL-3.0-or-later", 17 | "dependencies": { 18 | "aws-sdk": "^2.809.0", 19 | "tempy": "^1.0.0", 20 | "uuid": "^8.3.2" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /joc-lambda-chunk-transcoder/scripts/upload-lambda.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Import variables 4 | source ../../scripts/base.sh 5 | 6 | # exit when any command fails 7 | set -e 8 | 9 | #Create ZIP 10 | cd .. 11 | zip upload.zip -r *.js node_modules ffmpeg fonts -x "ffmpeg/.*" -x "scripts/*" -x ".*" -x "node_modules/aws*" 12 | 13 | #Populate lambda 14 | aws --no-cli-pager --no-cli-auto-prompt --region ${AWS_REGION} lambda update-function-code --function-name ${LAMBDA_CHUNK_TRANSCODER_NAME} --zip-file fileb://upload.zip 15 | 16 | #Remove zip 17 | rm upload.zip 18 | 19 | cd - -------------------------------------------------------------------------------- /joc-lambda-manifest-generator/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Jordi Cenzano 2020/12/06 3 | */ 4 | 5 | const aws = require('aws-sdk'); 6 | const { v4: uuidv4 } = require('uuid'); 7 | const querystring = require("querystring"); 8 | const LiveTranscoderConfig = require('./live-transcoder-config'); 9 | const path = require('path'); 10 | 11 | const DDB_MAX_RETRIES_DEF = 3; 12 | 13 | const dbbConfigDataDefault = { 14 | // General 15 | region: 'us-east-1', 16 | 17 | // Config 18 | configName: 'default', 19 | tableName: 'joc-dist-live-config', 20 | } 21 | const dbbChunksDataDefault = { 22 | // General 23 | region: 'us-east-1', 24 | 25 | // Chunks 26 | tableName: 'joc-dist-live-chunks', 27 | } 28 | 29 | const logType = { 30 | INFO: 'info', 31 | WARN: 'warn', 32 | ERR: 'err' 33 | }; 34 | 35 | // Log function 36 | function logData(type, msg, streamID, durationMs, data) { 37 | let dataStr = `[${msg}] [${streamID}] [${durationMs}]`; 38 | if (typeof(data) != 'undefined') { 39 | dataStr = dataStr + ` ${JSON.stringify(data, null, 2)}`; 40 | } 41 | if (type === logType.WARN) { 42 | console.warn(dataStr); 43 | } else if (type === logType.ERR) { 44 | console.error(dataStr); 45 | } 46 | else { 47 | console.log(dataStr); 48 | } 49 | } 50 | 51 | // Lambda is new 52 | const lambdaGUID = uuidv4(); 53 | logData(logType.INFO, 'Loading function', '', 0, lambdaGUID); 54 | 55 | const CONTENT_TYPE_M3U8 = 'application/vnd.apple.mpegurl'; 56 | const CONTENT_TYPE_STR = 'text/plain'; 57 | const MAX_AGE_S_DEF = 4; // Applied for error and main manifest 58 | 59 | const manifestType = { 60 | NONE: 'none', 61 | MANIFEST: 'manifest', 62 | CHUNKLIST: 'chunklist' 63 | } 64 | 65 | const liveType = { 66 | LIVE: 'live', 67 | EVENT: 'event', 68 | VOD: 'vod' 69 | } 70 | 71 | const filterFromManifestToChunklistQS = [ 72 | 'latency', 73 | 'chunksLatency', 74 | 'chunksNumber', 75 | 'fromEpochS', 76 | 'toEpochS', 77 | 'liveType', 78 | 'alternateChunkStreamID' 79 | ]; 80 | 81 | class HTTPErrorData extends Error { 82 | constructor(code, message) { 83 | super(message); 84 | this._code = code; 85 | } 86 | 87 | get code() { return this._code; } 88 | 89 | toString() { 90 | return `${this._code}: ${super.message}`; 91 | } 92 | } 93 | 94 | // Entry point 95 | exports.handler = async (event, context) => { 96 | // Update DDB configs 97 | const dbbConfigData = parseDDBConfig(process.env, dbbConfigDataDefault); 98 | const dbbChunksData = parseDDBChunks(process.env, dbbChunksDataDefault); 99 | 100 | const defaultParams = { 101 | latency: 20,// Deliver live edge - X secs (X = max transcoding chunk time) 102 | chunksLatency: 0, // Deliver live edge - X chunks 103 | chunksNumber: 3, // Deliver # chunks 104 | fromEpochS: -1, 105 | toEpochS: -1, // Not compatible with chunksNumber 106 | liveType: liveType.LIVE, 107 | manifestType: manifestType.NONE, 108 | renditionID: '', 109 | streamID: '', 110 | alternateChunkStreamID: '' 111 | } 112 | 113 | const startMs = getTimeInMilliseconds(); 114 | let streamID = ''; 115 | 116 | logData(logType.INFO, 'Received event', '', 0, event); 117 | try { 118 | 119 | // Fetch config and return it 120 | const transcoderConfig = new LiveTranscoderConfig() 121 | await transcoderConfig.loadFromDDB(dbbConfigData.region, dbbConfigData.tableName, dbbConfigData.configName); 122 | 123 | logData(logType.INFO, 'Fetched config', '', getTimeInMilliseconds() - startMs, transcoderConfig.toString()); 124 | 125 | const manifestConfig = getURLData(event, defaultParams); 126 | streamID = manifestConfig.streamID; 127 | logData(logType.INFO, 'Manifest config from URL', streamID, getTimeInMilliseconds() - startMs, manifestConfig); 128 | 129 | // Check if this is manifest or chunklist 130 | let maxAgeS = MAX_AGE_S_DEF; 131 | if (manifestConfig.manifestType === manifestType.MANIFEST) { 132 | res = createManifest(manifestConfig, transcoderConfig); 133 | } 134 | else if (manifestConfig.manifestType === manifestType.CHUNKLIST) { 135 | const chunks = await ddbGetChunks(dbbChunksData, manifestConfig); 136 | res = createChunklist(manifestConfig, transcoderConfig, chunks); 137 | maxAgeS = getTargetDurationMs(chunks) / (2 * 1000); 138 | } 139 | logData(logType.INFO, 'Response 200', streamID, getTimeInMilliseconds() - startMs, res); 140 | 141 | return response(context, 200, res, CONTENT_TYPE_M3U8, maxAgeS); 142 | } 143 | catch(e) { 144 | let errCode = 500; 145 | const errMsg = e.message; 146 | if (e instanceof HTTPErrorData) { 147 | errCode = e.code; 148 | } 149 | logData(logType.INFO, `Response ${errCode}`, streamID, getTimeInMilliseconds() - startMs, errMsg); 150 | 151 | return response(context, errCode, errMsg, CONTENT_TYPE_STR, MAX_AGE_S_DEF); 152 | } 153 | } 154 | 155 | function getTargetDurationMs(chunks) { 156 | let retMs = 10000; 157 | 158 | for (let n = 0; n < chunks.length; n++) { 159 | const chunk = chunks[n]; 160 | if (chunk['target-duration-ms'] < retMs) { 161 | retMs = chunk['target-duration-ms']; 162 | } 163 | } 164 | return retMs; 165 | } 166 | 167 | function createManifest(manifestConfig, transcoderConfig) { 168 | const manifestLines = []; 169 | 170 | manifestLines.push('#EXTM3U'); 171 | manifestLines.push('#EXT-X-VERSION:3'); 172 | for (let n = 0; n < transcoderConfig.getParam('renditions').length; n++){ 173 | const rendition = transcoderConfig.getParam('renditions')[n]; 174 | manifestLines.push(`#EXT-X-STREAM-INF:BANDWIDTH=${rendition.video_maxrate},RESOLUTION=${rendition.width}x${rendition.height}`); 175 | // Chunklist URL (relative) 176 | manifestLines.push(`${rendition.ID}/chunklist.m3u8?${createQSForChunklist(manifestConfig)}`); 177 | } 178 | return manifestLines.join("\n"); 179 | } 180 | 181 | function createChunklist(manifestConfig, transcoderConfig, chunks) { 182 | const manifestLines = []; 183 | 184 | manifestLines.push('#EXTM3U'); 185 | if (manifestConfig.liveType === liveType.EVENT) { 186 | manifestLines.push('#EXT-X-PLAYLIST-TYPE:EVENT'); 187 | } 188 | manifestLines.push('#EXT-X-VERSION:3'); 189 | const targetDurationMs = getTargetDurationMs(chunks); 190 | for (let n = chunks.length - 1; n >= 0; n--) { 191 | const chunk = chunks[n]; 192 | // Is 1st one 193 | if (n === chunks.length - 1) { 194 | manifestLines.push(`#EXT-X-MEDIA-SEQUENCE:${chunk['seq-number']}`); 195 | manifestLines.push('#EXT-X-DISCONTINUITY-SEQUENCE:0'); 196 | manifestLines.push(`#EXT-X-TARGETDURATION:${(targetDurationMs/1000).toFixed(0)}`); 197 | manifestLines.push("#EXT-X-INDEPENDENT-SEGMENTS"); 198 | } 199 | manifestLines.push(`#EXTINF:${(chunk['duration-ms']/1000).toFixed(8)},`); 200 | 201 | alternateChunkStreamID = manifestConfig.alternateChunkStreamID 202 | if ((alternateChunkStreamID !== "") && (chunk['seq-number'] % 2 === 0)) { 203 | // This is used for active active testing purposes ONLY!! 204 | filePath = path.parse(chunk['file-path']) 205 | pathDirs = filePath.dir.split("/") 206 | if (pathDirs.length > 0) { 207 | pathDirs[0] = alternateChunkStreamID 208 | } 209 | filePath.dir = pathDirs.join('/') 210 | finalChunkPath = path.format(filePath) 211 | 212 | manifestLines.push(new URL(finalChunkPath, transcoderConfig.getParam('mediaCdnPrefix')).toString()); 213 | } else { 214 | manifestLines.push(new URL(chunk['file-path'], transcoderConfig.getParam('mediaCdnPrefix')).toString()); 215 | } 216 | 217 | // Is last one 218 | if ((n === 0) && (manifestConfig.liveType === liveType.VOD)) { 219 | manifestLines.push('#EXT-X-ENDLIST'); 220 | } 221 | } 222 | return manifestLines.join("\n"); 223 | } 224 | 225 | function response(context, code, body, contentType, maxAgeS) { 226 | const headers = {}; 227 | let errorType = ''; 228 | if (typeof(contentType) === 'string') {headers['Content-Type'] = contentType;} 229 | if (typeof(maxAgeS) === 'number') {headers['Cache-Control'] = `max-age=${Math.floor(maxAgeS).toString()}`}; 230 | 231 | if ((code >= 400) && (code < 500)) { 232 | errorType = 'InvalidParameterException'; 233 | } else if (code >= 500) { 234 | errorType = 'InternalServerError'; 235 | } 236 | 237 | return {statusCode: code, errorType: errorType, requestId : context.awsRequestId, body: body, headers: headers, isBase64Encoded: false}; 238 | } 239 | 240 | function checkPresentAndType(value, name, type, isEmptyConsideredFalse) { 241 | if ((name in value) && (typeof(value[name]) === type)) { 242 | if ((isEmptyConsideredFalse) && type === 'string' && (value[name] === "")) { 243 | return false; 244 | } 245 | return true; 246 | } 247 | return false; 248 | } 249 | 250 | function createQSForChunklist(manifestConfig) { 251 | const filteredQS = {}; 252 | for (const [key, value] of Object.entries(manifestConfig)) { 253 | if (filterFromManifestToChunklistQS.includes(key)) { 254 | filteredQS[key] = value; 255 | } 256 | } 257 | return querystring.stringify(filteredQS); 258 | } 259 | 260 | function getURLData(event, defaultConfig) { 261 | const ret = defaultConfig; 262 | 263 | if (!checkPresentAndType(event, 'pathParameters', 'object')) { 264 | throw new HTTPErrorData(400, 'No streamID or renditionID in the URL path'); 265 | } 266 | if (checkPresentAndType(event.pathParameters, 'streamID', 'string')) { 267 | ret.streamID = event.pathParameters.streamID; 268 | ret.manifestType = manifestType.MANIFEST; 269 | } 270 | if (checkPresentAndType(event.pathParameters, 'renditionID', 'string')) { 271 | if (event.pathParameters.renditionID !== "") { 272 | ret.renditionID = event.pathParameters.renditionID; 273 | ret.manifestType = manifestType.CHUNKLIST; 274 | } 275 | } 276 | if(ret.manifestType === manifestType.NONE) { 277 | throw new HTTPErrorData(400, 'Could not parse streamID or/and renditionID in the URL path'); 278 | } 279 | 280 | if (checkPresentAndType(event, 'queryStringParameters', 'object')) { 281 | if (checkPresentAndType(event.queryStringParameters, 'liveType', 'string', true)) { 282 | if (Object.values(liveType).indexOf(event.queryStringParameters.liveType) < 0) { 283 | throw new HTTPErrorData(400, 'invalid liveType'); 284 | } 285 | ret.liveType = event.queryStringParameters.liveType; 286 | } 287 | if (checkPresentAndType(event.queryStringParameters, 'chunksNumber', 'string', true)) { 288 | ret.chunksNumber = parseInt(event.queryStringParameters.chunksNumber); 289 | } 290 | // For VOD and event we return all media 291 | if ((event.queryStringParameters.liveType === liveType.VOD) || (event.queryStringParameters.liveType === liveType.EVENT)) { 292 | ret.chunksNumber = -1; 293 | } 294 | 295 | // Load latency to provide chunklist 296 | // Check "latency", if not there use default 297 | if (checkPresentAndType(event.queryStringParameters, 'latency', 'string', true)) { 298 | ret.latency = parseInt(event.queryStringParameters.latency, 10); 299 | } 300 | else if (checkPresentAndType(event.queryStringParameters, 'chunksLatency', 'string', true)) { 301 | ret.chunksLatency = parseInt(event.queryStringParameters.chunksLatency, 10); 302 | } 303 | 304 | // Load from 305 | if (checkPresentAndType(event.queryStringParameters, 'fromEpochS', 'string', true)) { 306 | ret.fromEpochS = parseInt(event.queryStringParameters.fromEpochS, 10); 307 | } 308 | 309 | // Load to (only valid for VOD) 310 | if ((ret.liveType === liveType.VOD) && (checkPresentAndType(event.queryStringParameters, 'toEpochS', 'string', true))) { 311 | ret.toEpochS = parseInt(event.queryStringParameters.toEpochS, 10); 312 | } 313 | 314 | // Check from - to 315 | if ((ret.fromEpochS >= 0) && (ret.toEpochS >= 0) && (ret.toEpochS <= ret.fromEpochS)) { 316 | throw new HTTPErrorData(400, 'toEpochS can not be equal or lower than fromEpochS'); 317 | } 318 | 319 | // Only used for active-active testing!!!! 320 | if (checkPresentAndType(event.queryStringParameters, 'alternateChunkStreamID', 'string')) { 321 | if (event.queryStringParameters.alternateChunkStreamID !== "") { 322 | ret.alternateChunkStreamID = event.queryStringParameters.alternateChunkStreamID; 323 | } 324 | } 325 | } 326 | return ret; 327 | } 328 | 329 | // Helpers 330 | 331 | function parseDDBConfig(envVars, defaultDBBConfig) { 332 | ret = defaultDBBConfig; 333 | if ((typeof(envVars.AWS_REGION) === 'string') && (envVars.AWS_REGION != "")) { 334 | ret.region = envVars.AWS_REGION; 335 | } 336 | if ((typeof(envVars.DDB_CONFIG_TABLE_NAME) === 'string') && (envVars.DDB_CONFIG_TABLE_NAME != "")) { 337 | ret.tableName = envVars.DDB_CONFIG_TABLE_NAME; 338 | } 339 | 340 | console.log(`Dynamo table config data: ${JSON.stringify(ret)}`); 341 | 342 | return ret; 343 | } 344 | 345 | function parseDDBChunks(envVars, defaultDBBChunks) { 346 | ret = defaultDBBChunks; 347 | if ((typeof(envVars.AWS_REGION) === 'string') && (envVars.AWS_REGION != "")) { 348 | ret.region = envVars.AWS_REGION; 349 | } 350 | if ((typeof(envVars.DDB_CONFIG_TABLE_CHUNKS) === 'string') && (envVars.DDB_CONFIG_TABLE_CHUNKS != "")) { 351 | ret.tableName = envVars.DDB_CONFIG_TABLE_CHUNKS; 352 | } 353 | 354 | console.log(`Dynamo table chunks data: ${JSON.stringify(ret)}`); 355 | 356 | return ret; 357 | } 358 | 359 | // DDB 360 | 361 | async function ddbGetChunks(dbbChunksData, manifestConfig) { 362 | const ret = []; 363 | let limitChunksToGet = Number.MAX_SAFE_INTEGER; 364 | if (manifestConfig.chunksNumber > 0) { 365 | if (manifestConfig.chunksLatency > 0) { 366 | limitChunksToGet = manifestConfig.chunksNumber + manifestConfig.chunksLatency; 367 | } 368 | else { 369 | limitChunksToGet = manifestConfig.chunksNumber; 370 | } 371 | } 372 | 373 | const ddb = new aws.DynamoDB({region: dbbChunksData.region, maxRetries: DDB_MAX_RETRIES_DEF}); 374 | // Query Item 375 | let wcStartEpochSStr = "0"; 376 | let wcEndEpochSStr = "99999999999999999999999999999999999999"; 377 | if (manifestConfig.fromEpochS > 0) { 378 | wcStartEpochSStr = Math.floor(manifestConfig.fromEpochS * 1000 * 1000 * 1000).toString(); // To ns 379 | } 380 | if (manifestConfig.toEpochS > 0) { 381 | wcEndEpochSStr = Math.floor(manifestConfig.toEpochS * 1000 * 1000 * 1000).toString(); // To ns 382 | } else if (manifestConfig.latency > 0) { 383 | const limitMs = Date.now() - (manifestConfig.latency * 1000); 384 | wcEndEpochSStr = Math.floor(limitMs * 1000 * 1000).toString(); // To ns 385 | } 386 | const params = { 387 | TableName: dbbChunksData.tableName, 388 | IndexName: "stream-id-wallclock-epoch-ns-index", 389 | KeyConditionExpression: "#streamid = :streamid and #wallclockepochns between :wallclockstart and :wallclockend", 390 | FilterExpression: '#renditionid = :renditionid', 391 | ExpressionAttributeNames:{ 392 | "#streamid": "stream-id", 393 | "#wallclockepochns": "wallclock-epoch-ns", 394 | "#renditionid": "rendition-id", 395 | }, 396 | ExpressionAttributeValues: { 397 | ":streamid": {S: manifestConfig.streamID}, 398 | ":renditionid": {S: manifestConfig.renditionID}, 399 | ":wallclockstart": {N: wcStartEpochSStr}, 400 | ":wallclockend": {N: wcEndEpochSStr}, 401 | }, 402 | ScanIndexForward: false, 403 | Limit: limitChunksToGet 404 | }; 405 | 406 | let moreData = false; 407 | do { 408 | moreData = false; 409 | const dbbData = await ddb.query(params).promise(); 410 | for (let n = 0; n < dbbData.Items.length; n++) { 411 | ret.push(aws.DynamoDB.Converter.unmarshall(dbbData.Items[n])); 412 | } 413 | if (('LastEvaluatedKey' in dbbData) && (Object.keys(dbbData.LastEvaluatedKey).length > 0)) { 414 | params.ExclusiveStartKey = dbbData.LastEvaluatedKey; 415 | moreData = true; 416 | } 417 | } while ((moreData) && (ret.length < params.Limit)); 418 | 419 | // Remove extra items from the oldest ones 420 | while (ret.length > limitChunksToGet) { 421 | ret.splice(-1,1); 422 | } 423 | // Remove extra items from the newest, since perhaps those are 424 | if (manifestConfig.chunksLatency > 0) { 425 | let chunksToDel = manifestConfig.chunksLatency; 426 | while (chunksToDel > 0) { 427 | ret.shift(); 428 | chunksToDel--; 429 | } 430 | } 431 | return ret; 432 | } 433 | 434 | function getTimeInMilliseconds() { 435 | const hrTime = process.hrtime() 436 | return hrTime[0] * 1000 + hrTime[1] / 1000000; 437 | } 438 | -------------------------------------------------------------------------------- /joc-lambda-manifest-generator/live-transcoder-config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Jordi Cenzano 2020/12/06 3 | */ 4 | 5 | const aws = require('aws-sdk'); 6 | 7 | // Example config object 8 | /* 9 | { 10 | "copyOriginalContentTypeToABRChunks": true, 11 | "copyOriginalMetadataToABRChunks": true, 12 | "overlayEncodingData": true, 13 | "overlayMessage": "Test-", 14 | "publicReadToABRChunks": true, 15 | "renditions": [ 16 | { 17 | "height": 480, 18 | "ID": "480p", 19 | "video_buffersize": 4194304, 20 | "video_h264_level": "3.0", 21 | "video_h264_preset": "ultrafast", 22 | "video_h264_profile": "main", 23 | "video_maxrate": 2097152, 24 | "width": 854 25 | }, 26 | { 27 | "height": 360, 28 | "ID": "360p", 29 | "video_buffersize": 2097152, 30 | "video_h264_level": "3.0", 31 | "video_h264_preset": "ultrafast", 32 | "video_h264_profile": "main", 33 | "video_maxrate": 1048576, 34 | "width": 640 35 | } 36 | ], 37 | "s3OutputPrefix": "output/" 38 | } 39 | } 40 | */ 41 | 42 | class LiveTranscoderConfig { 43 | constructor() { 44 | this.DDB_MAX_RETRIES_DEF = 3; 45 | 46 | this.loaded = false; 47 | this.config = {}; 48 | this.ddb = null; 49 | } 50 | 51 | async loadFromDDB(region, tableName, configName) { 52 | // Create DDB object 53 | if (this.ddb === null) { 54 | this.ddb = new aws.DynamoDB({region: region, maxRetries: this.DDB_MAX_RETRIES_DEF}); 55 | } 56 | 57 | // Read Item 58 | const params = { 59 | Key: {"config-name": {S: configName}}, 60 | TableName: tableName 61 | }; 62 | const dbbData = await this.ddb.getItem(params).promise(); 63 | this.config = aws.DynamoDB.Converter.unmarshall(dbbData.Item).value; 64 | this.loaded = true; 65 | 66 | return this.loaded; 67 | } 68 | 69 | // Get data 70 | getParam(name) { 71 | return this.checkIntegrityAndReturn(name); 72 | } 73 | getParamDefault(name, defaultValue) { 74 | try { 75 | return this.checkIntegrityAndReturn(name); 76 | } 77 | catch(e) { 78 | return defaultValue; 79 | } 80 | } 81 | 82 | toString() { 83 | return JSON.stringify(this.config); 84 | } 85 | 86 | checkIntegrityAndReturn(name) { 87 | if (!this.loaded) { 88 | throw new Error (`Tried to access to a non loaded transcoding config`); 89 | } 90 | if (!(name in this.config)) { 91 | throw new Error (`Property ${name} not found in transcoding config`); 92 | } 93 | return this.config[name]; 94 | } 95 | } 96 | 97 | module.exports = LiveTranscoderConfig; -------------------------------------------------------------------------------- /joc-lambda-manifest-generator/local-test.js: -------------------------------------------------------------------------------- 1 | const underTest = require('./index.js'); 2 | 3 | const testEventChunklist = { 4 | "version":"2.0", 5 | "routeKey":"GET /video/{streamID}/{renditionID}", 6 | "rawPath":"/video/1/2", 7 | "rawQueryString":"name=jordi", 8 | "headers":{ 9 | "accept":"*/*", 10 | "content-length":"0", 11 | "host":"hml7q7d334.execute-api.us-east-1.amazonaws.com", 12 | "user-agent":"curl/7.64.1", 13 | "x-amzn-trace-id":"Root=1-5fd73a35-193fdaa414ca9f0b4cf6c289", 14 | "x-forwarded-for":"83.51.200.53", 15 | "x-forwarded-port":"443", 16 | "x-forwarded-proto":"https" 17 | }, 18 | "requestContext":{ 19 | "accountId":"957270781853", 20 | "apiId":"hml7q7d334", 21 | "domainName":"hml7q7d334.execute-api.us-east-1.amazonaws.com", 22 | "domainPrefix":"hml7q7d334", 23 | "http":{ 24 | "method":"GET", 25 | "path":"/video/1/2", 26 | "protocol":"HTTP/1.1", 27 | "sourceIp":"83.51.200.53", 28 | "userAgent":"curl/7.64.1" 29 | }, 30 | "requestId":"XiYIUgsMoAMEJXg=", 31 | "routeKey":"GET /video/{streamID}/{renditionID}", 32 | "stage":"$default", 33 | "time":"14/Dec/2020:10:11:01 +0000", 34 | "timeEpoch":1607940661123 35 | }, 36 | "pathParameters":{ 37 | "renditionID":"480p", 38 | "streamID":"20210101232828" 39 | //"streamID":"1" 40 | }, 41 | "queryStringParameters": { 42 | "liveType": "vod", 43 | "latency": "60", 44 | "fromEpochS": "1578078938", 45 | "toEpochS": "1609701339", 46 | //"alternateChunkStreamID": "alternateID" 47 | //"chunksLatency": "-1", 48 | //"chunksNumber": "1000" 49 | }, 50 | "isBase64Encoded":false 51 | }; 52 | 53 | const testEventManifest = { 54 | "version":"2.0", 55 | "routeKey":"GET /video/{streamID}/", 56 | "rawPath":"/video/1/2", 57 | "rawQueryString":"name=jordi", 58 | "headers":{ 59 | "accept":"*/*", 60 | "content-length":"0", 61 | "host":"hml7q7d334.execute-api.us-east-1.amazonaws.com", 62 | "user-agent":"curl/7.64.1", 63 | "x-amzn-trace-id":"Root=1-5fd73a35-193fdaa414ca9f0b4cf6c289", 64 | "x-forwarded-for":"83.51.200.53", 65 | "x-forwarded-port":"443", 66 | "x-forwarded-proto":"https" 67 | }, 68 | "requestContext":{ 69 | "accountId":"957270781853", 70 | "apiId":"hml7q7d334", 71 | "domainName":"hml7q7d334.execute-api.us-east-1.amazonaws.com", 72 | "domainPrefix":"hml7q7d334", 73 | "http":{ 74 | "method":"GET", 75 | "path":"/video/1/2", 76 | "protocol":"HTTP/1.1", 77 | "sourceIp":"83.51.200.53", 78 | "userAgent":"curl/7.64.1" 79 | }, 80 | "requestId":"XiYIUgsMoAMEJXg=", 81 | "routeKey":"GET /video/{streamID}", 82 | "stage":"$default", 83 | "time":"14/Dec/2020:10:11:01 +0000", 84 | "timeEpoch":1607940661123 85 | }, 86 | "pathParameters":{ 87 | "streamID":"20210101232828" 88 | }, 89 | "queryStringParameters": { 90 | "liveType": "vod", 91 | "latency": "60", 92 | "fromEpochS": "1578078938", 93 | "toEpochS": "1609701339", 94 | "alternateChunkStreamID": "alternateID" 95 | //"chunksLatency": "-1", 96 | //"chunksNumber": "1000" 97 | }, 98 | "isBase64Encoded":false 99 | }; 100 | 101 | const context = { 102 | isLocalDebug: true, 103 | testFfmpeg: false 104 | }; 105 | 106 | async function main() { 107 | console.log('[LOCAL] Start') 108 | const ret = await underTest.handler(testEventManifest, context); 109 | console.log('[LOCAL] end. Ret: ' + JSON.stringify(ret)); 110 | } 111 | 112 | main(); 113 | 114 | -------------------------------------------------------------------------------- /joc-lambda-manifest-generator/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "joc-lambda-manifest-generator", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "aws-sdk": { 8 | "version": "2.809.0", 9 | "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.809.0.tgz", 10 | "integrity": "sha512-wPmb3DbS2+jXzj3aBV9nbRY/rsTqceriXZBsLM9VOGknkULfcnM0vCpm9psgAR87DvevO+NhPoc2kNAEdFkvzg==", 11 | "requires": { 12 | "buffer": "4.9.2", 13 | "events": "1.1.1", 14 | "ieee754": "1.1.13", 15 | "jmespath": "0.15.0", 16 | "querystring": "0.2.0", 17 | "sax": "1.2.1", 18 | "url": "0.10.3", 19 | "uuid": "3.3.2", 20 | "xml2js": "0.4.19" 21 | }, 22 | "dependencies": { 23 | "uuid": { 24 | "version": "3.3.2", 25 | "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", 26 | "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==" 27 | } 28 | } 29 | }, 30 | "base64-js": { 31 | "version": "1.5.1", 32 | "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", 33 | "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==" 34 | }, 35 | "buffer": { 36 | "version": "4.9.2", 37 | "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.2.tgz", 38 | "integrity": "sha512-xq+q3SRMOxGivLhBNaUdC64hDTQwejJ+H0T/NB1XMtTVEwNTrfFF3gAxiyW0Bu/xWEGhjVKgUcMhCrUy2+uCWg==", 39 | "requires": { 40 | "base64-js": "^1.0.2", 41 | "ieee754": "^1.1.4", 42 | "isarray": "^1.0.0" 43 | } 44 | }, 45 | "events": { 46 | "version": "1.1.1", 47 | "resolved": "https://registry.npmjs.org/events/-/events-1.1.1.tgz", 48 | "integrity": "sha1-nr23Y1rQmccNzEwqH1AEKI6L2SQ=" 49 | }, 50 | "ieee754": { 51 | "version": "1.1.13", 52 | "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.13.tgz", 53 | "integrity": "sha512-4vf7I2LYV/HaWerSo3XmlMkp5eZ83i+/CDluXi/IGTs/O1sejBNhTtnxzmRZfvOUqj7lZjqHkeTvpgSFDlWZTg==" 54 | }, 55 | "isarray": { 56 | "version": "1.0.0", 57 | "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", 58 | "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" 59 | }, 60 | "jmespath": { 61 | "version": "0.15.0", 62 | "resolved": "https://registry.npmjs.org/jmespath/-/jmespath-0.15.0.tgz", 63 | "integrity": "sha1-o/Iiqarp+Wb10nx5ZRDigJF2Qhc=" 64 | }, 65 | "punycode": { 66 | "version": "1.3.2", 67 | "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", 68 | "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=" 69 | }, 70 | "querystring": { 71 | "version": "0.2.0", 72 | "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", 73 | "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=" 74 | }, 75 | "sax": { 76 | "version": "1.2.1", 77 | "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.1.tgz", 78 | "integrity": "sha1-e45lYZCyKOgaZq6nSEgNgozS03o=" 79 | }, 80 | "url": { 81 | "version": "0.10.3", 82 | "resolved": "https://registry.npmjs.org/url/-/url-0.10.3.tgz", 83 | "integrity": "sha1-Ah5NnHcF8hu/N9A861h2dAJ3TGQ=", 84 | "requires": { 85 | "punycode": "1.3.2", 86 | "querystring": "0.2.0" 87 | } 88 | }, 89 | "uuid": { 90 | "version": "8.3.2", 91 | "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", 92 | "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==" 93 | }, 94 | "xml2js": { 95 | "version": "0.4.19", 96 | "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.19.tgz", 97 | "integrity": "sha512-esZnJZJOiJR9wWKMyuvSE1y6Dq5LCuJanqhxslH2bxM6duahNZ+HMpCLhBQGZkbX6xRf8x1Y2eJlgt2q3qo49Q==", 98 | "requires": { 99 | "sax": ">=0.6.0", 100 | "xmlbuilder": "~9.0.1" 101 | } 102 | }, 103 | "xmlbuilder": { 104 | "version": "9.0.7", 105 | "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-9.0.7.tgz", 106 | "integrity": "sha1-Ey7mPS7FVlxVfiD0wi35rKaGsQ0=" 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /joc-lambda-manifest-generator/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "joc-lambda-manifest-generator", 3 | "version": "1.0.0", 4 | "description": "Lambda that generates an HLS manifest from DDB data in real time", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [ 10 | "video", 11 | "live", 12 | "transcoder", 13 | "distributed" 14 | ], 15 | "author": "Jordi Cenzano", 16 | "license": "GPL-3.0-or-later", 17 | "dependencies": { 18 | "aws-sdk": "^2.809.0", 19 | "uuid": "^8.3.2" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /joc-lambda-manifest-generator/scripts/upload-lambda.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Import variables 4 | source ../../scripts/base.sh 5 | 6 | # exit when any command fails 7 | set -e 8 | 9 | #Create ZIP 10 | cd .. 11 | zip upload.zip -r *.js node_modules -x "scripts/*" -x ".*" -x "node_modules/aws*" 12 | 13 | #Populate lambda 14 | aws --no-cli-pager --no-cli-auto-prompt --region ${AWS_REGION} lambda update-function-code --function-name ${LAMBDA_MANIFEST_NAME} --zip-file fileb://upload.zip 15 | 16 | #Remove zip 17 | rm upload.zip 18 | 19 | cd - -------------------------------------------------------------------------------- /scripts/attach-instance-profile-to-ec2.sh: -------------------------------------------------------------------------------- 1 | # Import variables 2 | source base.sh 3 | 4 | # exit when any command fails 5 | set -e 6 | 7 | if [ $# -lt 1 ]; then 8 | echo "Use ./attach-instance-profile-to-ec2.sh InstanceID\n" 9 | echo "InstanceID: InstanceID of the ec2 edge machine (example: i-0e8c876bb6f3cd69e)" 10 | echo "Example: ./attach-instance-profile-to-ec2.sh i-0e8c876bb6f3cd69e" 11 | exit 1 12 | fi 13 | 14 | # Instance ID 15 | EC2_INSTANCE_ID=$1 16 | 17 | echo "Attaching $IAM_INSTANCE_PROFILE_S3_FULL_ACCESS to $EC2_INSTANCE_ID" 18 | aws $AWS_FLAGS --region $AWS_REGION ec2 associate-iam-instance-profile --instance-id $EC2_INSTANCE_ID --iam-instance-profile Name="$IAM_INSTANCE_PROFILE_S3_FULL_ACCESS" -------------------------------------------------------------------------------- /scripts/base.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Variables used to create AWS env 4 | # **** MODIFY THOSE 2 VARS WITH THE REGION AND BASE NAMES YOU WANT!! 5 | AWS_REGION="eu-west-3" # Paris 6 | BASE_NAME="joc-live-dist-transcoder" 7 | 8 | # *********** 9 | 10 | S3_BUCKET_NAME="$BASE_NAME-bucket-media" 11 | 12 | IAM_EC2_ROLE_S3_FULL_ACCESS="$BASE_NAME-ec2-role-s3-full-access" 13 | IAM_POLICY_S3_FULL_ACCESS="$BASE_NAME-policy-s3-full-access" 14 | IAM_POLICY_DDB_FULL_ACCESS="$BASE_NAME-policy-ddb-full-access" 15 | IAM_POLICY_DDB_READ_ACCESS="$BASE_NAME-policy-ddb-read-access" 16 | IAM_POLICY_LAMBDA_LOGS="$BASE_NAME-policy-cloudwatch-logs" 17 | IAM_INSTANCE_PROFILE_S3_FULL_ACCESS="$BASE_NAME-instance-profile-s3-full-access" 18 | 19 | DDB_CONFIG_TABLE_NAME="$BASE_NAME-ddb-configs" 20 | DDB_CONFIG_TABLE_CHUNKS="$BASE_NAME-ddb-chunks" 21 | 22 | IAM_LAMBDA_ROLE_CHUNK_TRANSCODER="$BASE_NAME-role-lambda-chunk-transcoder" 23 | LAMBDA_CHUNK_TRANSCODER_NAME="$BASE_NAME-lambda-chunk-transcoder" 24 | IAM_LAMBDA_ROLE_MANIFEST="$BASE_NAME-role-lambda-manifest" 25 | LAMBDA_MANIFEST_NAME="$BASE_NAME-lambda-manifest" 26 | 27 | CLOUDFRONT_DISTRIBUTION_NAME="$BASE_NAME-cloudfront-media" 28 | CLOUDFRONT_ORIGIN_SHIELD_REGION="eu-west-2" # London (Not all regions are available for origin shield) 29 | 30 | AWS_APIGATEWAY_NAME="api-live-distribuited-platform" 31 | 32 | # AWS default input flabs 33 | AWS_FLAGS="--no-cli-pager --no-cli-auto-prompt" 34 | AWS_FLAGS_JSON="$AWS_FLAGS --output json" 35 | AWS_FLAGS_TEXT="$AWS_FLAGS --output text" 36 | -------------------------------------------------------------------------------- /scripts/create-cloudfront.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Import variables 4 | source base.sh 5 | 6 | # exit when any command fails 7 | set -e 8 | 9 | # Create Cloudfront access identity to allow only access throght CF 10 | echo "Creating Cloudfront access identity" 11 | CF_ORIGIN_ACCESS_IDENTITY=$(aws $AWS_FLAGS_TEXT cloudfront create-cloud-front-origin-access-identity --cloud-front-origin-access-identity-config 'CallerReference="20210221213400",Comment="Access to media through CF"' --query 'CloudFrontOriginAccessIdentity.Id') 12 | 13 | # Create HLS + QS cache policy 14 | CF_HLS_QS_CACHE_POLICY_ID=$(aws $AWS_FLAGS_TEXT cloudfront create-cache-policy --cache-policy-config file://../config/cloudfront-cache-policy.json --query 'CachePolicy.Id') 15 | 16 | # Create CORS request policy 17 | CF_ORIGIN_REQUEST_POLICY_ID=$(aws $AWS_FLAGS_TEXT cloudfront create-origin-request-policy --origin-request-policy-config file://../config/cloudfront-origin-request-policy.json --query 'OriginRequestPolicy.Id') 18 | 19 | # Replacements 20 | SOURCE_FILE_DIST="../config/cloudfront-REPLACE.txt" 21 | DEST_FILE_DIST="../config/cloudfront.json" 22 | 23 | sed -e "s/<>/${CLOUDFRONT_DISTRIBUTION_NAME}/g" \ 24 | -e "s/<>/${CF_ORIGIN_ACCESS_IDENTITY}/g" \ 25 | -e "s/<>/${S3_BUCKET_NAME}/g" \ 26 | -e "s/<>/${CLOUDFRONT_ORIGIN_SHIELD_REGION}/g" \ 27 | -e "s/<>/${CF_HLS_QS_CACHE_POLICY_ID}/g" \ 28 | -e "s/<>/${CF_ORIGIN_REQUEST_POLICY_ID}/g" \ 29 | $SOURCE_FILE_DIST > $DEST_FILE_DIST 30 | 31 | # Create cloudfront dist 32 | echo "Creating Cloudfront distribuition $CLOUDFRONT_DISTRIBUTION_NAME (with origin access identity: $CF_ORIGIN_ACCESS_IDENTITY, Cache policy ID: $CF_HLS_QS_CACHE_POLICY_ID, Req polixy ID: $CF_ORIGIN_REQUEST_POLICY_ID)" 33 | aws $AWS_FLAGS_JSON cloudfront create-distribution-with-tags --distribution-config file://$DEST_FILE_DIST 34 | 35 | # Remove replaced file 36 | rm $DEST_FILE_DIST 37 | 38 | # Replacements 39 | SOURCE_FILE_S3_POLICY="../config/s3-allow-cloudfront-read-policy-REPLACE.txt" 40 | DEST_FILE_S3_POLICY="../config/s3-allow-cloudfront-read-policy.json" 41 | 42 | sed -e "s/<>/${CF_ORIGIN_ACCESS_IDENTITY}/g" \ 43 | -e "s/<>/${S3_BUCKET_NAME}/g" \ 44 | $SOURCE_FILE_S3_POLICY > $DEST_FILE_S3_POLICY 45 | 46 | # Set S3 policy that allow CF to read from 47 | echo "Allowing Cloudfront distribuition $CLOUDFRONT_DISTRIBUTION_NAME (with origin access identity: $CF_ORIGIN_ACCESS_IDENTITY) to read from S3 bucket $S3_BUCKET_NAME" 48 | aws $AWS_FLAGS_JSON --region $AWS_REGION s3api put-bucket-policy --bucket $S3_BUCKET_NAME --policy file://$DEST_FILE_S3_POLICY 49 | 50 | # Remove replaced file 51 | rm $DEST_FILE_S3_POLICY -------------------------------------------------------------------------------- /scripts/create-ddb.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Import variables 4 | source base.sh 5 | 6 | # exit when any command fails 7 | set -e 8 | 9 | echo "Creating table $DDB_CONFIG_TABLE_NAME" 10 | aws $AWS_FLAGS_JSON --region $AWS_REGION dynamodb create-table --table-name $DDB_CONFIG_TABLE_NAME --attribute-definitions AttributeName=config-name,AttributeType=S --key-schema AttributeName=config-name,KeyType=HASH --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 11 | 12 | echo "Creating table $DDB_CONFIG_TABLE_CHUNKS with GSI" 13 | aws $AWS_FLAGS_JSON --region $AWS_REGION dynamodb create-table --table-name $DDB_CONFIG_TABLE_CHUNKS --attribute-definitions AttributeName=stream-id,AttributeType=S AttributeName=uid,AttributeType=S AttributeName=wallclock-epoch-ns,AttributeType=N --key-schema AttributeName=uid,KeyType=HASH AttributeName=stream-id,KeyType=RANGE --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 --global-secondary-indexes "[{\"IndexName\": \"stream-id-wallclock-epoch-ns-index\", \"KeySchema\": [{\"AttributeName\": \"stream-id\", \"KeyType\": \"HASH\"}, {\"AttributeName\": \"wallclock-epoch-ns\", \"KeyType\": \"RANGE\"}], \"Projection\": {\"ProjectionType\": \"ALL\"}, \"ProvisionedThroughput\": {\"ReadCapacityUnits\": 5, \"WriteCapacityUnits\": 5}}]" -------------------------------------------------------------------------------- /scripts/create-manifest-lambda.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Import variables 4 | source base.sh 5 | 6 | # exit when any command fails 7 | set -e 8 | 9 | # Create role 10 | echo "Creating role $IAM_LAMBDA_ROLE_MANIFEST in $AWS_REGION" 11 | aws $AWS_FLAGS_JSON --region $AWS_REGION iam create-role --role-name $IAM_LAMBDA_ROLE_MANIFEST --assume-role-policy-document file://../config/lambda-role-trust-policy.json 12 | 13 | # Add policies to role 14 | echo "Adding policy $IAM_POLICY_DDB_READ_ACCESS to role $IAM_LAMBDA_ROLE_MANIFEST" 15 | aws $AWS_FLAGS_JSON --region $AWS_REGION iam put-role-policy --role-name $IAM_LAMBDA_ROLE_MANIFEST --policy-name $IAM_POLICY_DDB_READ_ACCESS --policy-document file://../config/ddb-read-access-policy.json 16 | 17 | echo "Adding policy $IAM_POLICY_LAMBDA_LOGS to role $IAM_LAMBDA_ROLE_MANIFEST" 18 | aws $AWS_FLAGS_JSON --region $AWS_REGION iam put-role-policy --role-name $IAM_LAMBDA_ROLE_MANIFEST --policy-name $IAM_POLICY_LAMBDA_LOGS --policy-document file://../config/cloudwatch-lambda-policy.json 19 | 20 | # Get role ARN 21 | ARN_IAM_LAMBDA_ROLE_MANIFEST=$(aws $AWS_FLAGS_TEXT iam get-role --role-name $IAM_LAMBDA_ROLE_MANIFEST --query 'Role.Arn') 22 | 23 | echo "Creating lambda $LAMBDA_MANIFEST_NAME (ARN: $ARN_IAM_LAMBDA_ROLE_MANIFEST) pointing it to DDB ($DDB_CONFIG_TABLE_NAME, $DDB_CONFIG_TABLE_CHUNKS)" 24 | aws $AWS_FLAGS_JSON --region $AWS_REGION lambda create-function --function-name $LAMBDA_MANIFEST_NAME --runtime nodejs12.x --handler index.handler --timeout 180 --memory-size 10240 --role $ARN_IAM_LAMBDA_ROLE_MANIFEST --zip-file "fileb://emptyLambda/index.zip" --environment "Variables={DDB_CONFIG_TABLE_NAME=$DDB_CONFIG_TABLE_NAME,DDB_CONFIG_TABLE_CHUNKS=$DDB_CONFIG_TABLE_CHUNKS}" 25 | -------------------------------------------------------------------------------- /scripts/create-rest-api.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Import variables 4 | source base.sh 5 | 6 | # exit when any command fails 7 | set -e 8 | 9 | # Get arn of lambda manifest function 10 | ARN_LAMBDA_MANIFEST=$(aws $AWS_FLAGS_TEXT --region $AWS_REGION lambda get-function --function-name $LAMBDA_MANIFEST_NAME --query 'Configuration.FunctionArn') 11 | 12 | # Replacements 13 | SOURCE_FILE_API="../config/live-rest-api-REPLACE.txt" 14 | DEST_FILE_API="../config/live-rest-api.json" 15 | 16 | sed -e "s/<>/${AWS_REGION}/g" \ 17 | -e "s/<>/${ARN_LAMBDA_MANIFEST}/g" \ 18 | -e "s/<>/${AWS_APIGATEWAY_NAME}/g" \ 19 | $SOURCE_FILE_API > $DEST_FILE_API 20 | 21 | # Create rest API by importing swagger definition 22 | echo "Import swagger API definition to API Gateway on $AWS_REGION" 23 | aws $AWS_FLAGS_JSON --cli-binary-format raw-in-base64-out --region $AWS_REGION apigateway import-rest-api --parameters "endpointConfigurationTypes=REGIONAL,basepath=ignore" --body file://$DEST_FILE_API 24 | 25 | # Remove replaced file 26 | rm $DEST_FILE_API 27 | 28 | # Get API data 29 | API_ID=$(aws $AWS_FLAGS_TEXT --region $AWS_REGION apigateway get-rest-apis --query "items[?name=='$AWS_APIGATEWAY_NAME'].id") 30 | AWS_ACCOUNT_ID=$(aws $AWS_FLAGS_TEXT --region $AWS_REGION sts get-caller-identity --query 'Account') 31 | 32 | # Grant permissions to API Gateway to call manifest lambda 33 | echo "Grant permissions to API $AWS_APIGATEWAY_NAME (API: $API_ID, AWS ACC ID: $AWS_ACCOUNT_ID) to call manifest lambda" 34 | aws $AWS_FLAGS_JSON --region $AWS_REGION lambda add-permission --function-name $LAMBDA_MANIFEST_NAME --statement-id $AWS_APIGATEWAY_NAME-apigateway-to-manifest --action lambda:InvokeFunction --principal apigateway.amazonaws.com --source-arn "arn:aws:execute-api:$AWS_REGION:$AWS_ACCOUNT_ID:$API_ID/*/GET/video/*/manifest.m3u8" 35 | aws $AWS_FLAGS_JSON --region $AWS_REGION lambda add-permission --function-name $LAMBDA_MANIFEST_NAME --statement-id $AWS_APIGATEWAY_NAME-apigateway-to-chunklist --action lambda:InvokeFunction --principal apigateway.amazonaws.com --source-arn "arn:aws:execute-api:$AWS_REGION:$AWS_ACCOUNT_ID:$API_ID/*/GET/video/*/*/chunklist.m3u8" 36 | 37 | # Deploy API & activate cache 38 | echo "Deploying API $AWS_APIGATEWAY_NAME (API: $API_ID), to stage prod" 39 | aws $AWS_FLAGS_JSON --region $AWS_REGION apigateway create-deployment --cache-cluster-enabled --cache-cluster-size 0.5 --rest-api-id $API_ID --stage-name prod 40 | 41 | # Overwrite cache for all methods and set = 1s 42 | echo "Activate cache to 1s for $AWS_APIGATEWAY_NAME (API: $API_ID) in stage prod" 43 | aws $AWS_FLAGS_JSON --region $AWS_REGION apigateway update-stage --rest-api-id $API_ID --stage-name prod --patch-operations "op=replace,path=/*/*/caching/ttlInSeconds,value=1" -------------------------------------------------------------------------------- /scripts/create-s3-bucket.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Import variables 4 | source base.sh 5 | 6 | # exit when any command fails 7 | set -e 8 | 9 | # Check if bucket exists 10 | if aws $AWS_FLAGS_JSON s3api head-bucket --bucket "$S3_BUCKET_NAME" >/dev/null; then 11 | echo "Skipping creation, bucket $S3_BUCKET_NAME already exists" 12 | else 13 | echo "Creating S3 bucket $S3_BUCKET_NAME in $AWS_REGION" 14 | aws $AWS_FLAGS_JSON --region $AWS_REGION s3 mb "s3://$S3_BUCKET_NAME" --region $AWS_REGION 15 | fi 16 | 17 | echo "Setting S3 bucket lifecycle" 18 | aws $AWS_FLAGS_JSON --region $AWS_REGION s3api put-bucket-lifecycle-configuration --bucket $S3_BUCKET_NAME --lifecycle-configuration file://../config/s3-lifecycle.json 19 | 20 | echo "Blocking public access" 21 | aws $AWS_FLAGS_JSON --region $AWS_REGION s3api put-public-access-block --bucket $S3_BUCKET_NAME --public-access-block-configuration file://../config/s3-public-access.json 22 | 23 | echo "Setting CORS policy" 24 | aws $AWS_FLAGS_JSON --region $AWS_REGION s3api put-bucket-cors --bucket $S3_BUCKET_NAME --cors-configuration file://../config/s3-cors.json -------------------------------------------------------------------------------- /scripts/create-s3-full-access-for-ec2.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Import variables 4 | source base.sh 5 | 6 | # exit when any command fails 7 | set -e 8 | 9 | # Create role 10 | echo "Creating role $IAM_EC2_ROLE_S3_FULL_ACCESS in $AWS_REGION" 11 | aws $AWS_FLAGS_JSON --region $AWS_REGION iam create-role --role-name $IAM_EC2_ROLE_S3_FULL_ACCESS --assume-role-policy-document file://../config/ec2-role-trust-policy.json 12 | 13 | # Add policy to role 14 | echo "Adding policy $IAM_POLICY_S3_FULL_ACCESS to role $IAM_EC2_ROLE_S3_FULL_ACCESS" 15 | aws $AWS_FLAGS_JSON --region $AWS_REGION iam put-role-policy --role-name $IAM_EC2_ROLE_S3_FULL_ACCESS --policy-name $IAM_POLICY_S3_FULL_ACCESS --policy-document file://../config/s3-full-access-policy.json 16 | 17 | # Create instance profile 18 | echo "Creating instance profile $IAM_INSTANCE_PROFILE_S3_FULL_ACCESS" 19 | aws $AWS_FLAGS_JSON --region $AWS_REGION iam create-instance-profile --instance-profile-name $IAM_INSTANCE_PROFILE_S3_FULL_ACCESS 20 | 21 | # Attaching role to instance profile 22 | echo "Attaching role $IAM_EC2_ROLE_S3_FULL_ACCESS to instance profile $IAM_INSTANCE_PROFILE_S3_FULL_ACCESS" 23 | aws $AWS_FLAGS_JSON --region $AWS_REGION iam add-role-to-instance-profile --instance-profile-name $IAM_INSTANCE_PROFILE_S3_FULL_ACCESS --role-name $IAM_EC2_ROLE_S3_FULL_ACCESS -------------------------------------------------------------------------------- /scripts/create-trancoder-lambda.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Import variables 4 | source base.sh 5 | 6 | # exit when any command fails 7 | set -e 8 | 9 | # Create role 10 | echo "Creating role $IAM_LAMBDA_ROLE_CHUNK_TRANSCODER in $AWS_REGION" 11 | aws $AWS_FLAGS_JSON --region $AWS_REGION iam create-role --role-name $IAM_LAMBDA_ROLE_CHUNK_TRANSCODER --assume-role-policy-document file://../config/lambda-role-trust-policy.json 12 | 13 | # Add policies to role 14 | echo "Adding policy $IAM_POLICY_S3_FULL_ACCESS to role $IAM_LAMBDA_ROLE_CHUNK_TRANSCODER" 15 | aws $AWS_FLAGS_JSON --region $AWS_REGION iam put-role-policy --role-name $IAM_LAMBDA_ROLE_CHUNK_TRANSCODER --policy-name $IAM_POLICY_S3_FULL_ACCESS --policy-document file://../config/s3-full-access-policy.json 16 | 17 | echo "Adding policy $IAM_POLICY_DDB_FULL_ACCESS to role $IAM_LAMBDA_ROLE_CHUNK_TRANSCODER" 18 | aws $AWS_FLAGS_JSON --region $AWS_REGION iam put-role-policy --role-name $IAM_LAMBDA_ROLE_CHUNK_TRANSCODER --policy-name $IAM_POLICY_DDB_FULL_ACCESS --policy-document file://../config/ddb-full-access-policy.json 19 | 20 | echo "Adding policy $IAM_POLICY_LAMBDA_LOGS to role $IAM_LAMBDA_ROLE_CHUNK_TRANSCODER" 21 | aws $AWS_FLAGS_JSON --region $AWS_REGION iam put-role-policy --role-name $IAM_LAMBDA_ROLE_CHUNK_TRANSCODER --policy-name $IAM_POLICY_LAMBDA_LOGS --policy-document file://../config/cloudwatch-lambda-policy.json 22 | 23 | # Get role ARN 24 | ARN_IAM_LAMBDA_ROLE_CHUNK_TRANSCODER=$(aws $AWS_FLAGS_TEXT iam get-role --role-name $IAM_LAMBDA_ROLE_CHUNK_TRANSCODER --query 'Role.Arn') 25 | 26 | echo "Creating lambda $LAMBDA_CHUNK_TRANSCODER_NAME (ARN: $ARN_IAM_LAMBDA_ROLE_CHUNK_TRANSCODER) pointing it to DDB ($DDB_CONFIG_TABLE_NAME, $DDB_CONFIG_TABLE_CHUNKS)" 27 | aws $AWS_FLAGS_JSON --region $AWS_REGION lambda create-function --function-name $LAMBDA_CHUNK_TRANSCODER_NAME --runtime nodejs12.x --handler index.handler --timeout 180 --memory-size 10240 --role $ARN_IAM_LAMBDA_ROLE_CHUNK_TRANSCODER --zip-file "fileb://emptyLambda/index.zip" --environment "Variables={DDB_CONFIG_TABLE_NAME=$DDB_CONFIG_TABLE_NAME,DDB_CONFIG_TABLE_CHUNKS=$DDB_CONFIG_TABLE_CHUNKS}" 28 | -------------------------------------------------------------------------------- /scripts/create-transcode-trigger.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Import variables 4 | source base.sh 5 | 6 | # exit when any command fails 7 | set -e 8 | 9 | # Create role 10 | echo "Adding permission to S3 ($S3_BUCKET_NAME) to invoke $LAMBDA_CHUNK_TRANSCODER_NAME lambda" 11 | aws $AWS_FLAGS_JSON --region $AWS_REGION lambda add-permission --function-name $LAMBDA_CHUNK_TRANSCODER_NAME --principal s3.amazonaws.com --statement-id s3invoke --action "lambda:InvokeFunction" --source-arn arn:aws:s3:::$S3_BUCKET_NAME 12 | 13 | ARN_LAMBDA_CHUNK_TRANSCODER=$(aws $AWS_FLAGS_TEXT --region $AWS_REGION lambda get-function --function-name $LAMBDA_CHUNK_TRANSCODER_NAME --query 'Configuration.FunctionArn') 14 | 15 | SOURCE_FILE_TRIGGER="../config/s3-lambda-trigger-REPLACE.txt" 16 | DEST_FILE_TRIGGER="../config/s3-lambda-trigger.json" 17 | sed "s/<>/${ARN_LAMBDA_CHUNK_TRANSCODER}/g" $SOURCE_FILE_TRIGGER > $DEST_FILE_TRIGGER 18 | 19 | echo "Creating file $DEST_FILE_TRIGGER from $SOURCE_FILE_TRIGGER (ARN: $ARN_LAMBDA_CHUNK_TRANSCODER)" 20 | aws $AWS_FLAGS_JSON --region $AWS_REGION s3api put-bucket-notification-configuration --bucket $S3_BUCKET_NAME --notification-configuration file://$DEST_FILE_TRIGGER 21 | 22 | # Remove replaced file 23 | rm $DEST_FILE_TRIGGER -------------------------------------------------------------------------------- /scripts/emptyLambda/index.js: -------------------------------------------------------------------------------- 1 | exports.handler = (event, context, callback) => { 2 | console.log('This is an empty lambda, you need to upload some code!'); 3 | callback(null, 'Lambda complete!'); 4 | }; 5 | -------------------------------------------------------------------------------- /scripts/emptyLambda/index.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jordicenzano/serverless-distributed-live-platform/6bbfc5d520d9a0e874beb9c370a670097ca626ec/scripts/emptyLambda/index.zip -------------------------------------------------------------------------------- /scripts/get-api-cdn-prepend.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Import variables 4 | source base.sh 5 | 6 | # exit when any command fails 7 | set -e 8 | 9 | # Get API data 10 | API_ID=$(aws $AWS_FLAGS_TEXT --region $AWS_REGION apigateway get-rest-apis --query "items[?name=='$AWS_APIGATEWAY_NAME'].id") 11 | 12 | # Get api prepend from prod and add /video 13 | echo "The API CDN prepend is: https://${API_ID}.execute-api.${AWS_REGION}.amazonaws.com/prod/video" -------------------------------------------------------------------------------- /scripts/populate-ddb.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Import variables 4 | source base.sh 5 | 6 | # exit when any command fails 7 | set -e 8 | 9 | echo "Getting CDN dist ARN from tag (Name)" 10 | CF_DIST_ARN=$(aws $AWS_FLAGS_TEXT resourcegroupstaggingapi get-resources --tag-filters Key=Name,Values=joc-live-dist-transcoder-cloudfront-media --query 'ResourceTagMappingList[0].ResourceARN') 11 | 12 | # Get item after last / 13 | CF_ID=${CF_DIST_ARN##*/} 14 | 15 | echo "Getting CDN domain name for ID: $CF_ID (Arn: $CF_DIST_ARN)" 16 | MEDIA_CDN_DOMAIN_NAME=$(aws $AWS_FLAGS_TEXT cloudfront get-distribution --id $CF_ID --query 'Distribution.DomainName') 17 | 18 | # Replacements 19 | SOURCE_FILE_CONFIG="../config/system-config-5renditions-1080p-REPLACE.txt" 20 | DEST_FILE_CONFIG="../config/system-config-5renditions-1080p.json" 21 | 22 | sed -e "s/<>/${MEDIA_CDN_DOMAIN_NAME}/g" $SOURCE_FILE_CONFIG > $DEST_FILE_CONFIG 23 | 24 | echo "Populate DDB with configs value" 25 | aws $AWS_FLAGS_JSON --region $AWS_REGION dynamodb put-item --table-name $DDB_CONFIG_TABLE_NAME --item file://$DEST_FILE_CONFIG 26 | 27 | # Remove replaced file 28 | rm $DEST_FILE_CONFIG 29 | --------------------------------------------------------------------------------