├── .github └── workflows │ └── github-backup.yml ├── .gitignore ├── .gitmodules ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── benchmark └── benchmark-aws-ffmpeg.xlsx ├── bootstrap.sh ├── composer.json ├── composer.lock ├── input_samples ├── input_image1.json ├── input_thumbs1.json ├── input_thumbs1_http_input.json ├── input_video1.json ├── input_video1_http_input.json ├── input_videoHLS.json ├── input_video_custom_cmd.json └── input_video_custom_cmd_http_input.json ├── src ├── activities │ ├── BasicActivity.php │ ├── TranscodeAssetActivity.php │ ├── ValidateAssetActivity.php │ └── transcoders │ │ ├── AudioTranscoder.php │ │ ├── BasicTranscoder.php │ │ ├── DocumentTranscoder.php │ │ ├── ImageTranscoder.php │ │ └── VideoTranscoder.php ├── scripts │ ├── getFromS3.php │ └── putInS3.php └── utils │ ├── CommandExecuter.php │ └── S3Utils.php └── state_machines ├── SATranscodeAssets.json └── SAValidateTranscodeAssets.json /.github/workflows/github-backup.yml: -------------------------------------------------------------------------------- 1 | name: Mirror repo to S3 2 | on: 3 | push: 4 | branches: 5 | - develop 6 | jobs: 7 | s3Backup: 8 | if: github.repository_owner == 'bfansports' 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: S3 Backup 13 | uses: peter-evans/s3-backup@v1 14 | env: 15 | ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY }} 16 | SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_KEY }} 17 | MIRROR_TARGET: bfansports-github-backup/CloudTranscode 18 | with: 19 | args: --overwrite --remove 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore the local config 2 | .env.dev 3 | vendor/* 4 | 5 | # Vagrant 6 | .vagrant 7 | 8 | # Ignore vendor tree 9 | composer.phar 10 | 11 | # Ignore any build output 12 | build/* 13 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "presets"] 2 | path = presets 3 | url = https://github.com/sportarchive/CloudTranscode-FFMpeg-presets.git 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Fork the project, push your branch to your fork, and submit a Pull Request on GiHub. 2 | 3 | We're looking for more `state_machines` samples that you created on AWS Step Functions or for more activitiy implementations. 4 | 5 | Thanks for contributing to this project. 6 | 7 | @koxon 8 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM 501431420968.dkr.ecr.eu-west-1.amazonaws.com/sportarc/cloudtranscode-base:4.2 2 | MAINTAINER bFAN Sports 3 | 4 | COPY . /usr/src/cloudtranscode 5 | WORKDIR /usr/src/cloudtranscode 6 | 7 | RUN DEBIAN_FRONTEND=noninteractive TERM=screen \ 8 | apt-get update \ 9 | && apt-get install -y git \ 10 | && make \ 11 | && apt-get purge -y git \ 12 | && apt-get autoremove -y 13 | 14 | ENTRYPOINT ["/usr/src/cloudtranscode/bootstrap.sh"] 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | COMPOSER = ./composer.phar 2 | COMPOSER_CONF = ./composer.json 3 | 4 | .PHONY: all vendor 5 | 6 | all: vendor 7 | 8 | $(COMPOSER): 9 | curl -sS https://getcomposer.org/installer | php 10 | 11 | vendor: $(COMPOSER) $(COMPOSER_CONF) 12 | $(COMPOSER) self-update 13 | $(COMPOSER) install --ignore-platform-reqs --no-interaction --optimize-autoloader --prefer-dist 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/sportarchive/CloudTranscode?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) 2 | [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/sportarchive/CloudTranscode/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/sportarchive/CloudTranscode/?branch=master) 3 | 4 | ### Updates 2020/05/09 5 | Update to FFMpeg 4.2 6 | 7 | # What is Cloud Transcode? 8 | Cloud Transcode (CT) is your own distributed transcoding stack. With it you can transcode media files in a distributed way, at scale. 9 | 10 | ## Goal 11 | The goal of this project is to create an open source, scalable and cheap distributed transcoding platform where users have complete control over performance and cost. 12 | 13 | We started with video transcoding as it is the most costly, but the goal is to transcode any type media files (audio, documents and images). We use FFMpeg for video transcoding. CT also image transcoding using ImageMagic. 14 | 15 | Today's commercial solutions for video transcoding are very expensive for large volumes. With this solution you can transcode large quantity of files at the pace you want, thus controling your cost. 16 | 17 | ## Benefits 18 | With Cloud Transcode, you control: scale, speed and cost. You can run everything locally if you want, no Cloud instance required. Or you can deploy on AWS EC2, Beanstalk or Docker containers. 19 | 20 | Your workers only need an Internet connection to use the required Amazon services: SFN (AWS Step Functions) and S3. It means that you can have a local, hybrid or full cloud setup. It's up to you. 21 | 22 | ## Activity supported 23 | 24 | List of actions this stack allow you to do very quickly and at scale. 25 | 26 | - **Custom FFMpeg command**: Run and distribute your own `ffmpeg` commands 27 | - **Image to Image transcoding**: Run and sitribute your own ImageMagic `convert` commands 28 | - **Validate/Probe Asset**: Run `ffprobe` to get the `mime type` of an asset 29 | - **Transcode from HTTP**: Pull files from HTTP/S and transcode them on the fly at scale. Result files are put into AWS S3. 30 | - **Video to Video transcoding**: JSON input: One video IN, many videos OUT. Any formats and codecs supported by your ffmpeg. 31 | - **Video to Thumbnails transcoding**: JSON input: Snapshot at certain time in video or intervals snapshot every N seconds. Keep image ratio. 32 | - **Watermark integration in video**: JSON input: Take image IN and position a watermark on top of the video. Custom position and transparency. Keep image ratio. 33 | 34 | 35 | # How it works? 36 | 37 | Cloud Transcode is a set of "activities" that are standalone scripts implementing the `CpeActivity` class located in the CloudProcessingEngine-SDK: 38 | https://packagist.org/packages/sportarchive/cloud-processing-engine-sdk 39 | 40 | Those Activities listen to the Amazon SFN (Step functions) service for incoming tasks to process (You need an Amazon AWS account, yes). One activity will process one type of Tasks. 41 | 42 | Tasks and Workflows (aka `State Machine`) are defined in the AWS SFN console, and are identified by their AWS ARNs (AWS resources identifier). You can then start `N` activity workers that will start listening for incoming jobs and execute them. 43 | 44 | You can scale your infrastructure in AWS based on your volume, capacity, cost, resources, etc. 45 | You can run those SFN Activities on Docker, which is recommended. A Dockerfile is provided for you. 46 | But you can run on anything and anywhere. 47 | 48 | Your client applications can initiate new SFN workflows using the AWS SDK of your choice. The client apps will pass JSON input date to AWS SFN.
49 | SFN will then pass this input to your activities, which will then return a JSON output. This output can be passed on to the next activities. 50 | 51 | Thanks to the `CloudProcessingEngine-SDK` you can build your own workflow and call any activities you want. You can implement your own activities as well. 52 | 53 | Cloud Transcode could use help on the following Activities if you are interested in participating: 54 | 55 | - Document transcoding: DOC to PDF for example 56 | - Audio manipulation: Maybe this can be already done by FFMpeg. Never tested if FFmpeg supports it or if there is a better tool for Audio. 57 | - Other ideas? 58 | 59 | # Getting Started 60 | 61 | ## AWS Account 62 | 63 | You need one. You will use the following AWS services: 64 | S3, SFN, IAM, ECS (Docker cluster - Ideal), EC2, and several more. 65 | 66 | The ideal setup in on AWS ECS which provides EC2 instances management and Docker container management. 67 | You can use our Dockerfile to add your own configuration files to the final Docker image. 68 | Create a ECS Activity, and tell it to run your image. You can then scale the cluster and auto adjust. 69 | 70 | ## State Machine 71 | 72 | You must create a State Machine workflow in the AWS Step Function console to make things work. 73 | 74 | In the folder `state_machines` of the project, you will find a basic transcoding workflow for SFN. It validates the input and then processes ALL the outputs you want in one activity.
75 | In sequence, this workflow calls: 76 | 77 | - 1 -> ValidateAssetActivity 78 | - N -> TranscodeAssetActivity 79 | 80 | One TranscodeAssetActivity worker processes all outputs wanted, in sequence, not in parallel. 81 | 82 | > *Note:* I couldn't make SFN transform on the fly the input data given to the activities. 83 | > The array of "output files wanted" could have been split and one activity could be started for each output in the array, thus allowing parallel transcoding. 84 | > To achieve parallel transcoding, you need to have an intermediate activity that splits the input and initiate new workflows, each with only one output wanted. 85 | 86 | ## Run Activities 87 | 88 | Activities are standalone scripts writen in PHP (legacy reasons, but it's clean!) that can be started in command line. 89 | 90 | ``` 91 | bash $> ./src/activities/ValidateAssetActivity.php -A arn:aws:states:eu-west-1:XXXXXXXXXXXX:activity:ValidateAsset 92 | bash $> ./src/activities/TranscodeAssetActivity.php -A arn:aws:states:eu-west-1:XXXXXXXXXXXX:activity:TranscodeAsset 93 | ``` 94 | 95 | Or using Docker 96 | 97 | ``` 98 | $> sudo docker run 501431420968.dkr.ecr.eu-west-1.amazonaws.com/sportarc/cloudtranscode:4.2 ValidateAssetActivity -A arn:aws:states:eu-west-1:XXXXXXXXXXXX:activity:ValidateAsset 99 | $> sudo docker run 501431420968.dkr.ecr.eu-west-1.amazonaws.com/sportarc/cloudtranscode:4.2 TranscodeAssetActivity -A arn:aws:states:eu-west-1:XXXXXXXXXXXX:activity:TranscodeAsset 100 | ``` 101 | 102 | Using these commands, you can start an activity worker that processes one type of activity. In these cases `ValidateAssetActivity` and `TranscodeAssetActivity` 103 | 104 | ## Integrate with your client app 105 | 106 | Your Cloud Transcode workers (or custom workers) will do the work as wanted but your client applications that initiated the workflow will not have any idea of what is going on. 107 | 108 | In order to hook your client applications with Cloud Transcode, you must implement a PHP Interface. 109 | 110 | Your Interface will contain all the callback methods that will be called when events occur in your CT workflow: 111 | 112 | - onStart 113 | - onHeartbeat 114 | - onFail 115 | - onSuccess 116 | - onTranscodeDone 117 | 118 | You must implement the `CpeClientInterface.php` interface located in the `CloudProcessingEngine-SDK` project: 119 | 120 | - Composer: https://packagist.org/packages/sportarchive/cloud-processing-engine-sdk 121 | - Github: https://github.com/sportarchive/CloudProcessingEngine-SDK 122 | 123 | In order to pass this class to your Activity worker, you have to provide its location in command line using the [-C ] option. 124 | 125 | That means that if you use Docker, you must create your own Docker image based on the one provided in the project, which will contain your custom classes in it. 126 | 127 | A Dockerfile like this for example: 128 | 129 | 130 | ``` Dockerfile 131 | FROM 501431420968.dkr.ecr.eu-west-1.amazonaws.com/sportarc/cloudtranscode:4.2 132 | MAINTAINER bFAN Sports 133 | 134 | COPY clientInterfaces /usr/src/clientInterfaces 135 | ``` 136 | 137 | Just create a new folder, put the Dockerfile above in it and clone the CloudTranscode repository in it too. 138 | Then build your own image as follow: `sudo docker build -t 501431420968.dkr.ecr.eu-west-1.amazonaws.com/sportarc/cloudtranscode-prod .` 139 | 140 | Then you can start your workers like this: 141 | 142 | ```shell 143 | $> sudo docker run 501431420968.dkr.ecr.eu-west-1.amazonaws.com/sportarc/cloudtranscode-prod:4.2 ValidateAssetActivity -A arn:aws:states:eu-west-1:XXXXXXXXXXXX:activity:ValidateAsset -C /usr/src/clientInterfaces/ValidateAssetClientInterfaces.php 144 | $> sudo docker run 501431420968.dkr.ecr.eu-west-1.amazonaws.com/sportarc/cloudtranscode-prod:4.2 TranscodeAssetActivity -A arn:aws:states:eu-west-1:XXXXXXXXXXXX:activity:TranscodeAllOutputAssets -C /usr/src/clientInterfaces/TranscodeAllOutputAssetsClientInterfaces.php 145 | $> sudo docker run 501431420968.dkr.ecr.eu-west-1.amazonaws.com/sportarc/cloudtranscode-prod:4.2 TranscodeAssetActivity -A arn:aws:states:eu-west-1:XXXXXXXXXXXX:activity:TranscodeImageAsset -C /usr/src/clientInterfaces/TranscodeImagesAssetsClientInterfaces.php 146 | $> sudo docker run 501431420968.dkr.ecr.eu-west-1.amazonaws.com/sportarc/cloudtranscode-prod:4.2 TranscodeAssetActivity -A arn:aws:states:eu-west-1:XXXXXXXXXXXX:activity:OnDemandTranscodeAsset -C /usr/src/clientInterfaces/OnDemandTranscodeAssetClientInterfaces.php 147 | ``` 148 | 149 | As you can see, you can create many SFN tasks. Each task will execute the same activity code, but they are connected to different client applications using different Interface classes. 150 | This way you can have several sets of workers for all your workflows and client applications. 151 | Each worker will be processing only certain tasks. They are hooked to different client applications using the custom interface classes. 152 | 153 | ## Input format 154 | 155 | In the `input_sample` folder, we provide input samples that you can edit to match your setup. 156 | 157 | The main idea is: 158 | 159 | - One `input` section which describes what must be processed 160 | - One `output` section which contains a list of wanted output. Each output is describe by a JSON and specifies the work to be done and where the resulting file should go. 161 | 162 | A Simple example that takes a `.mp4` as input and generate two thumbnails and a proxy video using a FFmpeg template: 163 | 164 | ``` json 165 | { 166 | "input_asset": { 167 | "type": "VIDEO", 168 | "bucket": "cloudtranscode-eu-dev", 169 | "file": "/input/video1.mp4" 170 | }, 171 | "output_assets": [ 172 | { 173 | "type": "THUMB", 174 | "mode": "snapshot", 175 | "bucket": "cloudtranscode-eu-dev", 176 | "path": "/output/", 177 | "file": "thumbnail_sd.jpg", 178 | "s3_rrs": true, 179 | "s3_encrypt": true, 180 | "size": "-1:159", 181 | "snapshot_sec": 5 182 | }, 183 | { 184 | "type": "THUMB", 185 | "mode": "snapshot", 186 | "bucket": "cloudtranscode-eu-dev", 187 | "path": "/output/", 188 | "file": "thumbnail_hd.jpg", 189 | "s3_rrs": true, 190 | "s3_encrypt": true, 191 | "size": "-1:720", 192 | "snapshot_sec": 5 193 | }, 194 | { 195 | "type": "VIDEO", 196 | "bucket": "cloudtranscode-eu-dev", 197 | "path": "/output/", 198 | "file": "video1.mp4", 199 | "s3_rrs": true, 200 | "s3_encrypt": true, 201 | "keep_ratio": false, 202 | "no_enlarge": false, 203 | "preset": "360p-4.3-generic", 204 | "watermark": { 205 | "bucket": "cloudtranscode-eu-dev", 206 | "file": "/no-text-96px.png", 207 | "size": "96:96", 208 | "opacity": 0.2, 209 | "x": -20, 210 | "y": -20 211 | } 212 | } 213 | ] 214 | } 215 | 216 | ``` 217 | 218 | You can also submit custom FFmpeg commands, or specify as many output as you want here. 219 | 220 | > *Note:* As mentioned above, those outputs are processed in sequence by the same worker, NOT in parallel. 221 | 222 | # Contributing 223 | 224 | Feel free to send us your Pull Requests. 225 | 226 | Thanks for contributing ! 227 | 228 | # FFmpeg 229 | 230 | CloudTranscode uses FFmpeg 4.2 231 | 232 | The CloudTranscode Docker image is based on two other images: 233 | 234 | - https://hub.docker.com/r/sportarc/ffmpeg/ 235 | - https://hub.docker.com/r/sportarc/cloudtranscode-base/ 236 | 237 | 238 | # FFMpeg performance benchmark on Amazon EC2 239 | 240 | *This is already a little old and needs update with the latest AWS instances* 241 | 242 | Download the spreadsheet to compare the different Amazon EC2 instances cost and performances running FFMpeg: 243 | https://github.com/sportarchive/CloudTranscode/blob/master/benchmark/benchmark-aws-ffmpeg.xlsx 244 | -------------------------------------------------------------------------------- /benchmark/benchmark-aws-ffmpeg.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bfansports/CloudTranscode/40863958fffaeec91b7f4721ed85020539140e41/benchmark/benchmark-aws-ffmpeg.xlsx -------------------------------------------------------------------------------- /bootstrap.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -eu -o pipefail 4 | 5 | exec php "/usr/src/cloudtranscode/src/activities/$1.php" \ 6 | "${@:2}" 7 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "require": { 3 | "aws/aws-sdk-php": "3.*", 4 | "justinrainbow/json-schema": "~1.3", 5 | "bfansports/cloud-processing-engine-sdk": "dev-master" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /composer.lock: -------------------------------------------------------------------------------- 1 | { 2 | "_readme": [ 3 | "This file locks the dependencies of your project to a known state", 4 | "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", 5 | "This file is @generated automatically" 6 | ], 7 | "content-hash": "5fb9fa69f4b58c74361bbfbf68869ccd", 8 | "packages": [ 9 | { 10 | "name": "aws/aws-sdk-php", 11 | "version": "3.31.1", 12 | "source": { 13 | "type": "git", 14 | "url": "https://github.com/aws/aws-sdk-php.git", 15 | "reference": "551865464a2779b9038aa871094a24bb9e254e24" 16 | }, 17 | "dist": { 18 | "type": "zip", 19 | "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/551865464a2779b9038aa871094a24bb9e254e24", 20 | "reference": "551865464a2779b9038aa871094a24bb9e254e24", 21 | "shasum": "" 22 | }, 23 | "require": { 24 | "guzzlehttp/guzzle": "^5.3.1|^6.2.1", 25 | "guzzlehttp/promises": "~1.0", 26 | "guzzlehttp/psr7": "^1.4.1", 27 | "mtdowling/jmespath.php": "~2.2", 28 | "php": ">=5.5" 29 | }, 30 | "require-dev": { 31 | "andrewsville/php-token-reflection": "^1.4", 32 | "aws/aws-php-sns-message-validator": "~1.0", 33 | "behat/behat": "~3.0", 34 | "doctrine/cache": "~1.4", 35 | "ext-dom": "*", 36 | "ext-json": "*", 37 | "ext-openssl": "*", 38 | "ext-pcre": "*", 39 | "ext-simplexml": "*", 40 | "ext-spl": "*", 41 | "nette/neon": "^2.3", 42 | "phpunit/phpunit": "^4.8.35|^5.4.0", 43 | "psr/cache": "^1.0" 44 | }, 45 | "suggest": { 46 | "aws/aws-php-sns-message-validator": "To validate incoming SNS notifications", 47 | "doctrine/cache": "To use the DoctrineCacheAdapter", 48 | "ext-curl": "To send requests using cURL", 49 | "ext-openssl": "Allows working with CloudFront private distributions and verifying received SNS messages" 50 | }, 51 | "type": "library", 52 | "extra": { 53 | "branch-alias": { 54 | "dev-master": "3.0-dev" 55 | } 56 | }, 57 | "autoload": { 58 | "psr-4": { 59 | "Aws\\": "src/" 60 | }, 61 | "files": [ 62 | "src/functions.php" 63 | ] 64 | }, 65 | "notification-url": "https://packagist.org/downloads/", 66 | "license": [ 67 | "Apache-2.0" 68 | ], 69 | "authors": [ 70 | { 71 | "name": "Amazon Web Services", 72 | "homepage": "http://aws.amazon.com" 73 | } 74 | ], 75 | "description": "AWS SDK for PHP - Use Amazon Web Services in your PHP project", 76 | "homepage": "http://aws.amazon.com/sdkforphp", 77 | "keywords": [ 78 | "amazon", 79 | "aws", 80 | "cloud", 81 | "dynamodb", 82 | "ec2", 83 | "glacier", 84 | "s3", 85 | "sdk" 86 | ], 87 | "time": "2017-07-05T17:26:26+00:00" 88 | }, 89 | { 90 | "name": "bfansports/cloud-processing-engine-sdk", 91 | "version": "dev-master", 92 | "source": { 93 | "type": "git", 94 | "url": "https://github.com/bfansports/CloudProcessingEngine-SDK.git", 95 | "reference": "1a2f2501c6e31c30c34d0da15134b0f322a25a3b" 96 | }, 97 | "dist": { 98 | "type": "zip", 99 | "url": "https://api.github.com/repos/bfansports/CloudProcessingEngine-SDK/zipball/1a2f2501c6e31c30c34d0da15134b0f322a25a3b", 100 | "reference": "1a2f2501c6e31c30c34d0da15134b0f322a25a3b", 101 | "shasum": "" 102 | }, 103 | "require": { 104 | "aws/aws-sdk-php": "3.*", 105 | "php": ">=5.6" 106 | }, 107 | "require-dev": { 108 | "phpdocumentor/phpdocumentor": "2.*" 109 | }, 110 | "type": "library", 111 | "autoload": { 112 | "psr-0": { 113 | "SA": "src/" 114 | } 115 | }, 116 | "notification-url": "https://packagist.org/downloads/", 117 | "authors": [ 118 | { 119 | "name": "bFAN Sports", 120 | "email": "support@bfansports.com" 121 | } 122 | ], 123 | "description": "PHP SDK for the Cloud Processing Engine activities. Use this SDK to create your custom activities for the CloudTranscode project", 124 | "homepage": "https://github.com/bfansports/CloudProcessingEngine-SDK", 125 | "keywords": [ 126 | "Cloud Transcode" 127 | ], 128 | "time": "2017-07-06 16:38:58" 129 | }, 130 | { 131 | "name": "guzzlehttp/guzzle", 132 | "version": "6.3.0", 133 | "source": { 134 | "type": "git", 135 | "url": "https://github.com/guzzle/guzzle.git", 136 | "reference": "f4db5a78a5ea468d4831de7f0bf9d9415e348699" 137 | }, 138 | "dist": { 139 | "type": "zip", 140 | "url": "https://api.github.com/repos/guzzle/guzzle/zipball/f4db5a78a5ea468d4831de7f0bf9d9415e348699", 141 | "reference": "f4db5a78a5ea468d4831de7f0bf9d9415e348699", 142 | "shasum": "" 143 | }, 144 | "require": { 145 | "guzzlehttp/promises": "^1.0", 146 | "guzzlehttp/psr7": "^1.4", 147 | "php": ">=5.5" 148 | }, 149 | "require-dev": { 150 | "ext-curl": "*", 151 | "phpunit/phpunit": "^4.0 || ^5.0", 152 | "psr/log": "^1.0" 153 | }, 154 | "suggest": { 155 | "psr/log": "Required for using the Log middleware" 156 | }, 157 | "type": "library", 158 | "extra": { 159 | "branch-alias": { 160 | "dev-master": "6.2-dev" 161 | } 162 | }, 163 | "autoload": { 164 | "files": [ 165 | "src/functions_include.php" 166 | ], 167 | "psr-4": { 168 | "GuzzleHttp\\": "src/" 169 | } 170 | }, 171 | "notification-url": "https://packagist.org/downloads/", 172 | "license": [ 173 | "MIT" 174 | ], 175 | "authors": [ 176 | { 177 | "name": "Michael Dowling", 178 | "email": "mtdowling@gmail.com", 179 | "homepage": "https://github.com/mtdowling" 180 | } 181 | ], 182 | "description": "Guzzle is a PHP HTTP client library", 183 | "homepage": "http://guzzlephp.org/", 184 | "keywords": [ 185 | "client", 186 | "curl", 187 | "framework", 188 | "http", 189 | "http client", 190 | "rest", 191 | "web service" 192 | ], 193 | "time": "2017-06-22T18:50:49+00:00" 194 | }, 195 | { 196 | "name": "guzzlehttp/promises", 197 | "version": "v1.3.1", 198 | "source": { 199 | "type": "git", 200 | "url": "https://github.com/guzzle/promises.git", 201 | "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646" 202 | }, 203 | "dist": { 204 | "type": "zip", 205 | "url": "https://api.github.com/repos/guzzle/promises/zipball/a59da6cf61d80060647ff4d3eb2c03a2bc694646", 206 | "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646", 207 | "shasum": "" 208 | }, 209 | "require": { 210 | "php": ">=5.5.0" 211 | }, 212 | "require-dev": { 213 | "phpunit/phpunit": "^4.0" 214 | }, 215 | "type": "library", 216 | "extra": { 217 | "branch-alias": { 218 | "dev-master": "1.4-dev" 219 | } 220 | }, 221 | "autoload": { 222 | "psr-4": { 223 | "GuzzleHttp\\Promise\\": "src/" 224 | }, 225 | "files": [ 226 | "src/functions_include.php" 227 | ] 228 | }, 229 | "notification-url": "https://packagist.org/downloads/", 230 | "license": [ 231 | "MIT" 232 | ], 233 | "authors": [ 234 | { 235 | "name": "Michael Dowling", 236 | "email": "mtdowling@gmail.com", 237 | "homepage": "https://github.com/mtdowling" 238 | } 239 | ], 240 | "description": "Guzzle promises library", 241 | "keywords": [ 242 | "promise" 243 | ], 244 | "time": "2016-12-20T10:07:11+00:00" 245 | }, 246 | { 247 | "name": "guzzlehttp/psr7", 248 | "version": "1.4.2", 249 | "source": { 250 | "type": "git", 251 | "url": "https://github.com/guzzle/psr7.git", 252 | "reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c" 253 | }, 254 | "dist": { 255 | "type": "zip", 256 | "url": "https://api.github.com/repos/guzzle/psr7/zipball/f5b8a8512e2b58b0071a7280e39f14f72e05d87c", 257 | "reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c", 258 | "shasum": "" 259 | }, 260 | "require": { 261 | "php": ">=5.4.0", 262 | "psr/http-message": "~1.0" 263 | }, 264 | "provide": { 265 | "psr/http-message-implementation": "1.0" 266 | }, 267 | "require-dev": { 268 | "phpunit/phpunit": "~4.0" 269 | }, 270 | "type": "library", 271 | "extra": { 272 | "branch-alias": { 273 | "dev-master": "1.4-dev" 274 | } 275 | }, 276 | "autoload": { 277 | "psr-4": { 278 | "GuzzleHttp\\Psr7\\": "src/" 279 | }, 280 | "files": [ 281 | "src/functions_include.php" 282 | ] 283 | }, 284 | "notification-url": "https://packagist.org/downloads/", 285 | "license": [ 286 | "MIT" 287 | ], 288 | "authors": [ 289 | { 290 | "name": "Michael Dowling", 291 | "email": "mtdowling@gmail.com", 292 | "homepage": "https://github.com/mtdowling" 293 | }, 294 | { 295 | "name": "Tobias Schultze", 296 | "homepage": "https://github.com/Tobion" 297 | } 298 | ], 299 | "description": "PSR-7 message implementation that also provides common utility methods", 300 | "keywords": [ 301 | "http", 302 | "message", 303 | "request", 304 | "response", 305 | "stream", 306 | "uri", 307 | "url" 308 | ], 309 | "time": "2017-03-20T17:10:46+00:00" 310 | }, 311 | { 312 | "name": "justinrainbow/json-schema", 313 | "version": "1.6.1", 314 | "source": { 315 | "type": "git", 316 | "url": "https://github.com/justinrainbow/json-schema.git", 317 | "reference": "cc84765fb7317f6b07bd8ac78364747f95b86341" 318 | }, 319 | "dist": { 320 | "type": "zip", 321 | "url": "https://api.github.com/repos/justinrainbow/json-schema/zipball/cc84765fb7317f6b07bd8ac78364747f95b86341", 322 | "reference": "cc84765fb7317f6b07bd8ac78364747f95b86341", 323 | "shasum": "" 324 | }, 325 | "require": { 326 | "php": ">=5.3.29" 327 | }, 328 | "require-dev": { 329 | "json-schema/json-schema-test-suite": "1.1.0", 330 | "phpdocumentor/phpdocumentor": "~2", 331 | "phpunit/phpunit": "~3.7" 332 | }, 333 | "bin": [ 334 | "bin/validate-json" 335 | ], 336 | "type": "library", 337 | "extra": { 338 | "branch-alias": { 339 | "dev-master": "1.6.x-dev" 340 | } 341 | }, 342 | "autoload": { 343 | "psr-4": { 344 | "JsonSchema\\": "src/JsonSchema/" 345 | } 346 | }, 347 | "notification-url": "https://packagist.org/downloads/", 348 | "license": [ 349 | "BSD-3-Clause" 350 | ], 351 | "authors": [ 352 | { 353 | "name": "Bruno Prieto Reis", 354 | "email": "bruno.p.reis@gmail.com" 355 | }, 356 | { 357 | "name": "Justin Rainbow", 358 | "email": "justin.rainbow@gmail.com" 359 | }, 360 | { 361 | "name": "Igor Wiedler", 362 | "email": "igor@wiedler.ch" 363 | }, 364 | { 365 | "name": "Robert Schönthal", 366 | "email": "seroscho@googlemail.com" 367 | } 368 | ], 369 | "description": "A library to validate a json schema.", 370 | "homepage": "https://github.com/justinrainbow/json-schema", 371 | "keywords": [ 372 | "json", 373 | "schema" 374 | ], 375 | "time": "2016-01-25T15:43:01+00:00" 376 | }, 377 | { 378 | "name": "mtdowling/jmespath.php", 379 | "version": "2.4.0", 380 | "source": { 381 | "type": "git", 382 | "url": "https://github.com/jmespath/jmespath.php.git", 383 | "reference": "adcc9531682cf87dfda21e1fd5d0e7a41d292fac" 384 | }, 385 | "dist": { 386 | "type": "zip", 387 | "url": "https://api.github.com/repos/jmespath/jmespath.php/zipball/adcc9531682cf87dfda21e1fd5d0e7a41d292fac", 388 | "reference": "adcc9531682cf87dfda21e1fd5d0e7a41d292fac", 389 | "shasum": "" 390 | }, 391 | "require": { 392 | "php": ">=5.4.0" 393 | }, 394 | "require-dev": { 395 | "phpunit/phpunit": "~4.0" 396 | }, 397 | "bin": [ 398 | "bin/jp.php" 399 | ], 400 | "type": "library", 401 | "extra": { 402 | "branch-alias": { 403 | "dev-master": "2.0-dev" 404 | } 405 | }, 406 | "autoload": { 407 | "psr-4": { 408 | "JmesPath\\": "src/" 409 | }, 410 | "files": [ 411 | "src/JmesPath.php" 412 | ] 413 | }, 414 | "notification-url": "https://packagist.org/downloads/", 415 | "license": [ 416 | "MIT" 417 | ], 418 | "authors": [ 419 | { 420 | "name": "Michael Dowling", 421 | "email": "mtdowling@gmail.com", 422 | "homepage": "https://github.com/mtdowling" 423 | } 424 | ], 425 | "description": "Declaratively specify how to extract elements from a JSON document", 426 | "keywords": [ 427 | "json", 428 | "jsonpath" 429 | ], 430 | "time": "2016-12-03T22:08:25+00:00" 431 | }, 432 | { 433 | "name": "psr/http-message", 434 | "version": "1.0.1", 435 | "source": { 436 | "type": "git", 437 | "url": "https://github.com/php-fig/http-message.git", 438 | "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" 439 | }, 440 | "dist": { 441 | "type": "zip", 442 | "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", 443 | "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", 444 | "shasum": "" 445 | }, 446 | "require": { 447 | "php": ">=5.3.0" 448 | }, 449 | "type": "library", 450 | "extra": { 451 | "branch-alias": { 452 | "dev-master": "1.0.x-dev" 453 | } 454 | }, 455 | "autoload": { 456 | "psr-4": { 457 | "Psr\\Http\\Message\\": "src/" 458 | } 459 | }, 460 | "notification-url": "https://packagist.org/downloads/", 461 | "license": [ 462 | "MIT" 463 | ], 464 | "authors": [ 465 | { 466 | "name": "PHP-FIG", 467 | "homepage": "http://www.php-fig.org/" 468 | } 469 | ], 470 | "description": "Common interface for HTTP messages", 471 | "homepage": "https://github.com/php-fig/http-message", 472 | "keywords": [ 473 | "http", 474 | "http-message", 475 | "psr", 476 | "psr-7", 477 | "request", 478 | "response" 479 | ], 480 | "time": "2016-08-06T14:39:51+00:00" 481 | } 482 | ], 483 | "packages-dev": [], 484 | "aliases": [], 485 | "minimum-stability": "stable", 486 | "stability-flags": { 487 | "bfansports/cloud-processing-engine-sdk": 20 488 | }, 489 | "prefer-stable": false, 490 | "prefer-lowest": false, 491 | "platform": [], 492 | "platform-dev": [] 493 | } 494 | -------------------------------------------------------------------------------- /input_samples/input_image1.json: -------------------------------------------------------------------------------- 1 | { 2 | "input_asset": { 3 | "type": "IMAGE", 4 | "bucket": "cloudtranscode-eu-dev", 5 | "file": "/input/image.jpg" 6 | }, 7 | "output_assets": 8 | [ 9 | { 10 | "type": "IMAGE", 11 | "bucket": "cloudtranscode-eu-dev", 12 | "path": "/output/", 13 | "file": "image.*", 14 | "crop": "600x600+0+0", 15 | "quality": 70, 16 | "s3_rrs": true, 17 | "s3_encrypt": true 18 | } 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /input_samples/input_thumbs1.json: -------------------------------------------------------------------------------- 1 | { 2 | "input_asset": { 3 | "type": "VIDEO", 4 | "bucket": "cloudtranscode-dev", 5 | "file": "/input/video1.mp4" 6 | }, 7 | "output_asset": [ 8 | { 9 | "type": "THUMB", 10 | "mode": "snapshot", 11 | "bucket": "cloudtranscode-dev", 12 | "path": "/output/thumbs/", 13 | "file": "video1_thumb.jpg", 14 | "s3_rrs": true, 15 | "s3_encrypt": true, 16 | "size": "-1:159", 17 | "snapshot_sec": 5 18 | } 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /input_samples/input_thumbs1_http_input.json: -------------------------------------------------------------------------------- 1 | { 2 | "input_asset": { 3 | "type": "VIDEO", 4 | "http": "https://s3.amazonaws.com/cloudtranscode-dev/input/Andre+Johnson+mic%27d+up+uncensored.mp4" 5 | }, 6 | "output_asset": [ 7 | { 8 | "type": "THUMB", 9 | "mode": "snapshot", 10 | "bucket": "cloudtranscode-eu-dev", 11 | "path": "/output/thumbs/", 12 | "file": "video1_thumb.jpg", 13 | "s3_rrs": true, 14 | "s3_encrypt": true, 15 | "size": "-1:159", 16 | "snapshot_sec": 5 17 | } 18 | ] 19 | } 20 | -------------------------------------------------------------------------------- /input_samples/input_video1.json: -------------------------------------------------------------------------------- 1 | { 2 | "input_asset": { 3 | "type": "VIDEO", 4 | "bucket": "cloudtranscode-eu-dev", 5 | "file": "/input/video1.mp4" 6 | }, 7 | "output_assets": [ 8 | { 9 | "type": "THUMB", 10 | "mode": "snapshot", 11 | "bucket": "cloudtranscode-eu-dev", 12 | "path": "/output/", 13 | "file": "thumbnail_sd.jpg", 14 | "s3_rrs": true, 15 | "s3_encrypt": true, 16 | "size": "-1:159", 17 | "snapshot_sec": 5 18 | }, 19 | { 20 | "type": "THUMB", 21 | "mode": "snapshot", 22 | "bucket": "cloudtranscode-eu-dev", 23 | "path": "/output/", 24 | "file": "thumbnail_hd.jpg", 25 | "s3_rrs": true, 26 | "s3_encrypt": true, 27 | "size": "-1:720", 28 | "snapshot_sec": 5 29 | }, 30 | { 31 | "type": "VIDEO", 32 | "bucket": "cloudtranscode-eu-dev", 33 | "path": "/output/", 34 | "file": "video1.mp4", 35 | "s3_rrs": true, 36 | "s3_encrypt": true, 37 | "keep_ratio": false, 38 | "no_enlarge": false, 39 | "preset": "360p-4.3-generic", 40 | "watermark": { 41 | "bucket": "cloudtranscode-eu-dev", 42 | "file": "/no-text-96px.png", 43 | "size": "96:96", 44 | "opacity": 0.2, 45 | "x": -20, 46 | "y": -20 47 | } 48 | } 49 | ] 50 | } 51 | 52 | -------------------------------------------------------------------------------- /input_samples/input_video1_http_input.json: -------------------------------------------------------------------------------- 1 | { 2 | "input_asset": { 3 | "type": "VIDEO", 4 | "http": "https://s3.amazonaws.com/cloudtranscode-dev/input/Football+Gameplan%27s+2013+College+Football+FCS+Wraparound+-+Week+13+-+YouTube+%5B360p%5D.mp4" 5 | }, 6 | "output_assets": 7 | [ 8 | { 9 | "type": "THUMB", 10 | "mode": "snapshot", 11 | "bucket": "cloudtranscode-eu-dev", 12 | "path": "/output/", 13 | "file": "thumbnail_sd.jpg", 14 | "s3_rrs": true, 15 | "s3_encrypt": true, 16 | "size": "-1:159", 17 | "snapshot_sec": 5 18 | }, 19 | { 20 | "type": "THUMB", 21 | "mode": "snapshot", 22 | "bucket": "cloudtranscode-eu-dev", 23 | "path": "/output/", 24 | "file": "thumbnail_hd.jpg", 25 | "s3_rrs": true, 26 | "s3_encrypt": true, 27 | "size": "-1:720", 28 | "snapshot_sec": 5 29 | }, 30 | { 31 | "type": "VIDEO", 32 | "bucket": "cloudtranscode-eu-dev", 33 | "file": "/output/video1.mp4", 34 | "s3_rrs": true, 35 | "s3_encrypt": true, 36 | "keep_ratio": false, 37 | "no_enlarge": false, 38 | "preset": "360p-4.3-generic", 39 | "watermark": { 40 | "bucket": "cloudtranscode-eu-dev", 41 | "file": "/no-text-96px.png", 42 | "size": "96:96", 43 | "opacity": 0.2, 44 | "x": -20, 45 | "y": -20 46 | } 47 | } 48 | ] 49 | } 50 | -------------------------------------------------------------------------------- /input_samples/input_videoHLS.json: -------------------------------------------------------------------------------- 1 | { 2 | "input_asset": { 3 | "type": "VIDEO", 4 | "bucket": "cloudtranscode-dev", 5 | "file": "/input/video1.mp4" 6 | }, 7 | "output_asset": [ 8 | { 9 | "type": "VIDEO", 10 | "bucket": "cloudtranscode-dev", 11 | "path": "/output/HLS/", 12 | "file": "video1.M3U8", 13 | "s3_rrs": true, 14 | "s3_encrypt": true, 15 | "keep_ratio": false, 16 | "no_enlarge": false, 17 | "preset": "hls600k-generic", 18 | "watermark": { 19 | "bucket": "cloudtranscode-dev", 20 | "file": "/no-text-96px.png", 21 | "size": "96:96", 22 | "opacity": 0.2, 23 | "x": -20, 24 | "y": -20 25 | } 26 | ] 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /input_samples/input_video_custom_cmd.json: -------------------------------------------------------------------------------- 1 | { 2 | "input_asset": { 3 | "type": "VIDEO", 4 | "bucket": "cloudtranscode-dev", 5 | "file": "/input/video1.mp4" 6 | }, 7 | "output_asset": [ 8 | { 9 | "type": "VIDEO", 10 | "bucket": "cloudtranscode-dev", 11 | "path" : "/output/", 12 | "file": "video1.mp4", 13 | "s3_rrs": true, 14 | "s3_encrypt": true, 15 | "custom_cmd": "ffmpeg -i ${input_file} -c:v libx264 -preset slow -crf 22 -c:a copy ${watermark_options} ${output_file}", 16 | "watermark": { 17 | "bucket": "cloudtranscode-dev", 18 | "file": "/no-text-96px.png", 19 | "size": "96:96", 20 | "opacity": 0.2, 21 | "x": -20, 22 | "y": -20 23 | } 24 | ] 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /input_samples/input_video_custom_cmd_http_input.json: -------------------------------------------------------------------------------- 1 | { 2 | "input_asset": { 3 | "type": "VIDEO", 4 | "http": "https://s3.amazonaws.com/cloudtranscode-dev/input/Andre+Johnson+mic%27d+up+uncensored.mp4" 5 | }, 6 | "output_asset": 7 | { 8 | "type": "VIDEO", 9 | "bucket": "cloudtranscode-dev", 10 | "path": "/output/", 11 | "file": "video1_custom_cmd_http.mp4", 12 | "s3_rrs": true, 13 | "s3_encrypt": true, 14 | "custom_cmd": "ffmpeg -i ${input_file} -c:v libx264 -preset slow -crf 22 -c:a copy ${watermark_options} ${output_file}", 15 | "watermark": { 16 | "bucket": "cloudtranscode-dev", 17 | "file": "/no-text-96px.png", 18 | "size": "96:96", 19 | "opacity": 0.2, 20 | "x": -20, 21 | "y": -20 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/activities/BasicActivity.php: -------------------------------------------------------------------------------- 1 | s3Utils = new S3Utils($this->cpeLogger); 60 | } 61 | 62 | // Perform the activity 63 | public function process($task) 64 | { 65 | // Use workflowID to generate a unique TMP folder localy. 66 | $this->tmpInputPath = self::TMP_FOLDER 67 | . $this->logKey."/" 68 | . "input"; 69 | 70 | $inputFileInfo = null; 71 | if (isset($this->input->{'input_asset'}->{'file'})) { 72 | $this->input->{'input_asset'}->{'file'} = ltrim($this->input->{'input_asset'}->{'file'}, "/"); 73 | $inputFileInfo = pathinfo($this->input->{'input_asset'}->{'file'}); 74 | } 75 | 76 | // Create the tmp folder if doesn't exist 77 | if (!file_exists($this->tmpInputPath)) 78 | { 79 | if ($this->debug) 80 | $this->cpeLogger->logOut("DEBUG", basename(__FILE__), 81 | "Creating TMP input folder '".$this->tmpInputPath."'", 82 | $this->logKey); 83 | 84 | if (!mkdir($this->tmpInputPath, 0750, true)) 85 | throw new CpeSdk\CpeException( 86 | "Unable to create temporary folder '$this->tmpInputPath' !", 87 | self::TMP_FOLDER_FAIL 88 | ); 89 | } 90 | 91 | $this->inputFilePath = null; 92 | if (isset($this->input->{'input_asset'}->{'http'})) 93 | { 94 | // Pad HTTP input so it is cached in case of full encodes 95 | $this->inputFilePath = 'cache:' . $this->input->{'input_asset'}->{'http'}; 96 | } 97 | else if (isset($this->input->{'input_asset'}->{'bucket'}) && 98 | isset($this->input->{'input_asset'}->{'file'})) 99 | { 100 | // Download input file and store it in TMP folder 101 | $saveFileTo = $this->tmpInputPath."/".$inputFileInfo['basename']; 102 | $this->inputFilePath = $this->getFileToProcess( 103 | $task, 104 | $this->input->{'input_asset'}->{'bucket'}, 105 | $this->input->{'input_asset'}->{'file'}, 106 | $saveFileTo 107 | ); 108 | } 109 | } 110 | 111 | /** 112 | * Custom code for Cloud Transcode 113 | */ 114 | 115 | // Create TMP folder and download file to process 116 | public function getFileToProcess($task, $inputBuket, $inputFile, $saveFileTo) 117 | { 118 | // Get file from S3 or local copy if any 119 | $this->cpeLogger->logOut("INFO", 120 | basename(__FILE__), 121 | "Downloading '$inputBuket/$inputFile' to '$saveFileTo' ...", 122 | $this->logKey); 123 | 124 | // Use the S3 utils to initiate the download 125 | $s3Output = $this->s3Utils->get_file_from_s3( 126 | $inputBuket, 127 | $inputFile, 128 | $saveFileTo, 129 | array($this, "activityHeartbeat"), 130 | null, 131 | $this->logKey 132 | ); 133 | 134 | $this->cpeLogger->logOut("INFO", basename(__FILE__), 135 | $s3Output['msg'], 136 | $this->logKey); 137 | 138 | $this->cpeLogger->logOut("INFO", basename(__FILE__), 139 | "Input file successfully downloaded into local TMP folder '$saveFileTo' !", 140 | $this->logKey); 141 | 142 | return $saveFileTo; 143 | } 144 | } 145 | 146 | -------------------------------------------------------------------------------- /src/activities/TranscodeAssetActivity.php: -------------------------------------------------------------------------------- 1 | #!/usr/bin/php 2 | 3 | outputs = $this->input->{'output_assets'}; 52 | 53 | $this->cpeLogger->logOut( 54 | "INFO", 55 | basename(__FILE__), 56 | "Preparing Asset transcoding ...", 57 | $this->logKey 58 | ); 59 | 60 | foreach ($this->outputs as $output) 61 | { 62 | $this->validateInput($output); 63 | 64 | // Set output path to store result files 65 | $this->outputFilesPath = $this->getOutputPath($output); 66 | 67 | // Load the right transcoder base on input_type 68 | // Get asset detailed info 69 | switch ($this->input->{'input_asset'}->{'type'}) 70 | { 71 | case self::VIDEO: 72 | $result = $this->transcodeVideo($task, $output); 73 | break; 74 | case self::IMAGE: 75 | $result = $this->transcodeImage($task, $output); 76 | break; 77 | case self::AUDIO: 78 | case self::DOC: 79 | break; 80 | default: 81 | throw new CpeSdk\CpeException("Unknown input asset 'type'! Abording ...", 82 | self::UNKOWN_INPUT_TYPE); 83 | } 84 | 85 | // Upload resulting file 86 | $this->uploadResultFiles($task, $output); 87 | 88 | if ($this->client) 89 | $this->client->onTranscodeDone($this->token, $result); 90 | } 91 | 92 | return json_encode($result); 93 | } 94 | 95 | // Process INPUT IMAGE 96 | private function transcodeImage($task, $output) 97 | { 98 | require_once __DIR__.'/transcoders/ImageTranscoder.php'; 99 | 100 | // Instanciate transcoder to output Images 101 | $imageTranscoder = new ImageTranscoder($this, $task); 102 | 103 | # If we have metadata, we expect the output of ffprobe 104 | $metadata = null; 105 | if (isset($this->input->{'input_metadata'})) 106 | $metadata = $this->input->{'input_metadata'}; 107 | 108 | // Perform transcoding 109 | $result = $imageTranscoder->transcode_asset( 110 | $this->tmpInputPath, 111 | $this->inputFilePath, 112 | $this->outputFilesPath, 113 | $metadata, 114 | $output 115 | ); 116 | 117 | unset($imageTranscoder); 118 | 119 | return ($result); 120 | } 121 | 122 | // Process INPUT VIDEO 123 | private function transcodeVideo($task, $output) 124 | { 125 | require_once __DIR__.'/transcoders/VideoTranscoder.php'; 126 | 127 | // Instanciate transcoder to output Videos 128 | $videoTranscoder = new VideoTranscoder($this, $task); 129 | 130 | // Check preset file, read its content and add its data to output object 131 | if ($output->{'type'} == self::VIDEO && 132 | isset($output->{'preset'})) 133 | { 134 | // Validate output preset 135 | $videoTranscoder->validate_preset($output); 136 | 137 | // Set preset value 138 | $output->{'preset_values'} = $videoTranscoder->get_preset_values($output); 139 | } 140 | 141 | # If we have metadata, we expect the output of ffprobe 142 | $metadata = null; 143 | if (isset($this->input->{'input_metadata'})) 144 | $metadata = $this->input->{'input_metadata'}; 145 | 146 | // Perform transcoding 147 | $result = $videoTranscoder->transcode_asset( 148 | $this->tmpInputPath, 149 | $this->inputFilePath, 150 | $this->outputFilesPath, 151 | $metadata, 152 | $output 153 | ); 154 | 155 | unset($videoTranscoder); 156 | 157 | return ($result); 158 | } 159 | 160 | // Upload all output files to destination S3 bucket 161 | private function uploadResultFiles($task, $output) 162 | { 163 | // Sanitize output bucket and file path "/" 164 | $s3Bucket = str_replace("//", "/", 165 | $output->{"bucket"}); 166 | 167 | // Set S3 options 168 | $options = array("rrs" => false, "encrypt" => false); 169 | if (isset($output->{'s3_rrs'}) && 170 | $output->{'s3_rrs'} == true) { 171 | $options['rrs'] = true; 172 | } 173 | if (isset($output->{'s3_encrypt'}) && 174 | $output->{'s3_encrypt'} == true) { 175 | $options['encrypt'] = true; 176 | } 177 | 178 | // Open '$outputFilesPath' to read it and send all files to S3 bucket 179 | if (!$handle = opendir($this->outputFilesPath)) { 180 | throw new CpeSdk\CpeException("Can't open tmp path '$this->outputFilesPath'!", 181 | self::TMP_PATH_OPEN_FAIL); 182 | } 183 | 184 | // Upload all resulting files sitting in $outputFilesPath to S3 185 | while ($entry = readdir($handle)) { 186 | if ($entry == "." || $entry == "..") { 187 | continue; 188 | } 189 | 190 | // Destination path on S3. Sanitizing 191 | $s3Location = $output->{'output_file_info'}['dirname']."/$entry"; 192 | $s3Location = str_replace("//", "/", $s3Location); 193 | 194 | // Send to S3. We reference the callback s3_put_processing_callback 195 | // The callback ping back SWF so we stay alive 196 | $s3Output = $this->s3Utils->put_file_into_s3( 197 | $s3Bucket, 198 | $s3Location, 199 | "$this->outputFilesPath/$entry", 200 | $options, 201 | array($this, "activityHeartbeat"), 202 | null 203 | ); 204 | // We delete the TMP file once uploaded 205 | unlink("$this->outputFilesPath/$entry"); 206 | 207 | $this->cpeLogger->logOut("INFO", basename(__FILE__), 208 | $s3Output['msg'], 209 | $this->logKey); 210 | } 211 | } 212 | 213 | private function getOutputPath($output) 214 | { 215 | $outputFilesPath = self::TMP_FOLDER 216 | . $this->name."/".$this->logKey; 217 | 218 | $output->{'key'} = $output->{'path'}."/".$output->{'file'}; 219 | 220 | // Create TMP folder for output files 221 | $outputFileInfo = pathinfo($output->{'key'}); 222 | $output->{'output_file_info'} = $outputFileInfo; 223 | $outputFilesPath .= $outputFileInfo['dirname']; 224 | 225 | if (!file_exists($outputFilesPath)) 226 | { 227 | if ($this->debug) 228 | $this->cpeLogger->logOut("INFO", basename(__FILE__), 229 | "Creating TMP output folder '".$outputFilesPath."'", 230 | $this->logKey); 231 | 232 | if (!mkdir($outputFilesPath, 0750, true)) 233 | throw new CpeSdk\CpeException( 234 | "Unable to create temporary folder '$outputFilesPath' !", 235 | self::TMP_FOLDER_FAIL 236 | ); 237 | } 238 | 239 | return ($outputFilesPath); 240 | } 241 | 242 | // Perform custom validation on JSON input 243 | // Callback function used in $this->do_input_validation 244 | private function validateInput($output) 245 | { 246 | if (( 247 | $this->input->{'input_asset'}->{'type'} == self::VIDEO && 248 | $output->{'type'} != self::VIDEO && 249 | $output->{'type'} != self::THUMB && 250 | $output->{'type'} != self::AUDIO 251 | ) 252 | || 253 | ( 254 | $this->input->{'input_asset'}->{'type'} == self::IMAGE && 255 | $output->{'type'} != self::IMAGE 256 | ) 257 | || 258 | ( 259 | $this->input->{'input_asset'}->{'type'} == self::AUDIO && 260 | $output->{'type'} != self::AUDIO 261 | ) 262 | || 263 | ( 264 | $this->input->{'input_asset'}->{'type'} == self::DOC && 265 | $output->{'type'} != self::DOC 266 | )) 267 | { 268 | throw new CpeSdk\CpeException("Can't convert that input asset 'type' (".$this->input->{'input_asset'}->{'type'}.") into this output asset 'type' (".$output->{'type'}.")! Abording.", 269 | self::CONVERSION_TYPE_ERROR); 270 | } 271 | } 272 | } 273 | 274 | 275 | /* 276 | *************************** 277 | * Activity Startup SCRIPT 278 | *************************** 279 | */ 280 | 281 | // Usage 282 | function usage() 283 | { 284 | echo("Usage: php ". basename(__FILE__) . " -A [-C ] [-N ] [-h] [-d] [-l ]\n"); 285 | echo("-h: Print this help\n"); 286 | echo("-d: Debug mode\n"); 287 | echo("-l : Location where logs will be dumped in (folder).\n"); 288 | echo("-A : Activity name this Poller can process. Or use 'SNF_ACTIVITY_ARN' environment variable. Command line arguments have precedence\n"); 289 | echo("-C : Path to the PHP file that contains the class that implements your Client Interface\n"); 290 | echo("-N : Override the default activity name. Useful if you want to have different client interfaces for the same activity type.\n"); 291 | exit(0); 292 | } 293 | 294 | // Check command line input parameters 295 | function check_activity_arguments() 296 | { 297 | // Filling the globals with input 298 | global $arn; 299 | global $logPath; 300 | global $debug; 301 | global $clientClassPath; 302 | global $name; 303 | 304 | // Handle input parameters 305 | if (!($options = getopt("N:A:l:C:hd"))) 306 | usage(); 307 | 308 | if (isset($options['h'])) 309 | usage(); 310 | 311 | // Debug 312 | if (isset($options['d'])) 313 | $debug = true; 314 | 315 | if (isset($options['A']) && $options['A']) { 316 | $arn = $options['A']; 317 | } else if (getenv('SNF_ACTIVITY_ARN')) { 318 | $arn = getenv('SNF_ACTIVITY_ARN'); 319 | } else { 320 | echo "ERROR: You must provide the ARN of your activity (Sfn ARN). Use option [-A ] or environment variable: 'SNF_ACTIVITY_ARN'\n"; 321 | usage(); 322 | } 323 | 324 | if (isset($options['C']) && $options['C']) { 325 | $clientClassPath = $options['C']; 326 | } 327 | 328 | if (isset($options['N']) && $options['N']) { 329 | $name = $options['N']; 330 | } 331 | 332 | if (isset($options['l'])) 333 | $logPath = $options['l']; 334 | } 335 | 336 | 337 | 338 | /* 339 | * START THE SCRIPT ACTITIVY 340 | */ 341 | 342 | // Globals 343 | $debug = false; 344 | $logPath = null; 345 | $arn; 346 | $name = 'TranscodeAsset'; 347 | $clientClassPath = null; 348 | 349 | check_activity_arguments(); 350 | 351 | $cpeLogger = new SA\CpeSdk\CpeLogger($name, $logPath); 352 | $cpeLogger->logOut("INFO", basename(__FILE__), 353 | "\033[1mStarting activity\033[0m: $name"); 354 | 355 | // We instanciate the Activity 'ValidateAsset' and give it a name for Snf 356 | $activityPoller = new TranscodeAssetActivity( 357 | $clientClassPath, 358 | [ 359 | 'arn' => $arn, 360 | 'name' => $name 361 | ], 362 | $debug, 363 | $cpeLogger); 364 | 365 | // Initiate the polling loop and will call your `process` function upon trigger 366 | // The process will exit after 24 hours (1440 minutes) 367 | $activityPoller->doActivity(1440); -------------------------------------------------------------------------------- /src/activities/ValidateAssetActivity.php: -------------------------------------------------------------------------------- 1 | #!/usr/bin/php 2 | 3 | s3 = new \Aws\S3\S3Client([ 47 | "version" => "latest", 48 | "region" => $region 49 | ]); 50 | } 51 | 52 | // Used to limit the curl download in case of an HTTP encode 53 | private function writefn($ch, $chunk) 54 | { 55 | static $limit = 1024; 56 | 57 | $len = strlen($this->curl_data) + strlen($chunk); 58 | if ($len >= $limit) { 59 | $this->curl_data .= substr($chunk, 0, $limit-strlen($this->curl_data)); 60 | return -1; 61 | } 62 | 63 | $this->curl_data .= $chunk; 64 | return strlen($chunk); 65 | } 66 | 67 | // Perform the activity 68 | public function process($task) 69 | { 70 | $this->cpeLogger->logOut( 71 | "INFO", 72 | basename(__FILE__), 73 | "Preparing Asset validation ...", 74 | $this->logKey 75 | ); 76 | 77 | // Call parent process: 78 | parent::process($task); 79 | 80 | $this->activityHeartbeat(); 81 | $tmpFile = tempnam(sys_get_temp_dir(), 'ct'); 82 | 83 | if (isset($this->input->{'input_asset'}->{'http'})) { 84 | $this->cpeLogger->logOut( 85 | "DEBUG", 86 | basename(__FILE__), 87 | "Downloading first 1024 bytes from: " . $this->input->{'input_asset'}->{'http'}, 88 | $this->logKey 89 | ); 90 | 91 | $this->curl_data = ''; 92 | 93 | $ch = curl_init(); 94 | curl_setopt($ch, CURLOPT_URL, $this->input->{'input_asset'}->{'http'}); 95 | curl_setopt($ch, CURLOPT_RANGE, '0-1024'); 96 | curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($this, 'writefn')); 97 | curl_exec($ch); 98 | if ($errno = curl_errno($ch)) { 99 | if ($errno != CURLE_WRITE_ERROR) { 100 | $error_message = curl_strerror($errno); 101 | throw new CpeSdk\CpeException( 102 | $error_message, 103 | self::VALIDATE_ASSET_FAILED 104 | ); 105 | } 106 | } 107 | curl_close($ch); 108 | 109 | $chunk = $this->curl_data; 110 | } 111 | else if (isset($this->input->{'input_asset'}->{'bucket'}) && 112 | isset($this->input->{'input_asset'}->{'file'})) { 113 | $this->cpeLogger->logOut( 114 | "DEBUG", 115 | basename(__FILE__), 116 | "Downloading first 1024 bytes from S3. Bucket: " . $this->input->{'input_asset'}->{'bucket'} . ". Key: " . $this->input->{'input_asset'}->{'file'}, 117 | $this->logKey 118 | ); 119 | 120 | // Fetch first 1 KiB of the file for Magic number validation 121 | $obj = $this->s3->getObject([ 122 | 'Bucket' => $this->input->{'input_asset'}->{'bucket'}, 123 | 'Key' => $this->input->{'input_asset'}->{'file'}, 124 | 'Range' => 'bytes=0-1024' 125 | ]); 126 | $chunk = (string) $obj['Body']; 127 | } 128 | 129 | $this->activityHeartbeat(); 130 | 131 | // Determine file type 132 | file_put_contents($tmpFile, $chunk); 133 | $mime = trim((new CommandExecuter($this->cpeLogger, $this->logKey))->execute( 134 | 'file -b --mime-type '.escapeshellarg($tmpFile))['out']); 135 | $type = substr($mime, 0, strpos($mime, '/')); 136 | 137 | if ($this->debug) 138 | $this->cpeLogger->logOut( 139 | "DEBUG", 140 | basename(__FILE__), 141 | "File meta information gathered. Mime: $mime | Type: $type", 142 | $this->logKey 143 | ); 144 | 145 | // Load the right transcoder base on input_type 146 | // Get asset detailed info 147 | switch ($type) 148 | { 149 | case 'audio': 150 | case 'video': 151 | case 'image': 152 | default: 153 | require_once __DIR__.'/transcoders/VideoTranscoder.php'; 154 | 155 | // Initiate transcoder obj 156 | $videoTranscoder = new VideoTranscoder($this, $task); 157 | // Get input video information 158 | $assetInfo = $videoTranscoder->getAssetInfo($this->inputFilePath); 159 | 160 | // Liberate memory 161 | unset($videoTranscoder); 162 | } 163 | 164 | if ($mime === 'application/octet-stream' && isset($assetInfo->streams)) { 165 | // Check all stream types 166 | foreach ($assetInfo->streams as $stream) { 167 | if ($stream->codec_type === 'video') { 168 | // For a video type, set type to video and break 169 | $type = 'video'; 170 | break; 171 | } elseif ($stream->codec_type === 'audio') { 172 | // For an audio type, set to audio, but don't break 173 | // in case there's a video stream later 174 | $type = 'audio'; 175 | } 176 | } 177 | } 178 | 179 | $assetInfo->mime = $mime; 180 | $assetInfo->type = $type; 181 | 182 | $result['input_asset'] = $this->input->{'input_asset'}; 183 | $result['input_metadata'] = $assetInfo; 184 | $result['output_assets'] = $this->input->{'output_assets'}; 185 | 186 | return json_encode($result); 187 | } 188 | } 189 | 190 | 191 | /* 192 | *************************** 193 | * Activity Startup SCRIPT 194 | *************************** 195 | */ 196 | 197 | // Usage 198 | function usage() 199 | { 200 | echo("Usage: php ". basename(__FILE__) . " -A [-C ] [-N ] [-h] [-d] [-l ]\n"); 201 | echo("-h: Print this help\n"); 202 | echo("-d: Debug mode\n"); 203 | echo("-l : Location where logs will be dumped in (folder).\n"); 204 | echo("-A : Activity name this Poller can process. Or use 'SNF_ACTIVITY_ARN' environment variable. Command line arguments have precedence\n"); 205 | echo("-C : Path to the PHP file that contains the class that implements your Client Interface\n"); 206 | echo("-N : Override the default activity name. Useful if you want to have different client interfaces for the same activity type.\n"); 207 | exit(0); 208 | } 209 | 210 | // Check command line input parameters 211 | function check_activity_arguments() 212 | { 213 | // Filling the globals with input 214 | global $arn; 215 | global $logPath; 216 | global $debug; 217 | global $clientClassPath; 218 | global $name; 219 | 220 | // Handle input parameters 221 | if (!($options = getopt("N:A:l:C:hd"))) 222 | usage(); 223 | 224 | if (isset($options['h'])) 225 | usage(); 226 | 227 | // Debug 228 | if (isset($options['d'])) 229 | $debug = true; 230 | 231 | if (isset($options['A']) && $options['A']) { 232 | $arn = $options['A']; 233 | } else if (getenv('SNF_ACTIVITY_ARN')) { 234 | $arn = getenv('SNF_ACTIVITY_ARN'); 235 | } else { 236 | echo "ERROR: You must provide the ARN of your activity (Sfn ARN). Use option [-A ] or environment variable: 'SNF_ACTIVITY_ARN'\n"; 237 | usage(); 238 | } 239 | 240 | if (isset($options['C']) && $options['C']) { 241 | $clientClassPath = $options['C']; 242 | } 243 | 244 | if (isset($options['N']) && $options['N']) { 245 | $name = $options['N']; 246 | } 247 | 248 | if (isset($options['l'])) 249 | $logPath = $options['l']; 250 | } 251 | 252 | 253 | /* 254 | * START THE SCRIPT ACTITIVY 255 | */ 256 | 257 | // Globals 258 | $debug = false; 259 | $logPath = null; 260 | $arn; 261 | $name = 'ValidateAsset'; 262 | $clientClassPath = null; 263 | 264 | check_activity_arguments(); 265 | 266 | $cpeLogger = new SA\CpeSdk\CpeLogger($name, $logPath); 267 | $cpeLogger->logOut("INFO", basename(__FILE__), 268 | "\033[1mStarting activity\033[0m: $name"); 269 | 270 | // We instanciate the Activity 'ValidateAsset' and give it a name for Snf 271 | $activityPoller = new ValidateAssetActivity( 272 | $clientClassPath, 273 | [ 274 | 'arn' => $arn, 275 | 'name' => $name 276 | ], 277 | $debug, 278 | $cpeLogger); 279 | 280 | // Initiate the polling loop and will call your `process` function upon trigger 281 | // The process will exit after 24 hours (1440 minutes) 282 | $activityPoller->doActivity(1440); 283 | -------------------------------------------------------------------------------- /src/activities/transcoders/AudioTranscoder.php: -------------------------------------------------------------------------------- 1 | activityObj = $activityObj; 52 | $this->logKey = $activityObj->logKey; 53 | $this->task = $task; 54 | 55 | $this->cpeLogger = $activityObj->cpeLogger; 56 | $this->executer = new CommandExecuter($activityObj->cpeLogger, $this->logKey); 57 | $this->s3Utils = new S3Utils($activityObj->cpeLogger); 58 | } 59 | 60 | public function isDirEmpty($dir) 61 | { 62 | if (!is_readable($dir)) return null; 63 | $handle = opendir($dir); 64 | while (false !== ($entry = readdir($handle))) { 65 | if ($entry !== '.' && $entry !== '..') { 66 | return false; 67 | } 68 | } 69 | closedir($handle); 70 | return true; 71 | } 72 | 73 | 74 | /************************************** 75 | * GET ASSET METADATA INFO 76 | * The methods below are used to run ffprobe on assets 77 | * We capture as much info as possible on the input asset 78 | */ 79 | 80 | // Execute FFPROBE to get asset information 81 | public function getAssetInfo($inputFilePath) 82 | { 83 | $inputFilePath = escapeshellarg($inputFilePath); 84 | $ffprobeCmd = "ffprobe -v quiet -of json -show_format -show_streams $inputFilePath"; 85 | try { 86 | // Execute FFMpeg to validate and get information about input video 87 | $out = $this->executer->execute( 88 | $ffprobeCmd, 89 | 1, 90 | array( 91 | 1 => array("pipe", "w"), 92 | 2 => array("pipe", "w") 93 | ), 94 | false, false, 95 | false, 1 96 | ); 97 | } 98 | catch (\Exception $e) { 99 | $this->cpeLogger->logOut( 100 | "ERROR", 101 | basename(__FILE__), 102 | "Execution of command '".$ffprobeCmd."' failed.", 103 | $this->activityLogKey 104 | ); 105 | 106 | throw new CpeSdk\CpeException("Unable to execute FFProbe to get information about '$inputFilePath'!", 107 | self::EXEC_VALIDATE_FAILED); 108 | } 109 | 110 | if (empty($out)) { 111 | throw new CpeSdk\CpeException("Unable to execute FFProbe to get information about '$inputFilePath'!", 112 | self::EXEC_VALIDATE_FAILED); 113 | } 114 | 115 | // FFmpeg writes on STDERR ... 116 | if (!($assetInfo = json_decode($out['out']))) { 117 | throw new CpeSdk\CpeException("FFProbe returned invalid JSON!", 118 | self::EXEC_VALIDATE_FAILED); 119 | } 120 | 121 | return ($assetInfo); 122 | } 123 | 124 | // Extract Metadata from ffprobe 125 | public function _extractFileInfo($metadata) { 126 | 127 | $videoStreams; 128 | $audioStreams; 129 | 130 | foreach ($metadata->streams as $key => $value) { 131 | if ($value->codec_type === 'video') { 132 | $videoStreams = $value; 133 | } 134 | else if ($value->codec_type === 'audio') { 135 | $audioStreams = $value; 136 | } 137 | } 138 | 139 | $analyse = [ 140 | 'duration' => isset($metadata->format->duration) ? (float)$metadata->format->duration : 0, 141 | 'video' => empty($videoStreams) ? null : [ 142 | 'codec' => $videoStreams->codec_name, 143 | 'color' => @$videoStreams->color_space, 144 | 'resolution' => $videoStreams->width . 'x' . $videoStreams->height, 145 | 'sar' => $videoStreams->sample_aspect_ratio, 146 | 'dar' => $videoStreams->display_aspect_ratio, 147 | 'framerate' => $videoStreams->r_frame_rate, 148 | 'bitrate' => isset($videoStreams->bit_rate) ? (int)$videoStreams->bit_rate : null 149 | ], 150 | 'audio' => empty($audioStreams) ? null : [ 151 | 'codec' => $audioStreams->codec_name, 152 | 'frequency' => $audioStreams->sample_rate, 153 | 'channels' => (int)$audioStreams->channels, 154 | 'depth' => $audioStreams->bits_per_sample, 155 | 'bitrate' => (int)$audioStreams->bit_rate 156 | ] 157 | ]; 158 | 159 | return $analyse; 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /src/activities/transcoders/DocumentTranscoder.php: -------------------------------------------------------------------------------- 1 | _extractFileInfo($metadata); 48 | } 49 | 50 | $this->cpeLogger->logOut( 51 | "INFO", 52 | basename(__FILE__), 53 | "Start Transcoding Asset '$pathToInputFile' ...", 54 | $this->activityLogKey 55 | ); 56 | 57 | if ($metadata) 58 | $this->cpeLogger->logOut( 59 | "INFO", 60 | basename(__FILE__), 61 | "Input Video metadata: " . print_r($metadata, true), 62 | $this->activityLogKey 63 | ); 64 | 65 | try { 66 | $convertCmd = ""; 67 | 68 | // Update output extension file if it ends with '.*' 69 | // Output will take the same extension as input 70 | $this->_updateOutputExtension( 71 | $pathToInputFile, 72 | $outputWanted); 73 | 74 | // Custom command 75 | if (isset($outputWanted->{'custom_cmd'}) && 76 | $outputWanted->{'custom_cmd'}) { 77 | $convertCmd = $this->craft_convert_custom_cmd( 78 | $tmpPathInput, 79 | $pathToInputFile, 80 | $pathToOutputFiles, 81 | $metadata, 82 | $outputWanted 83 | ); 84 | } 85 | else { 86 | $convertCmd = $this->craft_convert_cmd( 87 | $tmpPathInput, 88 | $pathToInputFile, 89 | $pathToOutputFiles, 90 | $metadata, 91 | $outputWanted 92 | ); 93 | } 94 | 95 | $this->cpeLogger->logOut( 96 | "INFO", 97 | basename(__FILE__), 98 | "CONVERT CMD:\n$convertCmd\n", 99 | $this->activityLogKey 100 | ); 101 | 102 | // Use executer to start Converter command 103 | // Use 'capture_progression' function as callback 104 | // Pass video 'duration' as parameter 105 | // Sleep 1sec between turns and callback every 10 turns 106 | // Output progression logs (true) 107 | $this->executer->execute( 108 | $convertCmd, 109 | 1, 110 | array(2 => array("pipe", "w")), 111 | array($this->activityObj, "activityHeartbeat"), 112 | null, 113 | true, 114 | 10 115 | ); 116 | 117 | // Test if we have an output file ! 118 | if (!file_exists($pathToOutputFiles) || 119 | $this->isDirEmpty($pathToOutputFiles)) { 120 | throw new CpeSdk\CpeException( 121 | "Output file '$pathToOutputFiles' hasn't been created successfully or is empty !", 122 | self::TRANSCODE_FAIL 123 | ); 124 | } 125 | 126 | // FFProbe the output file and return its information 127 | // XXX: Remove FFprobe for image convertion. Save time 128 | $outputInfo = 129 | $this->getAssetInfo($pathToOutputFiles."/".$outputWanted->{'output_file_info'}['basename']); 130 | } 131 | catch (\Exception $e) { 132 | $this->cpeLogger->logOut( 133 | "ERROR", 134 | basename(__FILE__), 135 | "Execution of command '".$convertCmd."' failed: " . print_r($metadata, true). ". ".$e->getMessage(), 136 | $this->activityLogKey 137 | ); 138 | throw $e; 139 | } 140 | 141 | // No error. Transcode successful 142 | $this->cpeLogger->logOut( 143 | "INFO", 144 | basename(__FILE__), 145 | "Transcoding successfull !", 146 | $this->activityLogKey 147 | ); 148 | 149 | return [ 150 | "output" => $outputWanted, 151 | "outputInfo" => $outputInfo 152 | ]; 153 | } 154 | 155 | // Craft command based on JSON input 156 | private function craft_convert_cmd( 157 | $tmpPathInput, 158 | $pathToInputFile, 159 | $pathToOutputFiles, 160 | $metadata, 161 | $outputWanted) 162 | { 163 | $convertArgs = "$pathToInputFile "; 164 | 165 | if (isset($outputWanted->{'quality'})) { 166 | $quality = $outputWanted->{'quality'}; 167 | $convertArgs .= "-quality $quality "; 168 | } 169 | 170 | if (isset($outputWanted->{'resize'})) { 171 | $resize = $outputWanted->{'resize'}; 172 | $convertArgs .= "-resize $resize "; 173 | } 174 | 175 | if (isset($outputWanted->{'thumbnail'})) { 176 | $thumbnail = $outputWanted->{'thumbnail'}; 177 | $convertArgs .= "-thumbnail $thumbnail "; 178 | } 179 | 180 | if (isset($outputWanted->{'crop'})) { 181 | $crop = $outputWanted->{'crop'}; 182 | $convertArgs .= "-crop $crop "; 183 | } 184 | 185 | // Append output filename to path 186 | $pathToOutputFiles .= 187 | "/" . $outputWanted->{'output_file_info'}['basename']; 188 | 189 | $convertCmd = "convert $convertArgs $pathToOutputFiles"; 190 | 191 | return ($convertCmd); 192 | } 193 | 194 | // Craft custom command 195 | private function craft_convert_custom_cmd( 196 | $tmpPathInput, 197 | $pathToInputFile, 198 | $pathToOutputFiles, 199 | $metadata, 200 | $outputWanted) 201 | { 202 | $convertCmd = $outputWanted->{'custom_cmd'}; 203 | 204 | // Replace ${input_file} by input file path 205 | $pathToInputFile = escapeshellarg($pathToInputFile); 206 | $convertCmd = preg_replace('/\$\{input_file\}/', 207 | $pathToInputFile, $convertCmd); 208 | 209 | // Append output filename to path 210 | $pathToOutputFiles .= "/" . $outputWanted->{'output_file_info'}['basename']; 211 | // Replace ${output_file} by output filename and path to local disk 212 | $convertCmd = preg_replace('/\$\{output_file\}/', 213 | $pathToOutputFiles, $convertCmd); 214 | 215 | return ($convertCmd); 216 | } 217 | 218 | // Check if output file need an update on the extension 219 | private function _updateOutputExtension( 220 | $pathToInputFile, 221 | &$outputWanted) 222 | { 223 | $inputExtension = 224 | pathinfo($pathToInputFile)['extension']; 225 | 226 | // REplace output extension if == * with the input extension 227 | $outputPathInfo = 228 | pathinfo($outputWanted->{'output_file_info'}['basename']); 229 | $outputExtension = $outputPathInfo['extension']; 230 | if ($outputExtension == "*") { 231 | $outputWanted->{'output_file_info'}['basename'] = preg_replace( 232 | '/\*/', 233 | $inputExtension, 234 | $outputWanted->{'output_file_info'}['basename']); 235 | } 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /src/activities/transcoders/VideoTranscoder.php: -------------------------------------------------------------------------------- 1 | _extractFileInfo($metadata); 74 | } 75 | 76 | $this->cpeLogger->logOut( 77 | "INFO", 78 | basename(__FILE__), 79 | "Start Transcoding Asset '$inputFilePath' ...", 80 | $this->logKey 81 | ); 82 | 83 | if ($metadata) 84 | $this->cpeLogger->logOut( 85 | "INFO", 86 | basename(__FILE__), 87 | "Input Video metadata: " . print_r($metadata, true), 88 | $this->logKey 89 | ); 90 | 91 | try { 92 | $ffmpegCmd = ""; 93 | 94 | // Custom command 95 | if (isset($outputWanted->{'custom_cmd'}) && 96 | $outputWanted->{'custom_cmd'}) { 97 | $ffmpegCmd = $this->craft_ffmpeg_custom_cmd( 98 | $tmpInputPath, 99 | $inputFilePath, 100 | $outputFilesPath, 101 | $metadata, 102 | $outputWanted 103 | ); 104 | } else if ($outputWanted->{'type'} == self::VIDEO) { 105 | $ffmpegCmd = $this->craft_ffmpeg_cmd_video( 106 | $tmpInputPath, 107 | $inputFilePath, 108 | $outputFilesPath, 109 | $metadata, 110 | $outputWanted 111 | ); 112 | } else if ($outputWanted->{'type'} == self::THUMB) { 113 | $ffmpegCmd = $this->craft_ffmpeg_cmd_thumb( 114 | $tmpInputPath, 115 | $inputFilePath, 116 | $outputFilesPath, 117 | $metadata, 118 | $outputWanted 119 | ); 120 | } 121 | 122 | $this->cpeLogger->logOut( 123 | "INFO", 124 | basename(__FILE__), 125 | "FFMPEG CMD:\n$ffmpegCmd\n", 126 | $this->logKey 127 | ); 128 | 129 | // Send heartbeat and initialize progress 130 | $this->activityObj->activityHeartbeat( 131 | [ 132 | "output" => $outputWanted, 133 | "duration" => $metadata['duration'], 134 | "done" => 0, 135 | "progress" => 0 136 | ] 137 | ); 138 | 139 | // Use executer to start FFMpeg command 140 | // Use 'capture_progression' function as callback 141 | // Pass video 'duration' as parameter 142 | // Sleep 1sec between turns and callback every 10 turns 143 | // Output progression logs (true) 144 | $this->executer->execute( 145 | $ffmpegCmd, 146 | 1, 147 | array(2 => array("pipe", "w")), 148 | array($this, "capture_progression"), 149 | [ 150 | "duration" => $metadata['duration'], 151 | "output" => $outputWanted 152 | ], 153 | true, 154 | 10 155 | ); 156 | 157 | // Test if we have an output file ! 158 | if (!file_exists($outputFilesPath) || 159 | $this->isDirEmpty($outputFilesPath)) { 160 | throw new CpeSdk\CpeException( 161 | "Output file '$outputFilesPath' hasn't been created successfully or is empty !", 162 | self::TRANSCODE_FAIL 163 | ); 164 | } 165 | 166 | // FFProbe the output file and return its information 167 | $outputInfo = $this->getAssetInfo($outputFilesPath."/".$outputWanted->{'output_file_info'}['basename']); 168 | } 169 | catch (\Exception $e) { 170 | $this->cpeLogger->logOut( 171 | "ERROR", 172 | basename(__FILE__), 173 | "Execution of command '".$ffmpegCmd."' failed: " . print_r($metadata, true). ". ".$e->getMessage(), 174 | $this->logKey 175 | ); 176 | throw $e; 177 | } 178 | 179 | // No error. Transcode successful 180 | $this->cpeLogger->logOut( 181 | "INFO", 182 | basename(__FILE__), 183 | "Transcoding successfull !", 184 | $this->logKey 185 | ); 186 | 187 | return [ 188 | "output" => $outputWanted, 189 | "outputInfo" => $outputInfo 190 | ]; 191 | } 192 | 193 | // Craft custom command 194 | private function craft_ffmpeg_custom_cmd( 195 | $tmpInputPath, 196 | $inputFilePath, 197 | $outputFilesPath, 198 | $metadata, 199 | $outputWanted) 200 | { 201 | $ffmpegCmd = $outputWanted->{'custom_cmd'}; 202 | 203 | // Replace ${input_file} by input file path 204 | $inputFilePath = escapeshellarg($inputFilePath); 205 | $ffmpegCmd = preg_replace('/\$\{input_file\}/', $inputFilePath, $ffmpegCmd); 206 | 207 | $watermarkOptions = ""; 208 | // Process options for watermark 209 | if (isset($outputWanted->{'watermark'}) && $outputWanted->{'watermark'}) { 210 | $watermarkOptions = 211 | $this->get_watermark_options( 212 | $tmpInputPath, 213 | $outputWanted->{'watermark'}); 214 | // Replace ${watermark_options} by watermark options 215 | $ffmpegCmd = preg_replace('/\$\{watermark_options\}/', $watermarkOptions, $ffmpegCmd); 216 | } 217 | 218 | // Append output filename to path 219 | $outputFilesPath .= "/" . $outputWanted->{'output_file_info'}['basename']; 220 | // Replace ${output_file} by output filename and path to local disk 221 | $ffmpegCmd = preg_replace('/\$\{output_file\}/', $outputFilesPath, $ffmpegCmd); 222 | 223 | return ($ffmpegCmd); 224 | } 225 | 226 | // Generate FFmpeg command for video transcoding 227 | private function craft_ffmpeg_cmd_video( 228 | $tmpInputPath, 229 | $inputFilePath, 230 | $outputFilesPath, 231 | $metadata, 232 | $outputWanted) 233 | { 234 | // Check if a size is provided to override preset size 235 | $size = $this->set_output_video_size($metadata, $outputWanted); 236 | $inputFilePath = escapeshellarg($inputFilePath); 237 | 238 | $videoCodec = $outputWanted->{'preset_values'}->{'video_codec'}; 239 | if (isset($outputWanted->{'video_codec'})) { 240 | $videoCodec = $outputWanted->{'video_codec'}; 241 | } 242 | 243 | $audioCodec = $outputWanted->{'preset_values'}->{'audio_codec'}; 244 | if (isset($outputWanted->{'audio_codec'})) { 245 | $audioCodec = $outputWanted->{'audio_codec'}; 246 | } 247 | 248 | $videoBitrate = $outputWanted->{'preset_values'}->{'video_bitrate'}; 249 | if (isset($outputWanted->{'video_bitrate'})) { 250 | $videoBitrate = $outputWanted->{'video_bitrate'}; 251 | } 252 | 253 | $audioBitrate = $outputWanted->{'preset_values'}->{'audio_bitrate'}; 254 | if (isset($outputWanted->{'audio_bitrate'})) { 255 | $audioBitrate = $outputWanted->{'audio_bitrate'}; 256 | } 257 | 258 | $frameRate = $outputWanted->{'preset_values'}->{'frame_rate'}; 259 | if (isset($outputWanted->{'frame_rate'})) { 260 | $frameRate = $outputWanted->{'frame_rate'}; 261 | } 262 | 263 | $formattedOptions = ""; 264 | if (isset($outputWanted->{'preset_values'}->{'video_codec_options'})) { 265 | $formattedOptions = 266 | $this->set_output_video_codec_options($outputWanted->{'preset_values'}->{'video_codec_options'}); 267 | } 268 | 269 | $watermarkOptions = ""; 270 | // Process options for watermark 271 | if (isset($outputWanted->{'watermark'}) && $outputWanted->{'watermark'}) { 272 | $watermarkOptions = 273 | $this->get_watermark_options( 274 | $tmpInputPath, 275 | $outputWanted->{'watermark'}); 276 | } 277 | 278 | // Create FFMpeg arguments 279 | $ffmpegArgs = " -i $inputFilePath -y -threads 0"; 280 | $ffmpegArgs .= " -vf scale=$size"; 281 | $ffmpegArgs .= " -vcodec $videoCodec"; 282 | $ffmpegArgs .= " -acodec $audioCodec"; 283 | $ffmpegArgs .= " -b:v $videoBitrate"; 284 | $ffmpegArgs .= " -b:a $audioBitrate"; 285 | $ffmpegArgs .= " -r $frameRate"; 286 | $ffmpegArgs .= " $formattedOptions"; 287 | $ffmpegArgs .= " $watermarkOptions"; 288 | 289 | // Append output filename to path 290 | $outputFilesPath .= "/" . $outputWanted->{'output_file_info'}['basename']; 291 | // Final command 292 | $ffmpegCmd = "ffmpeg $ffmpegArgs $outputFilesPath"; 293 | 294 | return ($ffmpegCmd); 295 | } 296 | 297 | // Craft FFMpeg command to generate thumbnails 298 | private function craft_ffmpeg_cmd_thumb( 299 | $tmpInputPath, 300 | $inputFilePath, 301 | $outputFilesPath, 302 | $metadata, 303 | $outputWanted) 304 | { 305 | // FIXME: Use $metadata to improve the FFMpeg command 306 | // inputAssetInfo contains FFprobe output 307 | 308 | $frameOptions = ""; 309 | $outputFileInfo = pathinfo($outputWanted->{'file'}); 310 | $inputFilePath = escapeshellarg($inputFilePath); 311 | if ($outputWanted->{'mode'} == 'snapshot') 312 | { 313 | $snapshot_sec = self::SNAPSHOT_SEC_DEFAULT; 314 | if (isset($outputWanted->{'snapshot_sec'}) && 315 | $outputWanted->{'snapshot_sec'} > 0) { 316 | $snapshot_sec = $outputWanted->{'snapshot_sec'}; 317 | } 318 | 319 | $time = gmdate("H:i:s", $snapshot_sec) . ".000"; 320 | $outputFilesPath .= "/" . $outputFileInfo['basename']; 321 | $frameOptions = " -ss $time -vframes 1"; 322 | } 323 | else if ($outputWanted->{'mode'} == 'intervals') 324 | { 325 | $intervals = self::INTERVALS_DEFAULT; 326 | if (isset($outputWanted->{'intervals'}) && 327 | $outputWanted->{'intervals'} > 0) { 328 | $intervals = $outputWanted->{'intervals'}; 329 | } 330 | 331 | $outputFilesPath .= "/" . $outputFileInfo['filename'] . "%06d." 332 | . $outputFileInfo['extension']; 333 | $frameOptions = " -vf fps=fps=1/$intervals"; 334 | } 335 | 336 | // Create FFMpeg arguments 337 | $ffmpegArgs = " -i $inputFilePath -y -threads 0"; 338 | $ffmpegArgs .= " -vf scale=" . $outputWanted->{'size'}; 339 | $ffmpegArgs .= " $frameOptions -f image2 -q:v 8"; 340 | 341 | // Final command 342 | $ffmpegCmd = "ffmpeg $ffmpegArgs $outputFilesPath"; 343 | 344 | return ($ffmpegCmd); 345 | } 346 | 347 | // Get watermark info to generate overlay options for ffmpeg 348 | private function get_watermark_options( 349 | $tmpInputPath, 350 | $watermarkOptions) 351 | { 352 | // Get info about the video in order to save the watermark in same location 353 | $watermarkFileInfo = pathinfo($watermarkOptions->{'file'}); 354 | $watermarkPath = $tmpInputPath."/".$watermarkFileInfo['basename']; 355 | $newWatermarkPath = $tmpInputPath."/new-".$watermarkFileInfo['basename']; 356 | 357 | // Get watermark image from S3 358 | $s3Output = $this->s3Utils->get_file_from_s3( 359 | $watermarkOptions->{'bucket'}, 360 | $watermarkOptions->{'file'}, 361 | $watermarkPath); 362 | 363 | $this->cpeLogger->logOut("INFO", 364 | basename(__FILE__), 365 | $s3Output['msg'], 366 | $this->logKey); 367 | 368 | // Transform watermark for opacity 369 | $convertCmd = "convert $watermarkPath -alpha on -channel A -evaluate Multiply " . $watermarkOptions->{'opacity'} . " +channel $newWatermarkPath"; 370 | 371 | try { 372 | $out = $this->executer->execute($convertCmd, 1, 373 | array(1 => array("pipe", "w"), 2 => array("pipe", "w")), 374 | false, false, 375 | false, 1); 376 | } 377 | catch (\Exception $e) { 378 | $this->cpeLogger->logOut( 379 | "ERROR", 380 | basename(__FILE__), 381 | "Execution of command '".$convertCmd."' failed", 382 | $this->logKey 383 | ); 384 | return false; 385 | } 386 | 387 | // Any error ? 388 | if (isset($out['outErr']) && $out['outErr'] != "" && 389 | (!file_exists($newWatermarkPath) || !filesize($newWatermarkPath))) { 390 | throw new CpeSdk\CpeException( 391 | "Error transforming watermark file '$watermarkPath'!", 392 | self::WATERMARK_ERROR); 393 | } 394 | 395 | // Format options for FFMpeg 396 | $size = $watermarkOptions->{'size'}; 397 | $positions = $this->get_watermark_position($watermarkOptions); 398 | $formattedOptions = "-vf \"movie=$newWatermarkPath, scale=$size [wm]; [in][wm] overlay=" . $positions['x'] . ':' . $positions['y'] . " [out]\""; 399 | 400 | return ($formattedOptions); 401 | } 402 | 403 | // Generate the command line option to position the watermark 404 | private function get_watermark_position($watermarkOptions) 405 | { 406 | $positions = array('x' => 0, 'y' => 0); 407 | 408 | if ($watermarkOptions->{'x'} >= 0) { 409 | $positions['x'] = $watermarkOptions->{'x'}; 410 | } 411 | if ($watermarkOptions->{'y'} >= 0) { 412 | $positions['y'] = $watermarkOptions->{'y'}; 413 | } 414 | if ($watermarkOptions->{'x'} < 0) { 415 | $positions['x'] = 'main_w-overlay_w' . $watermarkOptions->{'x'}; 416 | } 417 | if ($watermarkOptions->{'y'} < 0) { 418 | $positions['y'] = 'main_h-overlay_h' . $watermarkOptions->{'y'}; 419 | } 420 | 421 | return ($positions); 422 | } 423 | 424 | // Get Video codec options and format the options properly for ffmpeg 425 | private function set_output_video_codec_options($videoCodecOptions) 426 | { 427 | $formattedOptions = ""; 428 | $options = explode(",", $videoCodecOptions); 429 | 430 | foreach ($options as $option) 431 | { 432 | $keyVal = explode("=", $option); 433 | if ($keyVal[0] === 'Profile') { 434 | $formattedOptions .= " -profile:v ".$keyVal[1]; 435 | } else if ($keyVal[0] === 'Level') { 436 | $formattedOptions .= " -level ".$keyVal[1]; 437 | } else if ($keyVal[0] === 'MaxReferenceFrames') { 438 | $formattedOptions .= " -refs ".$keyVal[1]; 439 | } 440 | } 441 | 442 | return ($formattedOptions); 443 | } 444 | 445 | // Verify Ratio and Size of output file to ensure it respect restrictions 446 | // Return the output video size 447 | private function set_output_video_size(&$metadata, $outputWanted) 448 | { 449 | // Handle video size 450 | $size = $outputWanted->{'preset_values'}->{'size'}; 451 | if (isset($outputWanted->{'size'})) { 452 | $size = $outputWanted->{'size'}; 453 | } 454 | 455 | // Ratio check 456 | if (!isset($outputWanted->{'keep_ratio'}) || 457 | $outputWanted->{'keep_ratio'} == 'true') 458 | { 459 | // FIXME: Improve ratio check 460 | 461 | /* $outputRatio = floatval($this->get_ratio($size)); */ 462 | /* $inputRatio = floatval($metadata->{'ratio'}); */ 463 | 464 | /* if ($outputRatio != $inputRatio) */ 465 | /* throw new CpeSdk\CpeException( */ 466 | /* "Output video ratio is different from input video: input_ratio: '$inputRatio' / output_ratio: '$outputRatio'. 'keep_ratio' option is enabled (default). Disable it to allow ratio change.", */ 467 | /* self::RATIO_ERROR */ 468 | /* ); */ 469 | } 470 | 471 | // Enlargement check 472 | if ($metadata && 473 | (!isset($outputWanted->{'allow_upscale'}) 474 | || $outputWanted->{'allow_upscale'} == 'false')) 475 | { 476 | $metadata['size'] = $metadata['video']['resolution']; 477 | $inputSize = $metadata['size']; 478 | $inputSizeSplit = explode("x", $inputSize); 479 | $outputSizeSplit = explode("x", $size); 480 | $width = $outputSizeSplit[0]; 481 | $height = $outputSizeSplit[1]; 482 | 483 | // We have a rotation. We flip width and height 484 | if ($metadata['video']['tags'] && 485 | $metadata['video']['tags']['rotate'] && 486 | ($metadata['video']['tags']['rotate'] == 90 || 487 | $metadata['video']['tags']['rotate'] == -90)) { 488 | $width = $outputSizeSplit[1]; 489 | $height = $outputSizeSplit[0]; 490 | } 491 | 492 | if (intval($width) > intval($inputSizeSplit[0]) || 493 | intval($height) > intval($inputSizeSplit[1])) { 494 | $this->cpeLogger->logOut( 495 | "INFO", 496 | basename(__FILE__), 497 | "Requested transcode size is bigger than the original. `allow_upscale` option not provided", 498 | $this->logKey 499 | ); 500 | $size = $width . "x" . $height; 501 | } 502 | } 503 | 504 | return (str_replace("x",":", $size)); 505 | } 506 | 507 | // REad ffmpeg output and calculate % progress 508 | // This is a callback called from 'CommandExecuter.php' 509 | // $out and $outErr contain FFmpeg output 510 | public function capture_progression($params, $out, $outErr) 511 | { 512 | $progress = 0; 513 | $done = 0; 514 | $duration = $params['duration']; 515 | $output = $params['output']; 516 | 517 | // # get the current time 518 | preg_match_all("/time=(.*?) bitrate/", $outErr, $matches); 519 | 520 | $last = array_pop($matches); 521 | // # this is needed if there is more than one match 522 | if (is_array($last)) { 523 | $last = array_pop($last); 524 | } 525 | 526 | // Perform Time transformation to get seconds 527 | $ar = array_reverse(explode(":", $last)); 528 | $done = floatval($ar[0]); 529 | if (!empty($ar[1])) { 530 | $done += intval($ar[1]) * 60; 531 | } 532 | if (!empty($ar[2])) { 533 | $done += intval($ar[2]) * 60 * 60; 534 | } 535 | 536 | // # finally, progress is easy 537 | if ($done && $duration) { 538 | $progress = round(($done/$duration)*100); 539 | } 540 | 541 | $this->cpeLogger->logOut( 542 | "INFO", 543 | basename(__FILE__), 544 | "Progress: $done / $progress%", 545 | $this->logKey 546 | ); 547 | 548 | // Send heartbeat and progress data 549 | $this->activityObj->activityHeartbeat( 550 | [ 551 | "output" => $output, 552 | "duration" => $duration, 553 | "done" => $done, 554 | "progress" => $progress 555 | ] 556 | ); 557 | } 558 | 559 | // Combine preset and custom output settings to generate output settings 560 | public function get_preset_values($output_wanted) 561 | { 562 | if (!$output_wanted) { 563 | throw new CpeSdk\CpeException("No output data provided to transcoder !", 564 | self::NO_OUTPUT); 565 | } 566 | 567 | if (!isset($output_wanted->{"preset"})) { 568 | throw new CpeSdk\CpeException("No preset selected for output !", 569 | self::BAD_PRESETS_DIR); 570 | } 571 | 572 | $preset = $output_wanted->{"preset"}; 573 | $presetPath = __DIR__ . '/../../../presets/'; 574 | 575 | if (!($presetContent = file_get_contents($presetPath.$preset.".json"))) { 576 | throw new CpeSdk\CpeException("Can't open preset file !", 577 | self::OPEN_PRESET_FAILED); 578 | } 579 | 580 | if (!($decodedPreset = json_decode($presetContent))) { 581 | throw new CpeSdk\CpeException("Bad preset JSON format !", 582 | self::BAD_PRESET_FORMAT); 583 | } 584 | 585 | return ($decodedPreset); 586 | } 587 | 588 | // Check if the preset exists 589 | public function validate_preset($output) 590 | { 591 | if (!isset($output->{"preset"})) { 592 | throw new CpeSdk\CpeException("No preset selected for output !", 593 | self::BAD_PRESETS_DIR); 594 | } 595 | 596 | $preset = $output->{"preset"}; 597 | $presetPath = __DIR__ . '/../../../presets/'; 598 | 599 | if (!($files = scandir($presetPath))) { 600 | throw new CpeSdk\CpeException("Unable to open preset directory '$presetPath' !", 601 | self::BAD_PRESETS_DIR); 602 | } 603 | 604 | foreach ($files as $presetFile) 605 | { 606 | if ($presetFile === '.' || $presetFile === '..') { continue; } 607 | 608 | if (is_file("$presetPath/$presetFile")) 609 | { 610 | if ($preset === pathinfo($presetFile)["filename"]) 611 | { 612 | if (!($presetContent = file_get_contents("$presetPath/$presetFile"))) { 613 | throw new CpeSdk\CpeException("Can't open preset file '$presetPath/$presetFile'!", 614 | self::OPEN_PRESET_FAILED); 615 | } 616 | 617 | if (!($decodedPreset = json_decode($presetContent))) { 618 | throw new CpeSdk\CpeException("Bad preset JSON format '$presetPath/$presetFile'!", 619 | self::BAD_PRESET_FORMAT); 620 | } 621 | 622 | return true; 623 | } 624 | } 625 | } 626 | 627 | throw new CpeSdk\CpeException("Unkown preset file '$preset' !", 628 | self::UNKNOWN_PRESET); 629 | } 630 | } 631 | -------------------------------------------------------------------------------- /src/scripts/getFromS3.php: -------------------------------------------------------------------------------- 1 | --file --to \n"); 12 | echo("--help, -h: Print this help\n"); 13 | echo("--bucket : Name of the S3 bucket\n"); 14 | echo("--file : Name of the file in the S3 bucket\n"); 15 | echo("--to : Full path to file where to save. You can override original filename.\n"); 16 | echo("--force: Force download even if file exists locally\n\n"); 17 | exit(0); 18 | } 19 | 20 | function check_input_parameters($options) 21 | { 22 | if (!count($options) || isset($options['h']) || 23 | isset($options['help'])) 24 | usage(); 25 | 26 | if (!isset($options['bucket']) || !isset($options['file']) || 27 | !isset($options['to'])) 28 | throw new \SA\CpeSdk\CpeException("Missing mandatory parameter!"); 29 | } 30 | 31 | $options = getopt("h", array("bucket:", "file:", "to:", "force::", "help::")); 32 | check_input_parameters($options); 33 | 34 | // If local file already exists. We don't download unless --force 35 | if (!isset($options['force']) && 36 | file_exists($options['to']) && 37 | filesize($options['to'])) 38 | { 39 | $out = [ "status" => "SUCCESS", 40 | "msg" => "[".__FILE__."] Using local copy: '" . $options['to'] . "'" ]; 41 | print json_encode($out)."\n"; 42 | exit(0); 43 | } 44 | 45 | # Check if preper env vars are setup 46 | if (!($region = getenv("AWS_DEFAULT_REGION"))) 47 | throw new \SA\CpeSdk\CpeException("Set 'AWS_DEFAULT_REGION' environment variable!"); 48 | 49 | // Get S3 client 50 | $s3 = new \Aws\S3\S3Client([ 51 | 'version' => 'latest', 52 | 'region' => $region 53 | ]); 54 | 55 | // Download and Save object to a local file. 56 | $res = $s3->getObject(array( 57 | 'Bucket' => $options['bucket'], 58 | 'Key' => ltrim($options['file'], '/'), 59 | 'SaveAs' => $options['to'] 60 | )); 61 | 62 | $out = [ "status" => "SUCCESS", 63 | "msg" => "[".__FILE__."] Download '" . $options['bucket'] . "/" . $options['file'] . "' successful !" ]; 64 | 65 | print json_encode($out)."\n"; 66 | -------------------------------------------------------------------------------- /src/scripts/putInS3.php: -------------------------------------------------------------------------------- 1 | --file --from \n"); 12 | echo("--help, -h: Print this help\n"); 13 | echo("--bucket : Name of the S3 bucket\n"); 14 | echo("--file : Name of the file to create in bucket. You can override local filename.\n"); 15 | echo("--from : Full path to file to send to S3\n"); 16 | echo("--rrs: Activate type of storage in S3: REDUCED_REDUNDANCY\n"); 17 | echo("--encrypt: Activate Server encryption: AES256\n\n"); 18 | exit(0); 19 | } 20 | 21 | function check_input_parameters(&$options) 22 | { 23 | if (!count($options) || isset($options['h']) || 24 | isset($options['help'])) 25 | usage(); 26 | 27 | if (!isset($options['bucket']) || !isset($options['file']) || 28 | !isset($options['from'])) 29 | { 30 | print "Error: Missing mandatory parameter !\n"; 31 | usage(); 32 | } 33 | 34 | $options['bucket'] = rtrim( $options['bucket'], "/"); 35 | } 36 | 37 | $options = getopt("h", [ 38 | "bucket:", 39 | "file:", 40 | "from:", 41 | "force::", 42 | "help::", 43 | "rrs::", 44 | "encrypt::"]); 45 | check_input_parameters($options); 46 | 47 | try { 48 | # Check if preper env vars are setup 49 | if (!($region = getenv("AWS_DEFAULT_REGION"))) 50 | throw new CpeSdk\CpeException("Set 'AWS_DEFAULT_REGION' environment variable!"); 51 | 52 | // Get S3 client 53 | $s3 = new \Aws\S3\S3Client([ 54 | 'version' => 'latest', 55 | 'region' => $region 56 | ]); 57 | 58 | $params = array( 59 | 'Bucket' => $options['bucket'], 60 | 'Key' => ltrim($options['file'], '/'), 61 | 'SourceFile' => $options['from'], 62 | ); 63 | 64 | // StorageClass and Encryption ? 65 | if (isset($options['rrs'])) 66 | $params['StorageClass'] = 'REDUCED_REDUNDANCY'; 67 | if (isset($options['encrypt'])) 68 | $params['ServerSideEncryption'] = 'AES256'; 69 | 70 | // Upload and Save file to S3 71 | $s3->putObject($params); 72 | 73 | // Print JSON error output 74 | print json_encode([ "status" => "SUCCESS", 75 | "msg" => "[".__FILE__."] Upload '" . $options['from'] . "' to '" . $options['bucket'] . "/" . $options['file'] . "' successful !" ]); 76 | } 77 | catch (Exception $e) { 78 | $err = "Unable to put file '" . $options['from'] . "' into S3: '" . $options['bucket'] . "/" . $options['file'] . "'! " . $e->getMessage(); 79 | 80 | // Print JSON error output 81 | print json_encode([ "status" => "ERROR", 82 | "msg" => "[".__FILE__."] $err" ]); 83 | 84 | die("[".__FILE__."] $err"); 85 | } 86 | -------------------------------------------------------------------------------- /src/utils/CommandExecuter.php: -------------------------------------------------------------------------------- 1 | cpeLogger = $cpeLogger; 22 | $this->logKey = $logKey; 23 | } 24 | 25 | public function execute( 26 | $cmd, 27 | $sleep = 1, 28 | $descriptors = array( 29 | 1 => array("pipe", "w"), 30 | 2 => array("pipe", "w") 31 | ), 32 | $progressCallback = null, 33 | $progressCallbackParams = null, 34 | $showProgress = false, 35 | $callbackTurns = 0, 36 | $logKey = null) 37 | { 38 | if ($logKey) 39 | $this->logKey = $logKey; 40 | 41 | $this->cpeLogger->logOut("INFO", basename(__FILE__), "Executing: $cmd", $this->logKey); 42 | 43 | // Start execution of $cmd 44 | if (!($process = proc_open($cmd, $descriptors, $pipes)) || 45 | !is_resource($process)) { 46 | $this->cpeLogger->logOut("ERROR", 47 | basename(__FILE__), "Unable to execute command:\n$cmd", 48 | $this->logKey); 49 | throw new CpeSdk\CpeException("Unable to execute command:\n$cmd\n", 50 | self::EXEC_FAILED); 51 | } 52 | 53 | // Set the pipes as non-blocking 54 | if (isset($descriptors[1]) && 55 | $descriptors[1]) { 56 | stream_set_blocking($pipes[1], FALSE); 57 | } 58 | if (isset($descriptors[2]) && 59 | $descriptors[2]) { 60 | stream_set_blocking($pipes[2], FALSE); 61 | } 62 | 63 | $i = 0; 64 | 65 | // Used to store all output 66 | $allOut = ""; 67 | $allOutErr = ""; 68 | 69 | // Check process status at every turn 70 | do { 71 | sleep($sleep); 72 | 73 | // If callback only after N turns 74 | if ( !$callbackTurns || in_array($i, array(0, $callbackTurns)) ) 75 | { 76 | if ($showProgress) { 77 | echo ".\n"; 78 | } 79 | 80 | // Call user provided callback. 81 | // Callback should be an array as per doc here: 82 | // http://www.php.net/manual/en/language.types.callable.php 83 | // Type 3: Object method call 84 | if (isset($progressCallback) && $progressCallback) { 85 | call_user_func($progressCallback, $progressCallbackParams, 86 | $allOut, $allOutErr); 87 | } 88 | 89 | $i = 0; 90 | } 91 | 92 | // Get latest status 93 | $procStatus = proc_get_status($process); 94 | if ($showProgress) { 95 | echo "."; 96 | flush(); 97 | } 98 | 99 | // Read prog output 100 | if (isset($pipes[1]) && $pipes[1]) { 101 | $out = stream_get_contents($pipes[1], -1); 102 | $allOut .= $out; 103 | } 104 | 105 | // Read prog errors 106 | if (isset($pipes[2]) && $pipes[2]) { 107 | $outErr = stream_get_contents($pipes[2], -1); 108 | $allOutErr .= $outErr; 109 | } 110 | 111 | $i++; 112 | } while ($procStatus['running']); 113 | 114 | if (isset($pipes[1])) 115 | fclose($pipes[1]); 116 | if (isset($pipes[2])) 117 | fclose($pipes[2]); 118 | 119 | if ($procStatus['exitcode'] > 0) 120 | { 121 | $this->cpeLogger->logOut("ERROR", 122 | basename(__FILE__), 123 | "Can't execute: $cmd. Exit Code: ".$procStatus['exitcode'], 124 | $this->logKey); 125 | if ($allOut) { 126 | $this->cpeLogger->logOut("ERROR", 127 | basename(__FILE__), "COMMAND STDOUT: ".$allOut, 128 | $this->logKey); 129 | $allOut = null; 130 | } 131 | if ($allOutErr) 132 | $this->cpeLogger->logOut("ERROR", 133 | basename(__FILE__), "COMMAND STDERR: ".$allOutErr, 134 | $this->logKey); 135 | } 136 | 137 | if ($showProgress) { 138 | echo "\n"; 139 | } 140 | 141 | // Process is over 142 | proc_close($process); 143 | 144 | return array('out' => $allOut, 'outErr' => $allOutErr); 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /src/utils/S3Utils.php: -------------------------------------------------------------------------------- 1 | cpeLogger = new CpeSdk\CpeLogger(null, 'S3Utils'); 27 | $this->cpeLogger = $cpeLogger; 28 | } 29 | 30 | // Get a file from S3 using external script localted in "scripts" folder 31 | public function get_file_from_s3( 32 | $bucket, 33 | $filename, 34 | $saveFileTo, 35 | $callback = null, 36 | $callbackParams = null, 37 | $logKey = null) 38 | { 39 | $cmd = "php " . __DIR__ . self::GET_FROM_S3; 40 | $cmd .= " --bucket $bucket"; 41 | $cmd .= " --file $filename"; 42 | $cmd .= " --to $saveFileTo"; 43 | 44 | // HAndle execution 45 | return ($this->handle_s3_ops( 46 | self::GET_FROM_S3, 47 | $cmd, 48 | $callback, 49 | $callbackParams, 50 | $logKey)); 51 | } 52 | 53 | // Get a file from S3 using external script localted in "scripts" folder 54 | public function put_file_into_s3( 55 | $bucket, 56 | $filename, 57 | $pathToFileToSend, 58 | $options, 59 | $callback = null, 60 | $callbackParams = null, 61 | $logKey = null) 62 | { 63 | $cmd = "php " . __DIR__ . self::PUT_IN_S3; 64 | $cmd .= " --bucket $bucket"; 65 | $cmd .= " --file $filename"; 66 | $cmd .= " --from $pathToFileToSend"; 67 | if ($options['rrs']) 68 | $cmd .= " --rrs"; 69 | if ($options['encrypt']) 70 | $cmd .= " --encrypt"; 71 | 72 | // HAndle execution 73 | return ($this->handle_s3_ops( 74 | self::PUT_IN_S3, 75 | $cmd, 76 | $callback, 77 | $callbackParams, 78 | $logKey) 79 | ); 80 | } 81 | 82 | // Execute S3 $cmd and capture output 83 | private function handle_s3_ops($caller, $cmd, $callback, $callbackParams, $logKey) 84 | { 85 | // Use executer to start external S3 script 86 | // The array request listening to 1 (STDOUT) and 2 (STDERR) 87 | $executer = new CommandExecuter($this->cpeLogger, $logKey); 88 | $out = $executer->execute( 89 | $cmd, 90 | 1, 91 | array(1 => array("pipe", "w"), 92 | 2 => array("pipe", "w")), 93 | $callback, 94 | $callbackParams, 95 | true, 96 | 2 97 | ); 98 | 99 | if ($out['outErr']) 100 | throw new CpeSdk\CpeException($out['outErr'], 101 | self::S3_OPS_FAILED); 102 | 103 | if (!$out['out']) 104 | throw new CpeSdk\CpeException("Script '$caller' didn't return any data !", 105 | self::NO_OUTPUT_DATA); 106 | 107 | if (!($decoded = json_decode($out['out'], true))) 108 | throw new CpeSdk\CpeException($out['out'], 109 | self::S3_OPS_FAILED); 110 | 111 | if ($decoded["status"] == "ERROR") 112 | throw new CpeSdk\CpeException($decoded["msg"], 113 | self::S3_OPS_FAILED); 114 | 115 | return ($decoded); 116 | } 117 | 118 | } -------------------------------------------------------------------------------- /state_machines/SATranscodeAssets.json: -------------------------------------------------------------------------------- 1 | { 2 | "Comment": "Simple Transcode", 3 | "StartAt": "TranscodeAsset", 4 | "States": { 5 | "TranscodeAsset": { 6 | "Type": "Task", 7 | "Resource": "arn:aws:states:eu-west-1:xxxxxxxx:activity:TranscodeAsset", 8 | "TimeoutSeconds": 28800, 9 | "HeartbeatSeconds": 30, 10 | "End": true 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /state_machines/SAValidateTranscodeAssets.json: -------------------------------------------------------------------------------- 1 | { 2 | "Comment": "Transcode a video asset into thumbnails and proxy mp4", 3 | "StartAt": "ValidateAsset", 4 | "States": { 5 | "ValidateAsset": { 6 | "Type": "Task", 7 | "Next": "TranscodeAsset", 8 | "Resource": "arn:aws:states:eu-west-1:xxxxx:activity:ValidateAsset", 9 | "TimeoutSeconds": 300, 10 | "HeartbeatSeconds": 30 11 | }, 12 | "TranscodeAsset": { 13 | "Type": "Task", 14 | "Resource": "arn:aws:states:eu-west-1:xxxxx:activity:TranscodeAsset", 15 | "TimeoutSeconds": 28800, 16 | "HeartbeatSeconds": 30, 17 | "End": true 18 | } 19 | } 20 | } 21 | --------------------------------------------------------------------------------