├── .github └── workflows │ └── autocompile-main.yml ├── .gitignore ├── LICENSE ├── README.md ├── build └── version.go ├── encoder ├── FPSCap.go ├── audio │ ├── audio.go │ ├── decoder.go │ ├── fdkaac.go │ ├── ffmpeg.go │ ├── fhgaac.go │ ├── filters.go │ └── qaac.go ├── keyint.go ├── reschooser.go └── video.go ├── go.mod ├── go.sum ├── hardware └── scaler.go ├── main.go ├── metadata ├── analyzer.go ├── bitratecalc.go ├── outmetadata.go ├── passthrough.go ├── targetselect.go ├── timecheck.go └── times.go ├── package.bat ├── scaler └── genparams.go ├── settings ├── encoding.go ├── ffenccheck.go ├── general.go ├── generator.go ├── manager.go └── settings.go ├── uploader ├── catbox.go └── uploader.go └── utils ├── updatecheck.go └── utils.go /.github/workflows/autocompile-main.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: 4 | push: 5 | branches: [ main, dev ] 6 | pull_request: 7 | branches: [ main, dev ] 8 | 9 | jobs: 10 | 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | 16 | - name: Set up Go 17 | uses: actions/setup-go@v2 18 | with: 19 | go-version: 1.17 20 | 21 | - name: Build - Windows 64bit 22 | run: GOOS=windows GOARCH=amd64 go build -trimpath -ldflags "-s -w" -o "discordcompressor-win64.exe" -v 23 | 24 | - name: Build - Windows 32bit 25 | run: GOOS=windows GOARCH=386 go build -trimpath -ldflags "-s -w" -o "discordcompressor-win32.exe" -v 26 | 27 | - name: Build - Linux 64bit 28 | run: GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w" -o "discordcompressor-linux64" -v 29 | 30 | - name: Build - Linux 32bit 31 | run: GOOS=linux GOARCH=386 go build -trimpath -ldflags "-s -w" -o "discordcompressor-linux32" -v 32 | 33 | - name: Upload 34 | uses: actions/upload-artifact@master 35 | with: 36 | name: Windows 64bit 37 | path: discordcompressor-win64.exe 38 | 39 | - name: Upload 40 | uses: actions/upload-artifact@master 41 | with: 42 | name: Windows 32bit 43 | path: discordcompressor-win32.exe 44 | 45 | - name: Upload 46 | uses: actions/upload-artifact@master 47 | with: 48 | name: Linux 64bit 49 | path: discordcompressor-linux64 50 | 51 | - name: Upload 52 | uses: actions/upload-artifact@master 53 | with: 54 | name: Linux 32bit 55 | path: discordcompressor-linux32 56 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.exe 2 | *.json 3 | .idea/ 4 | *.log -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DiscordCompressor 2 | 3 | A small program in Go that efficiently compresses videos using FFmpeg to a certain filesize. 4 | 5 | ## Dependencies 6 | 7 | [FFmpeg](https://ffmpeg.org) 8 | 9 | ## Usage 10 | 11 | `discordcompressor ` 12 | 13 | * `-o filename` - Sets the output filename, extension is automatically added 14 | * `-size 25` - Sets the target size in MB 15 | * `-last 10` - Compresses the last x seconds of a video 16 | * `-ss 15` - Sets the start time of the video in seconds 17 | * `-t 10` - Sets the time to encode after the start of the file or `-ss` in seconds 18 | * `-mixaudio` - Mixes all audio tracks into one 19 | * `-normaudio` - Normalizes audio volume (use if the input video's audio is very quiet, loud or uneven) 20 | * `-settings string` - Selects the settings file if you have multiple, or generates a new one with the chosen suffix. 21 | * `-debug` - Shows extra information. Please use when reporting bugs, or if you're just curious. 22 | * `-c:v` - Forces a certain video encoder, specified in settings.json 23 | * `-c:a` - Forces a certain audio encoder, specified in settings.json 24 | * `-f` - Forces a certain container, for example, `-f mkv` will output a .mkv file. 25 | 26 | Please check the wiki to get tips on how to make discordcompressor even more efficient without a performance penalty, or much faster. 27 | Settings and logs are located in %appdata%\vladaad\dc on Windows and ~/.config/vladaad/dc on Linux 28 | 29 | ## Compiling from source 30 | 31 | You need [Go 1.16](https://golang.org/dl/) or newer 32 | 33 | Afterwards, run `go build` -------------------------------------------------------------------------------- /build/version.go: -------------------------------------------------------------------------------- 1 | package build 2 | 3 | var VERSION = "dev" 4 | var BUILD = "static" 5 | -------------------------------------------------------------------------------- /encoder/FPSCap.go: -------------------------------------------------------------------------------- 1 | package encoder 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/settings" 5 | "strconv" 6 | ) 7 | 8 | func calculateFPS(video *settings.Vid) (*settings.FPS, bool) { 9 | modified := false // This variable is for accurate detection if FPS was changed, float fuckery? was making -vf fps=25/1 when input was 25.0000 10 | fps := new(settings.FPS) 11 | fps.D, fps.N = video.Input.FPS.D, video.Input.FPS.N 12 | for { 13 | if float64(fps.N)/float64(fps.D) > float64(video.Output.Settings.MaxFPS)+1 { // allow for leniency 14 | if settings.Encoding.HalveFPS { 15 | fps.D *= 2 16 | modified = true 17 | } else { 18 | fps.N = video.Output.Settings.MaxFPS 19 | fps.D = 1 20 | modified = true 21 | break 22 | } 23 | } else { 24 | break 25 | } 26 | } 27 | return fps, modified 28 | } 29 | 30 | func fpsFilter(video *settings.Vid) string { 31 | fps := video.Output.FPS 32 | if video.Input.FPS != video.Output.FPS { 33 | var str string 34 | expr := strconv.Itoa(fps.N) 35 | expr += "/" 36 | expr += strconv.Itoa(fps.D) 37 | str = "fps=" + expr 38 | return str 39 | } else { 40 | return "" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /encoder/audio/audio.go: -------------------------------------------------------------------------------- 1 | package audio 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/settings" 5 | "log" 6 | "os" 7 | "sync" 8 | ) 9 | 10 | func GenFilename(video *settings.Vid) string { 11 | filename := video.UUID + "." 12 | switch video.Output.AEncoder.Type { 13 | case "ffmpeg": 14 | filename += video.Output.Settings.Container 15 | case "qaac", "fdkaac", "fhgaac": 16 | filename += "m4a" 17 | } 18 | return filename 19 | } 20 | func EncodeAudio(video *settings.Vid, wg *sync.WaitGroup) *settings.Vid { 21 | defer wg.Done() 22 | dec := decodeAudio(video) 23 | switch video.Output.AEncoder.Type { 24 | case "ffmpeg": 25 | encFFmpeg(video, dec) 26 | case "fdkaac": 27 | encFDK(video, dec) 28 | case "fhgaac": 29 | encFHG(video, dec) 30 | case "qaac": 31 | encQaac(video, dec) 32 | } 33 | 34 | if !settings.Encoding.FastMode { 35 | video.Output.Bitrate.Audio = getBitrate(video) 36 | video.Output.Bitrate.Video = video.Output.Bitrate.Total - video.Output.Bitrate.Audio 37 | } else { 38 | log.Println("Audio encoding finished!") 39 | } 40 | return video 41 | } 42 | 43 | func getBitrate(video *settings.Vid) int { 44 | info, err := os.Stat(video.Output.AudioFile) 45 | if err != nil { 46 | panic("Failed to get audio bitrate") 47 | } 48 | return int(float64(info.Size()*8) / video.Time.Duration) 49 | } 50 | -------------------------------------------------------------------------------- /encoder/audio/decoder.go: -------------------------------------------------------------------------------- 1 | package audio 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/metadata" 5 | "github.com/vladaad/discordcompressor/settings" 6 | "io" 7 | "log" 8 | "os/exec" 9 | ) 10 | 11 | func decodeAudio(video *settings.Vid) io.ReadCloser { 12 | var options []string 13 | 14 | // input 15 | options = append(options, "-loglevel", "warning", "-stats") 16 | options = append(options, metadata.AppendTimes(video)...) 17 | options = append(options, "-i", video.InFile) 18 | 19 | options = append(options, "-map_metadata", "-1") 20 | options = append(options, "-map_chapters", "-1") 21 | 22 | // filters 23 | filters, mapping := getFilters(video) 24 | if filters != "" { 25 | options = append(options, "-filter_complex", filters) 26 | } 27 | options = append(options, "-map", mapping) 28 | 29 | // output format 30 | options = append(options, "-c:a", "pcm_s32le") 31 | if video.Input.AChannels > 2 { 32 | options = append(options, "-ac", "2") 33 | } 34 | 35 | options = append(options, "-f", "wav", "-") 36 | 37 | if settings.Debug { 38 | log.Println(options) 39 | } 40 | 41 | cmd := exec.Command(settings.General.FFmpegExecutable, options...) 42 | pipe, _ := cmd.StdoutPipe() 43 | err := cmd.Start() 44 | if err != nil { 45 | panic(err) 46 | } 47 | 48 | return pipe 49 | } 50 | -------------------------------------------------------------------------------- /encoder/audio/fdkaac.go: -------------------------------------------------------------------------------- 1 | package audio 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/settings" 5 | "io" 6 | "log" 7 | "os" 8 | "os/exec" 9 | "strconv" 10 | "strings" 11 | ) 12 | 13 | func encFDK(video *settings.Vid, input io.ReadCloser) { 14 | var options []string 15 | encoderSettings := strings.Split(video.Output.AEncoder.Args, " ") 16 | // input 17 | options = append(options, "-") 18 | // encoding 19 | options = append(options, encoderSettings...) 20 | if !video.Output.AEncoder.TVBR { 21 | options = append(options, "-b", strconv.Itoa(video.Output.Bitrate.Audio)) 22 | } 23 | // output 24 | options = append(options, "-o", video.Output.AudioFile) 25 | 26 | if settings.Debug { 27 | log.Println(options) 28 | } 29 | 30 | // running 31 | cmd := exec.Command(settings.General.FDKaacExecutable, options...) 32 | 33 | cmd.Stdin = input 34 | 35 | if !settings.Encoding.FastMode { 36 | cmd.Stdout = os.Stdout 37 | cmd.Stderr = os.Stderr 38 | } 39 | 40 | err := cmd.Start() 41 | if err != nil { 42 | panic(err) 43 | } 44 | err = cmd.Wait() 45 | if err != nil { 46 | panic(err) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /encoder/audio/ffmpeg.go: -------------------------------------------------------------------------------- 1 | package audio 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/settings" 5 | "io" 6 | "log" 7 | "os" 8 | "os/exec" 9 | "strconv" 10 | "strings" 11 | ) 12 | 13 | func encFFmpeg(video *settings.Vid, input io.ReadCloser) { 14 | var options []string 15 | encoderSettings := strings.Split(video.Output.AEncoder.Args, " ") 16 | // input 17 | options = append(options, "-loglevel", "quiet", "-stats") 18 | options = append(options, "-i", "-") 19 | // encoding 20 | options = append(options, encoderSettings...) 21 | if !video.Output.AEncoder.TVBR { 22 | options = append(options, "-b:a", strconv.Itoa(video.Output.Bitrate.Audio)) 23 | } 24 | options = append(options, "-map", "0:a:0") 25 | // output 26 | options = append(options, video.Output.AudioFile) 27 | 28 | if settings.Debug { 29 | log.Println(options) 30 | } 31 | 32 | // running 33 | cmd := exec.Command(settings.General.FFmpegExecutable, options...) 34 | 35 | cmd.Stdin = input 36 | 37 | if !settings.Encoding.FastMode { 38 | cmd.Stdout = os.Stdout 39 | cmd.Stderr = os.Stderr 40 | } 41 | 42 | err := cmd.Start() 43 | if err != nil { 44 | panic(err) 45 | } 46 | err = cmd.Wait() 47 | if err != nil { 48 | panic(err) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /encoder/audio/fhgaac.go: -------------------------------------------------------------------------------- 1 | package audio 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/settings" 5 | "io" 6 | "log" 7 | "os" 8 | "os/exec" 9 | "strconv" 10 | "strings" 11 | ) 12 | 13 | func encFHG(video *settings.Vid, input io.ReadCloser) { 14 | var options []string 15 | var encoderSettings []string 16 | if video.Output.AEncoder.Args != "" { 17 | encoderSettings = strings.Split(video.Output.AEncoder.Args, " ") 18 | } 19 | 20 | // encoding 21 | if encoderSettings != nil { 22 | options = append(options, encoderSettings...) 23 | } 24 | if !video.Output.AEncoder.TVBR { 25 | options = append(options, "--cbr", strconv.Itoa(video.Output.Bitrate.Audio/1024)) 26 | } 27 | // input 28 | options = append(options, "-") 29 | // output 30 | options = append(options, video.Output.AudioFile) 31 | 32 | if settings.Debug { 33 | log.Println(options) 34 | } 35 | 36 | // running 37 | cmd := exec.Command(settings.General.FHGaacExecutable, options...) 38 | 39 | cmd.Stdin = input 40 | 41 | if !settings.Encoding.FastMode { 42 | cmd.Stdout = os.Stdout 43 | cmd.Stderr = os.Stderr 44 | } 45 | 46 | err := cmd.Start() 47 | if err != nil { 48 | panic(err) 49 | } 50 | err = cmd.Wait() 51 | if err != nil { 52 | panic(err) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /encoder/audio/filters.go: -------------------------------------------------------------------------------- 1 | package audio 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/settings" 5 | "strconv" 6 | "strings" 7 | ) 8 | 9 | func getFilters(video *settings.Vid) (filter string, mapping string) { 10 | var filters []string 11 | var inputs []string 12 | // Input 13 | if settings.MixAudio { 14 | for i := 0; i < video.Input.ATracks; i++ { 15 | inputs = append(inputs, "[0:a:"+strconv.Itoa(i)+"]") 16 | } 17 | } else { 18 | inputs = append(inputs, "[0:a:0]") 19 | } 20 | mapping = "0:a:0" 21 | // Audio mixing 22 | if settings.MixAudio { 23 | var filter []string 24 | filter = append(filter, inputs...) 25 | filter = append(filter, "amix=inputs=", strconv.Itoa(video.Input.ATracks)) 26 | filter = append(filter, "[mixed]") 27 | filters = append(filters, strings.Join(filter, "")) 28 | inputs = []string{"[mixed]"} 29 | mapping = inputs[0] 30 | } 31 | // Audio normalization 32 | if settings.NormAudio { 33 | var filter []string 34 | filter = append(filter, inputs...) 35 | filter = append(filter, "dynaudnorm=g=5:f=300:p=0.99") 36 | filter = append(filter, "[norm]") 37 | filters = append(filters, strings.Join(filter, "")) 38 | inputs = []string{"[norm]"} 39 | mapping = inputs[0] 40 | } 41 | 42 | filter = strings.Join(filters, ";") 43 | return filter, mapping 44 | } 45 | -------------------------------------------------------------------------------- /encoder/audio/qaac.go: -------------------------------------------------------------------------------- 1 | package audio 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/settings" 5 | "io" 6 | "log" 7 | "os" 8 | "os/exec" 9 | "strconv" 10 | "strings" 11 | ) 12 | 13 | func encQaac(video *settings.Vid, input io.ReadCloser) { 14 | var options []string 15 | var encoderSettings []string 16 | if video.Output.AEncoder.Args != "" { 17 | encoderSettings = strings.Split(video.Output.AEncoder.Args, " ") 18 | } 19 | 20 | // encoding 21 | if encoderSettings != nil { 22 | options = append(options, encoderSettings...) 23 | } 24 | if !video.Output.AEncoder.TVBR { 25 | options = append(options, "-a", strconv.Itoa(video.Output.Bitrate.Audio)) 26 | } 27 | // input 28 | options = append(options, "-") 29 | // output 30 | options = append(options, "-o", video.Output.AudioFile) 31 | 32 | if settings.Debug { 33 | log.Println(options) 34 | } 35 | 36 | // running 37 | cmd := exec.Command(settings.General.QaacExecutable, options...) 38 | 39 | cmd.Stdin = input 40 | 41 | if !settings.Encoding.FastMode { 42 | cmd.Stdout = os.Stdout 43 | cmd.Stderr = os.Stderr 44 | } 45 | 46 | err := cmd.Start() 47 | if err != nil { 48 | panic(err) 49 | } 50 | err = cmd.Wait() 51 | if err != nil { 52 | panic(err) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /encoder/keyint.go: -------------------------------------------------------------------------------- 1 | package encoder 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/settings" 5 | "strconv" 6 | ) 7 | 8 | func keyint(video *settings.Vid) string { 9 | return strconv.Itoa(video.Output.Encoder.Keyint * video.Output.FPS.N / video.Output.FPS.D) 10 | } 11 | -------------------------------------------------------------------------------- /encoder/reschooser.go: -------------------------------------------------------------------------------- 1 | package encoder 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/metadata" 5 | "github.com/vladaad/discordcompressor/scaler" 6 | "github.com/vladaad/discordcompressor/settings" 7 | "github.com/vladaad/discordcompressor/utils" 8 | "log" 9 | "math" 10 | "os" 11 | "os/exec" 12 | "strconv" 13 | "strings" 14 | ) 15 | 16 | func CalculateResolution(video *settings.Vid) *settings.Vid { 17 | // options 18 | heights := []int{108, 144, 180, 240, 288, 360, 480, 540, 576, 648, 720, 900, 1080, 1152, 1440, 2160} 19 | var options []string 20 | var bdrate int 21 | testRes := math.Min(float64(video.Input.Height), 720) 22 | scalefilter := "fast_bilinear" 23 | if settings.Encoding.Scaler == "cuda" { 24 | scalefilter = "cuda" 25 | } 26 | // bdrate selection depending on encoder 27 | switch utils.GetArg(video.Output.Encoder.Args, "-c:v") { 28 | case "libx264": 29 | switch utils.GetArg(video.Output.Encoder.Args, "-preset") { 30 | case "veryslow": 31 | bdrate = -27 32 | case "slower": 33 | bdrate = -25 34 | case "slow": 35 | bdrate = -22 36 | case "medium": 37 | bdrate = -20 38 | case "fast": 39 | bdrate = -15 40 | case "faster": 41 | bdrate = -10 42 | default: 43 | bdrate = -10 44 | log.Println("Your x264 preset was not optimized for automatic resolution selection") 45 | log.Println("Use faster to veryslow for best accuracy") 46 | } 47 | case "libvpx-vp9": 48 | args := []string{"-speed", "-cpu-used"} 49 | speed := 8 50 | for i := range args { 51 | spd, err := strconv.Atoi(utils.GetArg(video.Output.Encoder.Args, args[i])) 52 | if err == nil { 53 | speed = spd 54 | break 55 | } 56 | } 57 | if speed == 8 { 58 | log.Println("Your libvpx-vp9 preset was not detected for automatic resolution selection") 59 | log.Println("Assuming cpu-used 8") 60 | } 61 | bdrate = -55 + 3*speed 62 | case "libaom-av1": 63 | speed, err := strconv.Atoi(utils.GetArg(video.Output.Encoder.Args, "-cpu-used")) 64 | if err != nil { 65 | log.Println("Your aomenc preset was not detected for automatic resolution selection") 66 | log.Println("Assuming cpu-used 6") 67 | speed = 6 68 | } 69 | bdrate = -68 + speed 70 | default: 71 | bdrate = -10 72 | } 73 | bdratefac := 100 / (100 + float64(bdrate)) 74 | tempFilename := video.UUID + ".resa.mkv" 75 | 76 | // FPS 77 | var fpsModified bool 78 | video.Output.FPS, fpsModified = calculateFPS(video) 79 | fpsf := "" 80 | if fpsModified { 81 | fpsf = fpsFilter(video) 82 | } 83 | // ffmpeg options 84 | options = append(options, "-loglevel", "warning", "-stats") 85 | options = append(options, metadata.AppendTimes(video)...) 86 | options = append(options, "-hwaccel", settings.General.Hwaccel) 87 | options = append(options, "-i", video.InFile) 88 | options = append(options, "-map", "0:v:0") 89 | options = append(options, "-map_metadata", "-1") 90 | options = append(options, "-map_chapters", "-1") 91 | 92 | var filters []string 93 | filters = append(filters, scaler.GenerateFilter(video, -2, int(testRes), "yuv420p", scalefilter)) 94 | if fpsf != "" { 95 | filters = append(filters, fpsf) 96 | } 97 | 98 | options = append(options, "-vf", strings.Join(filters, ",")) 99 | options = append(options, "-c:v", "libx264", "-preset", "veryfast", "-crf", "26") 100 | options = append(options, "-g", keyint(video)) 101 | options = append(options, tempFilename) 102 | 103 | // encode 104 | cmd := exec.Command(settings.General.FFmpegExecutable, options...) 105 | if settings.Debug { 106 | log.Println(options) 107 | } 108 | cmd.Stdout = os.Stdout 109 | cmd.Stderr = os.Stderr 110 | err := cmd.Start() 111 | if err != nil { 112 | panic(err) 113 | } 114 | err = cmd.Wait() 115 | if err != nil { 116 | panic(err) 117 | } 118 | 119 | obitrate := metadata.GetStats(tempFilename, false).Bitrate.Total 120 | 121 | // fancy calculation stolen from discordify.sh 122 | height := int(math.Sqrt((testRes * testRes) * bdratefac * (float64(video.Output.Bitrate.Video) * video.Time.Duration) / (float64(obitrate) * video.Time.Duration))) 123 | 124 | // rounding height 125 | minimumDiff := math.MaxInt 126 | finalHeight := video.Output.Settings.MaxVRes 127 | for i := range heights { 128 | if height >= heights[i] { 129 | diff := height - heights[i] 130 | if diff < minimumDiff { 131 | finalHeight = heights[i] 132 | minimumDiff = diff 133 | } 134 | } else { 135 | diff := heights[i] - height 136 | if diff < minimumDiff { 137 | finalHeight = heights[i] 138 | minimumDiff = diff 139 | } 140 | } 141 | } 142 | video.Output.Settings.MaxVRes = int(math.Min(float64(finalHeight), float64(settings.Encoding.AutoResCap))) 143 | 144 | os.Remove(tempFilename) 145 | 146 | return video 147 | } 148 | -------------------------------------------------------------------------------- /encoder/video.go: -------------------------------------------------------------------------------- 1 | package encoder 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/metadata" 5 | "github.com/vladaad/discordcompressor/scaler" 6 | "github.com/vladaad/discordcompressor/settings" 7 | "log" 8 | "os" 9 | "os/exec" 10 | "strconv" 11 | "strings" 12 | ) 13 | 14 | func EncodeVideo(video *settings.Vid, pass int) { 15 | var options []string 16 | EncoderOptions := strings.Split(video.Output.Encoder.Args, " ") 17 | options = append(options, "-loglevel", "warning", "-stats") 18 | 19 | // Input 20 | options = append(options, metadata.AppendTimes(video)...) 21 | options = append(options, "-hwaccel", settings.General.Hwaccel) 22 | options = append(options, "-y", "-i") 23 | options = append(options, video.InFile) 24 | 25 | if video.Output.AudioFile != "" && pass != 1 { 26 | options = append(options, "-i", video.Output.AudioFile) 27 | } 28 | 29 | // Filtering 30 | var filters []string 31 | // FPS 32 | var fpsModified bool 33 | video.Output.FPS, fpsModified = calculateFPS(video) 34 | if fpsModified { 35 | f := fpsFilter(video) 36 | if f != "" { 37 | filters = append(filters, f) 38 | } 39 | } 40 | // VFR 41 | if settings.Encoding.VariableFPS { 42 | filters = append(filters, "mpdecimate=max=2") 43 | } 44 | // Resolution 45 | 46 | scaled := false 47 | if video.Output.Settings.MaxVRes < video.Input.Height { 48 | scaled = true 49 | scalefilter := settings.Encoding.Scaler 50 | if pass == 1 && scalefilter != "cuda" { 51 | scalefilter = "fast_bilinear" 52 | } 53 | filters = append(filters, scaler.GenerateFilter(video, -2, video.Output.Settings.MaxVRes, video.Output.Encoder.Pixfmt, scalefilter)) 54 | } 55 | // Combining 56 | if filters != nil { 57 | combined := strings.Join(filters, ",") 58 | options = append(options, "-vf", combined) 59 | } 60 | 61 | // Encoding 62 | options = append(options, EncoderOptions...) 63 | if !scaled { 64 | options = append(options, "-pix_fmt", video.Output.Encoder.Pixfmt) 65 | } 66 | options = append(options, "-b:v", strconv.Itoa(video.Output.Bitrate.Video)) 67 | 68 | if video.Output.Encoder.Passes != 1 { 69 | options = append(options, "-pass", strconv.Itoa(pass)) 70 | options = append(options, "-passlogfile", video.UUID) 71 | } 72 | 73 | // Mapping 74 | options = append(options, "-map", "0:v:0") 75 | if video.Output.AudioFile != "" && pass != 1 { 76 | options = append(options, "-map", "1:a:0") 77 | options = append(options, "-c:a", "copy") 78 | } 79 | if video.Output.APassthrough && pass != 1 { 80 | options = append(options, "-map", "0:a:0") 81 | options = append(options, "-c:a", "copy") 82 | } 83 | options = append(options, "-map_metadata", "-1") 84 | options = append(options, "-map_chapters", "-1") 85 | 86 | // Add own metadata 87 | options = append(options, metadata.AddOutputMetadata(video)...) 88 | 89 | // Faststart for MP4, VFR 90 | if strings.ToLower(video.Output.Settings.Container) == "mp4" { 91 | options = append(options, "-movflags", "+faststart") 92 | } 93 | options = append(options, "-fps_mode", "vfr") 94 | 95 | // WebM H264 trick 96 | if video.Output.Settings.Container == "webm" { 97 | options = append(options, "-f", "matroska") 98 | } 99 | 100 | // Output 101 | 102 | if pass != 1 { 103 | options = append(options, video.OutFile) 104 | } else { 105 | options = append(options, "-f", "null", "-") 106 | } 107 | 108 | if settings.Debug { 109 | log.Println(options) 110 | } 111 | 112 | // Execution 113 | cmd := exec.Command(settings.General.FFmpegExecutable, options...) 114 | 115 | cmd.Stdout = os.Stdout 116 | cmd.Stderr = os.Stderr 117 | 118 | err := cmd.Start() 119 | if err != nil { 120 | panic(err) 121 | } 122 | err = cmd.Wait() 123 | if err != nil { 124 | panic(err) 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/vladaad/discordcompressor 2 | 3 | go 1.17 4 | 5 | require ( 6 | github.com/google/uuid v1.3.0 7 | github.com/wabarc/go-catbox v0.1.0 8 | ) 9 | 10 | require ( 11 | github.com/atotto/clipboard v0.1.4 // indirect 12 | github.com/pkg/errors v0.9.1 // indirect 13 | github.com/wabarc/helper v0.0.0-20210718171053-59c70d0b20c2 // indirect 14 | golang.org/x/net v0.0.0-20210716203947-853a461950ff // indirect 15 | golang.org/x/text v0.3.6 // indirect 16 | mvdan.cc/xurls/v2 v2.2.0 // indirect 17 | ) 18 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= 2 | github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= 3 | github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= 4 | github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 5 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 6 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 7 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 8 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= 9 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 10 | github.com/rogpeppe/go-internal v1.5.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= 11 | github.com/wabarc/go-catbox v0.1.0 h1:/UhV9md3MJrjZtm+EToSyFjawXgPiHSExLNRqsWNisg= 12 | github.com/wabarc/go-catbox v0.1.0/go.mod h1:Zjs9Y55f2WOwGWwmKSCrUuMfwh+nDktkjub9jgHq4CQ= 13 | github.com/wabarc/helper v0.0.0-20210718171053-59c70d0b20c2 h1:6rMZse2rdD7N6GxHRZqHlkSptBWh/Vf9aHiFVQjlQNo= 14 | github.com/wabarc/helper v0.0.0-20210718171053-59c70d0b20c2/go.mod h1:uS6mimKlWkGvEZXkJ6JoW7LYnnB2JP6dLU9q7pgDaWQ= 15 | golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= 16 | golang.org/x/net v0.0.0-20210716203947-853a461950ff h1:j2EK/QoxYNBsXI4R7fQkkRUk8y6wnOBI+6hgPdP/6Ds= 17 | golang.org/x/net v0.0.0-20210716203947-853a461950ff/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= 18 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 19 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 20 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 21 | golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= 22 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 23 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 24 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 25 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 26 | gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= 27 | mvdan.cc/xurls/v2 v2.2.0 h1:NSZPykBXJFCetGZykLAxaL6SIpvbVy/UFEniIfHAa8A= 28 | mvdan.cc/xurls/v2 v2.2.0/go.mod h1:EV1RMtya9D6G5DMYPGD8zTQzaHet6Jh8gFlRgGRJeO8= 29 | -------------------------------------------------------------------------------- /hardware/scaler.go: -------------------------------------------------------------------------------- 1 | package hardware 2 | 3 | import ( 4 | "os/exec" 5 | ) 6 | 7 | func CudaCheck(ffmpegExec string) error { 8 | var options []string 9 | options = append(options, "-y", "-hwaccel", "cuda", "-f", "lavfi", "-i", "nullsrc=2560x1440") 10 | options = append(options, "-vframes", "1", "-an") 11 | options = append(options, "-vf", "hwupload_cuda,scale_cuda=1920:1080:lanczos:p010,hwdownload,format=p010le,format=yuv420p10le") 12 | options = append(options, "-f", "null", "-") 13 | 14 | cmd := exec.Command(ffmpegExec, options...) 15 | 16 | err := cmd.Start() 17 | err = cmd.Wait() 18 | return err 19 | } 20 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "github.com/google/uuid" 6 | "github.com/vladaad/discordcompressor/build" 7 | "github.com/vladaad/discordcompressor/encoder" 8 | "github.com/vladaad/discordcompressor/encoder/audio" 9 | "github.com/vladaad/discordcompressor/metadata" 10 | "github.com/vladaad/discordcompressor/settings" 11 | "github.com/vladaad/discordcompressor/uploader" 12 | "github.com/vladaad/discordcompressor/utils" 13 | "io" 14 | "log" 15 | "math" 16 | "os" 17 | "path" 18 | "runtime" 19 | "strconv" 20 | "strings" 21 | "sync" 22 | ) 23 | 24 | var targetSize int 25 | var targetStartingTime float64 26 | var lastSeconds float64 27 | var targetTotalTime float64 28 | var customOutputFile string 29 | var input string 30 | 31 | var forceEncoder string 32 | var forceAEncoder string 33 | var forceContainer string 34 | 35 | func init() { 36 | // Update checker 37 | utils.CheckForUpdates() 38 | // Settings dir creation 39 | err := os.MkdirAll(utils.SettingsDir(), 0755) 40 | if err != nil { 41 | panic("Failed to create settings directory") 42 | } 43 | // Log setup 44 | logFileName := utils.SettingsDir() 45 | logFileName += "/dcomp.log" 46 | file, err := os.Create(logFileName) 47 | if err != nil { 48 | panic(err) 49 | } 50 | log.SetOutput(io.MultiWriter(os.Stdout, file)) 51 | // Version print 52 | log.Println("Starting DiscordCompressor version " + build.VERSION) 53 | // Check for FFmpeg and FFprobe 54 | checkForFF() 55 | 56 | // Parsing flags 57 | settingsFile := flag.String("settings", "", "Selects the settings file to be used") 58 | startTime := flag.Float64("ss", float64(0), "Sets the starting time") 59 | targetTime := flag.Float64("t", float64(0), "Sets the time to encode") 60 | lastXSeconds := flag.Float64("last", float64(0), "Sets the time from the end to encode") 61 | targetSizeMB := flag.Float64("size", float64(-1), "Sets the target size in MB") 62 | debug := flag.Bool("debug", false, "Prints extra info") 63 | customOutput := flag.String("o", "", "Outputs to a specific filename") 64 | forceEncode := flag.String("c:v", "", "Uses a specific encoder") 65 | forceAEncode := flag.String("c:a", "", "Uses a specific audio encoder") 66 | forceContaine := flag.String("f", "", "Uses a specific container") // don't mind the cut off letters thanks 67 | mixAudio := flag.Bool("mixaudio", false, "Mix together all audio tracks") 68 | normAudio := flag.Bool("normaudio", false, "Normalize the audio volume") 69 | upload := flag.Bool("upload", false, "Upload the video to the service defined in settings.json") 70 | flag.Parse() 71 | 72 | if len(flag.Args()) == 0 { 73 | log.Println("No input file specified") 74 | os.Exit(0) 75 | } 76 | // Forcing 77 | forceEncoder = *forceEncode 78 | forceAEncoder = *forceAEncode 79 | forceContainer = *forceContaine 80 | 81 | input = flag.Args()[0] 82 | targetStartingTime = *startTime 83 | targetTotalTime = *targetTime 84 | lastSeconds = *lastXSeconds 85 | customOutputFile = *customOutput 86 | settings.Debug = *debug 87 | settings.MixAudio = *mixAudio 88 | settings.NormAudio = *normAudio 89 | 90 | // Settings loading 91 | settings.LoadSettings(*settingsFile) 92 | 93 | // Load defaults 94 | if *targetSizeMB == float64(-1) { 95 | if *upload { // This is only set when the flag is used to ensure that TargetSizeMB in settings can still be used to compensate for overhead in some configs 96 | *targetSizeMB = settings.General.UploadMaxMB 97 | } 98 | *targetSizeMB = settings.General.TargetSizeMB 99 | } 100 | targetSize = int(*targetSizeMB * 8388608) // 1024*1024*8 - in bits 101 | 102 | if *upload { 103 | settings.General.AutoUpload = *upload 104 | } 105 | 106 | } 107 | 108 | func main() { 109 | outVideo := compress(input) 110 | log.Println("Done!") 111 | 112 | // Optional video upload 113 | if settings.General.AutoUpload { 114 | URL := uploader.Upload(outVideo) 115 | if URL != "" { 116 | if settings.General.UploadEmbedLink { 117 | URL = "https://embeds.video/" + URL 118 | } 119 | log.Println("Uploaded to: " + URL) 120 | log.Println("The link is also in your clipboard") 121 | utils.PasteIntoClipboard(URL) 122 | } 123 | } 124 | } 125 | 126 | func compress(inVideo string) string { 127 | var wg sync.WaitGroup 128 | // Initialize variables 129 | video := initVideo() 130 | video.InFile = inVideo 131 | 132 | // Check if file exists 133 | if _, err := os.Stat(video.InFile); err != nil { 134 | panic(video.InFile + " doesn't exist") 135 | } 136 | 137 | // Video analysis, time calculation 138 | log.Println("Analyzing video...") 139 | video.Input = metadata.GetStats(video.InFile, false) 140 | video = metadata.CalculateTime(video, lastSeconds, targetStartingTime, targetTotalTime) 141 | 142 | // Bitrate calculation 143 | // min(target bps/time, max bps) 144 | video.Output.Bitrate.Total = int(math.Min(float64(targetSize)/video.Time.Duration, float64(settings.Encoding.MaxBitrate*1024))) 145 | 146 | // Cap for uploading 147 | // min(target bps, max bps) 148 | if settings.General.AutoUpload { 149 | video.Output.Bitrate.Total = int(math.Min(float64(video.Output.Bitrate.Total), float64(settings.General.UploadMaxBitrate*1024))) 150 | } 151 | 152 | // Encoder selection 153 | video.Output.Force.Video, video.Output.Force.Audio, video.Output.Force.Container = forceEncoder, forceAEncoder, forceContainer 154 | video = metadata.SelectEncoder(video) 155 | video = metadata.CalcOverhead(video) 156 | 157 | // Force fast mode with 1-pass 158 | if video.Output.Encoder.Passes == 1 { 159 | settings.Encoding.FastMode = true 160 | } 161 | 162 | // Audio bitrate calculation and encoding 163 | if video.Input.ATracks > 0 { 164 | video = metadata.CalcAudioBitrate(video) 165 | } 166 | video = metadata.PassthroughCheck(video) 167 | if !video.Output.APassthrough || forceAEncoder != "" { 168 | if video.Input.ATracks > 0 { 169 | video.Output.AudioFile = audio.GenFilename(video) 170 | wg.Add(1) 171 | if settings.Encoding.FastMode { 172 | go audio.EncodeAudio(video, &wg) 173 | } else { 174 | log.Println("Encoding audio...") 175 | audio.EncodeAudio(video, &wg) 176 | } 177 | } else { 178 | video.Output.Bitrate.Video = video.Output.Bitrate.Total 179 | } 180 | } 181 | 182 | if settings.Debug { 183 | log.Println("Video bitrate:", video.Output.Bitrate.Video/1024) 184 | log.Println("Audio bitrate:", video.Output.Bitrate.Audio/1024) 185 | } 186 | 187 | // Resolution analysis 188 | if !settings.Encoding.FastMode && settings.Encoding.AutoRes { 189 | log.Println("Automatically choosing resolution, this may take a while...") 190 | video = encoder.CalculateResolution(video) 191 | if settings.Debug { 192 | log.Println("Chosen vertical resolution:", video.Output.Settings.MaxVRes) 193 | } 194 | } 195 | 196 | // Output filename 197 | suffix := strings.ReplaceAll(settings.General.OutputSuffix, "%s", strconv.FormatFloat(float64(targetSize)/8388608, 'f', 1, 64)) 198 | video.OutFile = strings.TrimSuffix(video.InFile, path.Ext(video.InFile)) + suffix + "." + video.Output.Settings.Container 199 | if customOutputFile != "" { 200 | video.OutFile = customOutputFile + "." + video.Output.Settings.Container 201 | } 202 | // Encoding 203 | if video.Output.Encoder.Passes == 1 { 204 | wg.Wait() 205 | log.Println("Encoding") 206 | encoder.EncodeVideo(video, 0) 207 | } else { 208 | log.Println("Encoding, pass 1/2") 209 | encoder.EncodeVideo(video, 1) 210 | wg.Wait() 211 | log.Println("Encoding, pass 2/2") 212 | encoder.EncodeVideo(video, 2) 213 | } 214 | 215 | // Cleanup 216 | os.Remove(video.UUID + "-0.log") 217 | os.Remove(video.UUID + "-0.log.mbtree") 218 | os.Remove(video.Output.AudioFile) 219 | 220 | return video.OutFile 221 | } 222 | 223 | func checkForFF() { 224 | exit := false 225 | check := []string{"ffmpeg", "ffprobe"} 226 | 227 | for i := range check { 228 | if !utils.CheckIfPresent(check[i]) { 229 | message := check[i] + " not installed or not added to PATH" 230 | if runtime.GOOS == "windows" { 231 | message = message + ", you can download it here: https://github.com/BtbN/FFmpeg-Builds/releases" 232 | } 233 | log.Println(message) 234 | exit = true 235 | } 236 | } 237 | 238 | if exit { 239 | os.Exit(1) 240 | } 241 | } 242 | 243 | func initVideo() *settings.Vid { 244 | // god fucking dammit 245 | video := new(settings.Vid) 246 | time := new(settings.Time) 247 | bitrates := new(settings.Bitrates) 248 | output := new(settings.Out) 249 | force := new(settings.Force) 250 | output.Bitrate = bitrates 251 | video.Output = output 252 | video.Output.Force = force 253 | video.Time = time 254 | video.UUID = uuid.New().String() 255 | 256 | return video 257 | } 258 | -------------------------------------------------------------------------------- /metadata/analyzer.go: -------------------------------------------------------------------------------- 1 | package metadata 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/vladaad/discordcompressor/settings" 6 | "log" 7 | "os/exec" 8 | "strconv" 9 | "strings" 10 | ) 11 | 12 | type StreamList struct { 13 | Streams []Stream `json:"streams"` 14 | Format Format `json:"format"` 15 | } 16 | 17 | type Stream struct { 18 | CodecName string `json:"codec_name"` 19 | StreamType string `json:"codec_type"` 20 | Width int `json:"width"` 21 | Height int `json:"height"` 22 | Pixfmt string `json:"pix_fmt"` 23 | Framerate string `json:"r_frame_rate"` 24 | Channels int `json:"channels"` 25 | Bitrate string `json:"bit_rate"` 26 | } 27 | 28 | type Format struct { 29 | Duration string `json:"duration"` 30 | Bitrate string `json:"bit_rate"` 31 | } 32 | 33 | func GetStats(filename string, audioonly bool) *settings.InputStats { 34 | stats := new(settings.InputStats) 35 | stats.Bitrate = new(settings.Bitrates) 36 | probe, err := exec.Command( 37 | settings.General.FFprobeExecutable, 38 | "-loglevel", "quiet", 39 | "-of", "json", 40 | "-show_entries", "stream:format", 41 | filename, 42 | ).Output() 43 | 44 | if err != nil { 45 | panic("Failed to start FFprobe") 46 | } 47 | // JSON parsing 48 | probeOutput := new(StreamList) 49 | 50 | err = json.Unmarshal(probe, &probeOutput) 51 | if err != nil { 52 | log.Println(err) 53 | panic("Failed to parse JSON") 54 | } 55 | 56 | if !audioonly { 57 | videoStream := findFirstStream("video", probeOutput.Streams) 58 | stats.Bitrate.Video, _ = strconv.Atoi(videoStream.Bitrate) 59 | stats.VCodec = videoStream.CodecName 60 | stats.Pixfmt = videoStream.Pixfmt 61 | stats.Width = videoStream.Width 62 | stats.Height = videoStream.Height 63 | // FPS 64 | fps := new(settings.FPS) 65 | fpsSplit := strings.Split(videoStream.Framerate, "/") 66 | n1, _ := strconv.Atoi(fpsSplit[0]) 67 | n2, _ := strconv.Atoi(fpsSplit[1]) 68 | fps.N, fps.D = n1, n2 69 | stats.FPS = fps 70 | } 71 | // Other 72 | stats.Duration, _ = strconv.ParseFloat(probeOutput.Format.Duration, 64) 73 | stats.Bitrate.Total, _ = strconv.Atoi(probeOutput.Format.Bitrate) 74 | // Audio 75 | stats.ATracks = countStreams("audio", probeOutput.Streams) 76 | if stats.ATracks != 0 { 77 | audioStream := findFirstStream("audio", probeOutput.Streams) 78 | stats.ACodec = audioStream.CodecName 79 | stats.Bitrate.Audio, _ = strconv.Atoi(audioStream.Bitrate) 80 | stats.AChannels = audioStream.Channels 81 | } 82 | 83 | return stats 84 | } 85 | 86 | func findFirstStream(streamType string, streamList []Stream) Stream { 87 | for i := range streamList { 88 | if streamList[i].StreamType == streamType { 89 | return streamList[i] 90 | } 91 | } 92 | panic("Stream not found") 93 | } 94 | 95 | func countStreams(streamType string, streamList []Stream) int { 96 | streamCount := 0 97 | for i := range streamList { 98 | if streamList[i].StreamType == streamType { 99 | streamCount++ 100 | } 101 | } 102 | return streamCount 103 | } 104 | -------------------------------------------------------------------------------- /metadata/bitratecalc.go: -------------------------------------------------------------------------------- 1 | package metadata 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/settings" 5 | "github.com/vladaad/discordcompressor/utils" 6 | "log" 7 | "math" 8 | ) 9 | 10 | func CalcOverhead(video *settings.Vid) *settings.Vid { 11 | // thanks RootAtKali, calculations taken from discordify.sh 12 | var overhead float64 13 | var header float64 14 | var frameOverhead float64 15 | var timeOverhead float64 16 | var marginBase float64 17 | mult := 1.0 18 | switch utils.GetArg(video.Output.Encoder.Args, "-c:v") { 19 | case "h264_nvenc", "h264_qsv", "h264_amf": 20 | header = 15000 21 | frameOverhead = 300 22 | timeOverhead = 2700 23 | marginBase = 720000 24 | mult = 0.9 // hwenc is 1-pass only, forced multiplier 25 | case "libx264": 26 | header = 15000 27 | frameOverhead = 300 28 | timeOverhead = 2700 29 | marginBase = 720000 30 | mult = 0.98 // x264 is so inaccurate in my testing this is needed for many types of footage 31 | case "libvpx-vp9": 32 | header = 9152 33 | frameOverhead = 60 34 | timeOverhead = 2680 35 | marginBase = 160000 36 | case "libaom-av1": 37 | header = 9152 38 | frameOverhead = 56 39 | timeOverhead = 2704 40 | marginBase = 320000 41 | default: 42 | log.Println("Encoder not recognized, overhead estimation may not be accurate") 43 | header = 12000 44 | frameOverhead = 178 45 | timeOverhead = 2704 46 | marginBase = 640000 47 | } 48 | 49 | extraMargin := marginBase / math.Sqrt(video.Time.Duration) 50 | 51 | overhead += header 52 | overhead += timeOverhead * video.Time.Duration 53 | overhead += frameOverhead * math.Min(float64(video.Input.FPS.N)/float64(video.Input.FPS.D), float64(video.Output.Settings.MaxFPS)) 54 | overhead += extraMargin 55 | overhead /= video.Time.Duration 56 | 57 | video.Output.Bitrate.Total -= int(overhead) 58 | video.Output.Bitrate.Total = int(float64(video.Output.Bitrate.Total) * mult) 59 | return video 60 | } 61 | 62 | func CalcAudioBitrate(video *settings.Vid) *settings.Vid { 63 | // thanks RootAtKali, calculations taken from discordify.sh 64 | abr := int((318000 / (1 + math.Exp(-0.0000014*float64(video.Output.Bitrate.Total)))) - 154000) 65 | mult := video.Output.AEncoder.BMult 66 | if video.Input.AChannels == 1 { 67 | mult *= 0.5 // halve audio bitrate if mono 68 | } 69 | 70 | video.Output.Bitrate.Audio = int(float64(abr) * mult) 71 | // cap audio bitrate, spaghetti 72 | video.Output.Bitrate.Audio = int(math.Max(math.Min(float64(video.Output.Bitrate.Audio), float64(video.Output.AEncoder.BMax*1024)), float64(video.Output.AEncoder.BMin*1024))) 73 | video.Output.Bitrate.Video = video.Output.Bitrate.Total - abr 74 | return video 75 | } 76 | -------------------------------------------------------------------------------- /metadata/outmetadata.go: -------------------------------------------------------------------------------- 1 | package metadata 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/build" 5 | "github.com/vladaad/discordcompressor/settings" 6 | "github.com/vladaad/discordcompressor/utils" 7 | "strconv" 8 | ) 9 | 10 | func AddOutputMetadata(video *settings.Vid) []string { 11 | var options []string 12 | 13 | options = append(options, "-metadata:s:v:0", "title="+"Video compressed using DiscordCompressor "+build.VERSION+" | "+generateVideoDescription(video)) 14 | if video.Output.Bitrate.Audio > 0 { 15 | options = append(options, "-metadata:s:a:0", "title="+generateAudioDescription(video)) 16 | } 17 | 18 | return options 19 | } 20 | 21 | func generateVideoDescription(video *settings.Vid) (description string) { 22 | const FPSPrecision = 0 23 | 24 | description = description + strconv.Itoa(video.Output.Settings.MaxVRes) + "p" 25 | description = description + strconv.FormatFloat(float64(video.Output.FPS.N)/float64(video.Output.FPS.D), 'f', FPSPrecision, 64) + " " 26 | description = description + strconv.FormatFloat(float64(video.Output.Bitrate.Video)/1024, 'f', 0, 64) + "kbit " 27 | description = description + " | " 28 | description = description + video.Output.Encoder.Args 29 | 30 | return description 31 | } 32 | 33 | func generateAudioDescription(video *settings.Vid) (description string) { 34 | if video.Output.APassthrough { 35 | description = description + "Passed through - " 36 | description = description + strconv.FormatFloat(float64(video.Input.Bitrate.Audio)/1024, 'f', 0, 64) + "kbit " 37 | description = description + video.Input.ACodec 38 | } else { 39 | description = description + strconv.FormatFloat(float64(video.Output.Bitrate.Audio)/1024, 'f', 0, 64) + "kbit " 40 | var encoderName string 41 | switch video.Output.AEncoder.Type { 42 | case "ffmpeg": 43 | encoderName = utils.GetArg(video.Output.AEncoder.Args, "-c:a") 44 | default: 45 | encoderName = video.Output.AEncoder.Type 46 | } 47 | if video.Output.AEncoder.Type == "ffmpeg" && encoderName == "aac" { 48 | encoderName = "FFmpeg AAC" 49 | } 50 | description = description + encoderName 51 | } 52 | 53 | return description 54 | } 55 | -------------------------------------------------------------------------------- /metadata/passthrough.go: -------------------------------------------------------------------------------- 1 | package metadata 2 | 3 | import ( 4 | "bufio" 5 | "github.com/vladaad/discordcompressor/settings" 6 | "github.com/vladaad/discordcompressor/utils" 7 | "log" 8 | "os/exec" 9 | "strconv" 10 | "strings" 11 | ) 12 | 13 | func PassthroughCheck(video *settings.Vid) *settings.Vid { 14 | webmCodecs := []string{"opus", "vorbis", "av1", "h264", "vp9"} // probably could've done this cleaner 15 | // Audio passthrough 16 | if video.Input.Bitrate.Audio == 0 && settings.Encoding.ForceGetABR { 17 | video.Input.Bitrate.Audio = AnalyzeAudio(video.InFile) 18 | video.Input.Bitrate.Video = video.Input.Bitrate.Total - video.Input.Bitrate.Audio 19 | } 20 | 21 | if video.Input.Bitrate.Audio != 0 && video.Input.Bitrate.Audio < video.Output.Bitrate.Audio { 22 | 23 | if video.Input.ACodec == "aac" && video.Output.Settings.Container == "mp4" { 24 | video.Output.APassthrough = true 25 | } 26 | 27 | if contains(video.Input.ACodec, webmCodecs) { 28 | if video.Output.Settings.Container == "mp4" && utils.GetArg(video.Output.Encoder.Args, "-c:v") == "libx264" { 29 | video.Output.Settings.Container = "webm" 30 | video.Output.APassthrough = true 31 | log.Println("Setting container to WebM for audio passthrough") 32 | } else if video.Output.Settings.Container == "webm" { 33 | video.Output.APassthrough = true 34 | } 35 | } 36 | } 37 | // Correct A/V bitrate if passthrough 38 | if video.Output.APassthrough { 39 | video.Output.Bitrate.Audio = video.Input.Bitrate.Audio 40 | video.Output.Bitrate.Video = video.Output.Bitrate.Total - video.Output.Bitrate.Audio 41 | } 42 | return video 43 | } 44 | 45 | func contains(str string, list []string) bool { 46 | for i := range list { 47 | if str == list[i] { 48 | return true 49 | } 50 | } 51 | return false 52 | } 53 | 54 | func AnalyzeAudio(filename string) int { 55 | extract := exec.Command( 56 | settings.General.FFmpegExecutable, 57 | "-y", "-i", filename, 58 | "-map", "0:a:0", 59 | "-c:a", "copy", 60 | "-f", "nut", 61 | "-", 62 | ) 63 | 64 | pipe, err := extract.StderrPipe() 65 | scanner := bufio.NewScanner(pipe) 66 | if err != nil { 67 | panic(err) 68 | } 69 | 70 | err = extract.Start() 71 | if err != nil { 72 | panic("Couldn't start FFmpeg") 73 | } 74 | 75 | for scanner.Scan() { 76 | line := strings.TrimSpace(scanner.Text()) 77 | if strings.Contains(line, "bitrate=") { 78 | split := strings.Split(line, "bitrate=") 79 | split2 := strings.Split(split[len(split)-1], "/") 80 | replaced := strings.ReplaceAll(split2[0], "kbits", "") 81 | parsed, err := strconv.ParseFloat(strings.TrimSpace(replaced), 64) 82 | if err != nil { 83 | return 0 84 | } 85 | return int(parsed * 1024) 86 | } 87 | } 88 | return 0 89 | } 90 | -------------------------------------------------------------------------------- /metadata/targetselect.go: -------------------------------------------------------------------------------- 1 | package metadata 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/settings" 5 | ) 6 | 7 | func SelectEncoder(video *settings.Vid) *settings.Vid { 8 | for i := range settings.Encoding.Limits { 9 | if settings.Encoding.Limits[i].MinBitrate*1024 < video.Output.Bitrate.Total { 10 | target := settings.Encoding.Limits[i] 11 | video.Output.Settings = target 12 | if video.Output.Force.Container != "" { 13 | video.Output.Settings.Container = video.Output.Force.Container 14 | } 15 | video.Output.Encoder, video.Output.AEncoder = encSelect(video) 16 | return video 17 | } 18 | } 19 | panic("Could not find suitable bitrate target") 20 | } 21 | 22 | func encSelect(target *settings.Vid) (*settings.Encoder, *settings.AudioEncoder) { 23 | for i := range settings.Encoding.Encoders { 24 | if target.Output.Force.Video != "" { 25 | target.Output.Settings.Encoder = target.Output.Force.Video 26 | } 27 | if settings.Encoding.Encoders[i].Name == target.Output.Settings.Encoder { 28 | venc := settings.Encoding.Encoders[i] 29 | aenc := aencSelect(target) 30 | return venc, aenc 31 | } 32 | } 33 | panic("Could not find video encoder " + target.Output.Settings.Encoder) 34 | } 35 | 36 | func aencSelect(target *settings.Vid) *settings.AudioEncoder { 37 | for i := range settings.Encoding.AEncoders { 38 | if target.Output.Force.Audio != "" { 39 | target.Output.Settings.AEncoder = target.Output.Force.Audio 40 | } 41 | if settings.Encoding.AEncoders[i].Name == target.Output.Settings.AEncoder { 42 | return settings.Encoding.AEncoders[i] 43 | } 44 | } 45 | panic("Could not find audio encoder " + target.Output.Settings.AEncoder) 46 | } 47 | -------------------------------------------------------------------------------- /metadata/timecheck.go: -------------------------------------------------------------------------------- 1 | package metadata 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/settings" 5 | "log" 6 | "os" 7 | ) 8 | 9 | func CalculateTime(video *settings.Vid, lastSecs float64, targetStart float64, targetTime float64) *settings.Vid { 10 | video.Time.Duration = video.Input.Duration 11 | if lastSecs != 0 { 12 | video.Time.Start = video.Input.Duration - lastSecs 13 | video.Time.Duration = lastSecs 14 | return video 15 | } 16 | if targetStart != 0 { 17 | if targetStart > video.Input.Duration { 18 | log.Println("Starting time is longer than the video!") 19 | os.Exit(1) 20 | } 21 | video.Time.Start = targetStart 22 | video.Time.Duration = video.Input.Duration - targetStart 23 | } 24 | if targetTime != 0 { 25 | if targetTime > (video.Input.Duration - targetStart) { 26 | targetTime = video.Input.Duration - targetStart 27 | } 28 | video.Time.Duration = targetTime 29 | } 30 | return video 31 | } 32 | -------------------------------------------------------------------------------- /metadata/times.go: -------------------------------------------------------------------------------- 1 | package metadata 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/settings" 5 | "strconv" 6 | ) 7 | 8 | func AppendTimes(video *settings.Vid) []string { 9 | var times []string 10 | if video.Time.Start != float64(0) { 11 | times = append(times, "-ss", strconv.FormatFloat(video.Time.Start, 'f', -1, 64)) 12 | } 13 | times = append(times, "-t", strconv.FormatFloat(video.Time.Duration, 'f', -1, 64)) 14 | return times 15 | } 16 | -------------------------------------------------------------------------------- /package.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | if "%1" == "" ( 3 | set version=dev 4 | ) else ( 5 | set version=%1 6 | ) 7 | echo This might screw up your GOOS env variable if it's not default 8 | pause 9 | go env -w GOOS=windows 10 | go build -trimpath -ldflags "-s -w -X 'github.com/vladaad/discordcompressor/build.VERSION=%version%'" -o discordcompressor.exe 11 | go env -w GOOS=linux 12 | go build -trimpath -ldflags "-s -w -X 'github.com/vladaad/discordcompressor/build.VERSION=%version%'" -o discordcompressor 13 | go env -u GOOS 14 | set z="C:\Program Files\7-Zip\7z.exe" 15 | set options=-mmt1 -mx9 16 | %z% a %options% discordcompressor-windows.zip discordcompressor.exe 17 | #%z% a %options% discordcompressor-windows-portable.zip discordcompressor-portable.exe 18 | %z% a %options% discordcompressor-linux.zip discordcompressor 19 | #%z% a %options% discordcompressor-linux-portable.zip discordcompressor-portable -------------------------------------------------------------------------------- /scaler/genparams.go: -------------------------------------------------------------------------------- 1 | package scaler 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/settings" 5 | "strconv" 6 | ) 7 | 8 | func GenerateFilter(video *settings.Vid, targetWidth int, targetHeight int, targetPixfmt string, scaler string) string { 9 | var filter string 10 | if scaler != "cuda" { //swscale 11 | filter += "scale=" + strconv.Itoa(targetWidth) 12 | filter += ":" + strconv.Itoa(targetHeight) 13 | filter += ":flags=" + scaler 14 | if targetPixfmt != "" { 15 | filter += ",format=" + targetPixfmt 16 | } 17 | } else { //cuda 18 | pixfmt := targetPixfmt 19 | pixfmt_cuda := pixfmt 20 | samePixfmt := false 21 | if targetPixfmt == "" { 22 | samePixfmt = true 23 | pixfmt = video.Input.Pixfmt 24 | pixfmt_cuda = pixfmt 25 | } 26 | if pixfmt_cuda == "yuv420p10le" { 27 | pixfmt_cuda = "p010" 28 | } 29 | 30 | filter += "hwupload_cuda," 31 | filter += "scale_cuda=" + strconv.Itoa(targetWidth) 32 | filter += ":" + strconv.Itoa(targetHeight) 33 | if !samePixfmt { 34 | filter += ":format=" + pixfmt_cuda 35 | } 36 | filter += ",hwdownload,format=" + pixfmt_cuda //hwdownload always needs pixfmt 37 | 38 | } 39 | return filter 40 | } 41 | -------------------------------------------------------------------------------- /settings/encoding.go: -------------------------------------------------------------------------------- 1 | package settings 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/hardware" 5 | ) 6 | 7 | var Encoding = initEncoding() 8 | 9 | func initEncoding() *encoding { 10 | return &encoding{ 11 | MaxBitrate: 15000, 12 | FastMode: false, 13 | AutoRes: true, 14 | AutoResCap: 1080, 15 | HalveFPS: true, 16 | VariableFPS: false, 17 | Passthrough: true, 18 | ForceGetABR: true, 19 | Scaler: genScaler(), 20 | Encoders: []*Encoder{ 21 | nil, 22 | }, 23 | AEncoders: []*AudioEncoder{ 24 | nil, 25 | }, 26 | Limits: []*Limit{ 27 | { 28 | Encoder: "fast", 29 | AEncoder: "aac", 30 | Container: "mp4", 31 | MinBitrate: 12000, 32 | MaxVRes: 1080, 33 | MaxFPS: 60, 34 | }, 35 | { 36 | Encoder: "normal", 37 | AEncoder: "aac", 38 | Container: "mp4", 39 | MinBitrate: 5000, 40 | MaxVRes: 1080, 41 | MaxFPS: 60, 42 | }, 43 | { 44 | Encoder: "normal", 45 | AEncoder: "aac", 46 | Container: "mp4", 47 | MinBitrate: 3000, 48 | MaxVRes: 900, 49 | MaxFPS: 60, 50 | }, 51 | { 52 | Encoder: "normal", 53 | AEncoder: "aac", 54 | Container: "mp4", 55 | MinBitrate: 1500, 56 | MaxVRes: 720, 57 | MaxFPS: 60, 58 | }, 59 | { 60 | Encoder: "slow", 61 | AEncoder: "aac", 62 | Container: "mp4", 63 | MinBitrate: 800, 64 | MaxVRes: 540, 65 | MaxFPS: 60, 66 | }, 67 | { 68 | Encoder: "ultra", 69 | AEncoder: "opus", 70 | Container: "webm", 71 | MinBitrate: 0, 72 | MaxVRes: 540, 73 | MaxFPS: 30, 74 | }, 75 | }, 76 | } 77 | } 78 | 79 | func genScaler() string { 80 | if hardware.CudaCheck("ffmpeg") == nil { 81 | return "cuda" 82 | } else { 83 | return "bicubic" 84 | } 85 | } 86 | 87 | type encoding struct { 88 | MaxBitrate int 89 | FastMode bool 90 | AutoRes bool 91 | AutoResCap int 92 | HalveFPS bool 93 | VariableFPS bool 94 | Scaler string 95 | Passthrough bool 96 | ForceGetABR bool 97 | Encoders []*Encoder 98 | AEncoders []*AudioEncoder 99 | Limits []*Limit 100 | } 101 | 102 | type Encoder struct { 103 | Name string 104 | Passes int 105 | Keyint int 106 | Pixfmt string 107 | Args string 108 | } 109 | 110 | type AudioEncoder struct { 111 | Name string 112 | Type string 113 | BMult float64 114 | BMax int 115 | BMin int 116 | TVBR bool 117 | Args string 118 | } 119 | 120 | type Limit struct { 121 | Encoder string 122 | AEncoder string 123 | Container string 124 | MinBitrate int 125 | MaxVRes int 126 | MaxFPS int 127 | } 128 | -------------------------------------------------------------------------------- /settings/ffenccheck.go: -------------------------------------------------------------------------------- 1 | package settings 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "os/exec" 7 | ) 8 | 9 | func checkEncoder(encoder string, audio bool) bool { 10 | var options []string 11 | 12 | if audio { 13 | options = append(options, "-f", "lavfi", "-i", "anullsrc") 14 | } else { 15 | options = append(options, "-f", "lavfi", "-i", "nullsrc=1920x1080") 16 | } 17 | 18 | options = append(options, "-t", "1") 19 | 20 | if audio { 21 | options = append(options, "-c:a", encoder) 22 | } else { 23 | options = append(options, "-c:v", encoder) 24 | } 25 | 26 | options = append(options, "-f", "null", "-") 27 | 28 | if Debug { 29 | log.Println(options) 30 | } 31 | 32 | // Execution 33 | cmd := exec.Command(General.FFmpegExecutable, options...) 34 | 35 | if Debug { 36 | cmd.Stdout = os.Stdout 37 | cmd.Stderr = os.Stderr 38 | log.Println("Testing ", encoder) 39 | } 40 | 41 | err := cmd.Start() 42 | if err != nil { 43 | return false 44 | } 45 | err = cmd.Wait() 46 | if err != nil { 47 | return false 48 | } 49 | 50 | return true 51 | } 52 | -------------------------------------------------------------------------------- /settings/general.go: -------------------------------------------------------------------------------- 1 | package settings 2 | 3 | var General = initGeneral() 4 | 5 | func initGeneral() *general { 6 | return &general{ 7 | TargetSizeMB: 25, 8 | Hwaccel: "auto", 9 | FFmpegExecutable: "ffmpeg", 10 | FFprobeExecutable: "ffprobe", 11 | QaacExecutable: "qaac64", 12 | FDKaacExecutable: "fdkaac", 13 | FHGaacExecutable: "fhgaacenc", 14 | OutputSuffix: "-%smb", 15 | AutoUpload: false, 16 | UploadService: "catbox", 17 | UploadMaxMB: 100, 18 | UploadMaxBitrate: 3500, 19 | UploadEmbedLink: true, 20 | } 21 | } 22 | 23 | type general struct { 24 | TargetSizeMB float64 25 | Hwaccel string 26 | FFmpegExecutable string 27 | FFprobeExecutable string 28 | QaacExecutable string 29 | FDKaacExecutable string 30 | FHGaacExecutable string 31 | OutputSuffix string 32 | AutoUpload bool 33 | UploadService string 34 | UploadMaxMB float64 35 | UploadMaxBitrate int 36 | UploadEmbedLink bool 37 | } 38 | -------------------------------------------------------------------------------- /settings/generator.go: -------------------------------------------------------------------------------- 1 | package settings 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/utils" 5 | "log" 6 | ) 7 | 8 | func newSettings() { 9 | log.Println("Generating new settings") 10 | genAudioEncoders() 11 | genVideoEncoders() 12 | } 13 | 14 | func genAudioEncoders() { 15 | aac := genAACEncoder() 16 | opus := genOpusEncoder() 17 | 18 | if Debug { 19 | log.Println("Automatic encoder choice") 20 | log.Println("AAC: ", aac.Type, ", Opus: ", opus.Type) 21 | } 22 | 23 | Encoding.AEncoders = []*AudioEncoder{aac, opus} 24 | } 25 | 26 | func genVideoEncoders() { 27 | fastest := genFastestEncoder() 28 | 29 | Encoding.Encoders = []*Encoder{ 30 | fastest, 31 | { 32 | Name: "fast", 33 | Passes: 2, 34 | Keyint: 10, 35 | Pixfmt: "yuv420p", 36 | Args: "-c:v libx264 -preset medium -aq-mode 3", 37 | }, 38 | { 39 | Name: "normal", 40 | Passes: 2, 41 | Keyint: 10, 42 | Pixfmt: "yuv420p", 43 | Args: "-c:v libx264 -preset slow -aq-mode 3", 44 | }, 45 | { 46 | Name: "slow", 47 | Passes: 2, 48 | Keyint: 10, 49 | Pixfmt: "yuv420p", 50 | Args: "-c:v libx264 -preset veryslow -aq-mode 3", 51 | }, 52 | { 53 | Name: "veryslow", 54 | Passes: 2, 55 | Keyint: 15, 56 | Pixfmt: "yuv420p10le", 57 | Args: "-c:v libvpx-vp9 -lag-in-frames 25 -cpu-used 4 -auto-alt-ref 1 -arnr-maxframes 7 -arnr-strength 4 -aq-mode 0 -enable-tpl 1 -row-mt 1", // credit: BlueSwordM 58 | }, 59 | { 60 | Name: "ultra", 61 | Passes: 2, 62 | Keyint: 15, 63 | Pixfmt: "yuv420p10le", 64 | Args: "-c:v libaom-av1 -cpu-used 6 -lag-in-frames 25 -aom-params enable-keyframe-filtering=1:arnr-strength=1:sb-size=dynamic:enable-chroma-deltaq=1:enable-qm=1:quant-b-adapt=1", // credit: wiki.x266.mov/blog/av1-encoding-for-dummies 65 | }, 66 | } 67 | } 68 | 69 | func genFastestEncoder() *Encoder { 70 | var encoder *Encoder 71 | log.Println("Checking hardware encoders, this may take a while") 72 | // fuck this shit i hate multithreading 73 | nvenc := checkEncoder("h264_nvenc", false) 74 | qsv := checkEncoder("h264_qsv", false) 75 | amf := checkEncoder("h264_amf", false) 76 | 77 | if nvenc { 78 | encoder = &Encoder{ 79 | Name: "fastest", 80 | Passes: 1, 81 | Keyint: 10, 82 | Pixfmt: "yuv420p", 83 | Args: "-c:v h264_nvenc -preset p7", 84 | } 85 | } else if qsv { 86 | encoder = &Encoder{ 87 | Name: "fastest", 88 | Passes: 1, 89 | Keyint: 10, 90 | Pixfmt: "yuv420p", 91 | Args: "-c:v h264_qsv -preset veryslow", 92 | } 93 | } else if amf { 94 | encoder = &Encoder{ 95 | Name: "fastest", 96 | Passes: 1, 97 | Keyint: 10, 98 | Pixfmt: "yuv420p", 99 | Args: "-c:v h264_amf -quality quality", 100 | } 101 | } else { 102 | encoder = &Encoder{ 103 | Name: "fastest", 104 | Passes: 1, 105 | Keyint: 10, 106 | Pixfmt: "yuv420p", 107 | Args: "-c:v libx264 -preset veryfast -aq-mode 3", 108 | } 109 | } 110 | return encoder 111 | } 112 | 113 | func genAACEncoder() *AudioEncoder { 114 | var encoder *AudioEncoder 115 | 116 | if utils.CheckIfPresent("qaac64") { 117 | encoder = &AudioEncoder{ 118 | Name: "aac", 119 | Type: "qaac", 120 | BMult: 1.2, 121 | BMax: 144, 122 | BMin: 72, 123 | TVBR: false, 124 | Args: "", 125 | } 126 | } else if utils.CheckIfPresent("fhgaacenc") { 127 | encoder = &AudioEncoder{ 128 | Name: "aac", 129 | Type: "fhgaac", 130 | BMult: 1.2, 131 | BMax: 144, 132 | BMin: 72, 133 | TVBR: false, 134 | Args: "", 135 | } 136 | } else if utils.CheckIfPresent("fdkaac") { 137 | encoder = &AudioEncoder{ 138 | Name: "aac", 139 | Type: "fdkaac", 140 | BMult: 1.2, 141 | BMax: 144, 142 | BMin: 72, 143 | TVBR: false, 144 | Args: "", 145 | } 146 | } else { 147 | encoder = &AudioEncoder{ 148 | Name: "aac", 149 | Type: "ffmpeg", 150 | BMult: 1.4, 151 | BMax: 192, 152 | BMin: 96, 153 | TVBR: false, 154 | Args: "-c:a aac", 155 | } 156 | } 157 | return encoder 158 | } 159 | 160 | func genOpusEncoder() *AudioEncoder { 161 | var encoder *AudioEncoder // for future expansion 162 | encoder = &AudioEncoder{ 163 | Name: "opus", 164 | Type: "ffmpeg", 165 | BMult: 1, 166 | BMax: 128, 167 | BMin: 32, 168 | TVBR: false, 169 | Args: "-c:a libopus", 170 | } 171 | return encoder 172 | } 173 | -------------------------------------------------------------------------------- /settings/manager.go: -------------------------------------------------------------------------------- 1 | package settings 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/vladaad/discordcompressor/utils" 7 | "io/ioutil" 8 | "log" 9 | "os" 10 | "strings" 11 | ) 12 | 13 | // Stolen from https://github.com/Wieku/danser-go/app/settings 14 | 15 | var fileStorage *fileformat 16 | 17 | func initStorage() { 18 | fileStorage = &fileformat{ 19 | General: General, 20 | Encoding: Encoding, 21 | } 22 | } 23 | 24 | func LoadSettings(version string) bool { 25 | initStorage() 26 | fileName := utils.SettingsDir() 27 | fileName += "/settings" 28 | if version != "" { 29 | fileName += "-" + version 30 | } 31 | fileName += ".json" 32 | if detectOldSettings(fileName) { 33 | log.Println("Old settings were backed up and new settings were created!") 34 | } 35 | 36 | file, err := os.Open(fileName) 37 | defer file.Close() 38 | 39 | if os.IsNotExist(err) { 40 | newSettings() 41 | saveSettings(fileName, fileStorage) 42 | return true 43 | } else if err != nil { 44 | panic(err) 45 | } else { 46 | load(file, fileStorage) 47 | saveSettings(fileName, fileStorage) //this is done to save additions from the current format 48 | } 49 | return false 50 | } 51 | 52 | func load(file *os.File, target interface{}) { 53 | decoder := json.NewDecoder(file) 54 | if err := decoder.Decode(target); err != nil { 55 | panic(fmt.Sprintf("Failed to parse %s! Please re-check the file for mistakes. Error: %s", file.Name(), err)) 56 | } 57 | } 58 | 59 | func saveSettings(path string, source interface{}) { 60 | file, err := os.Create(path) 61 | if err != nil && !os.IsExist(err) { 62 | panic(err) 63 | } 64 | 65 | encoder := json.NewEncoder(file) 66 | encoder.SetIndent("", "\t") 67 | 68 | if err := encoder.Encode(source); err != nil { 69 | panic(err) 70 | } 71 | 72 | if err := file.Close(); err != nil { 73 | panic(err) 74 | } 75 | } 76 | 77 | func detectOldSettings(path string) bool { 78 | f, err := ioutil.ReadFile(path) 79 | if err != nil { 80 | return false 81 | } 82 | if strings.Contains(string(f), "BitrateTargets") { 83 | err = os.Rename(path, path+".old") 84 | if err != nil { 85 | panic(err) 86 | } 87 | return true 88 | } 89 | return false 90 | } 91 | -------------------------------------------------------------------------------- /settings/settings.go: -------------------------------------------------------------------------------- 1 | package settings 2 | 3 | var Debug bool 4 | var MixAudio bool 5 | var NormAudio bool 6 | 7 | type fileformat struct { 8 | General *general 9 | Encoding *encoding 10 | } 11 | 12 | type Vid struct { 13 | UUID string 14 | Input *InputStats 15 | Output *Out 16 | InFile string 17 | OutFile string 18 | Time *Time 19 | } 20 | 21 | type Out struct { 22 | FPS *FPS 23 | Force *Force 24 | Encoder *Encoder 25 | AEncoder *AudioEncoder 26 | Settings *Limit 27 | Bitrate *Bitrates 28 | AudioFile string 29 | APassthrough bool 30 | } 31 | 32 | type Time struct { 33 | Start float64 34 | Duration float64 35 | } 36 | 37 | type InputStats struct { 38 | Width int 39 | Height int 40 | FPS *FPS 41 | Bitrate *Bitrates 42 | Duration float64 43 | ACodec string 44 | VCodec string 45 | Pixfmt string 46 | ATracks int 47 | AChannels int 48 | } 49 | 50 | type Bitrates struct { 51 | Total int 52 | Audio int 53 | Video int 54 | } 55 | 56 | type FPS struct { 57 | N int 58 | D int 59 | } 60 | 61 | type Force struct { 62 | Video string 63 | Audio string 64 | Container string 65 | } 66 | -------------------------------------------------------------------------------- /uploader/catbox.go: -------------------------------------------------------------------------------- 1 | package uploader 2 | 3 | import ( 4 | "github.com/wabarc/go-catbox" 5 | "log" 6 | ) 7 | 8 | func catboxUpload(path string) string { 9 | url, err := catbox.New(nil).Upload(path) 10 | 11 | if err != nil { 12 | log.Println(err) 13 | panic("Catbox upload failed!") 14 | } 15 | 16 | return url 17 | } 18 | -------------------------------------------------------------------------------- /uploader/uploader.go: -------------------------------------------------------------------------------- 1 | package uploader 2 | 3 | import ( 4 | "github.com/vladaad/discordcompressor/settings" 5 | "log" 6 | "os" 7 | ) 8 | 9 | func Upload(path string) string { 10 | // Checking if filesize is under limit 11 | file, err := os.Stat(path) 12 | if err != nil { 13 | panic(err) 14 | } 15 | 16 | if file.Size() > int64(settings.General.UploadMaxMB*1048576) { // 1024^2 17 | log.Println("The video has exceeded the set upload limit! Please reduce the size parameter.") 18 | return "" 19 | } 20 | 21 | // Upload 22 | log.Println("Uploading...") 23 | switch settings.General.UploadService { 24 | case "catbox": 25 | return catboxUpload(path) 26 | default: 27 | log.Println("Upload service name invalid!") 28 | return "" 29 | } 30 | } -------------------------------------------------------------------------------- /utils/updatecheck.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/vladaad/discordcompressor/build" 6 | "log" 7 | "net/http" 8 | "strings" 9 | "time" 10 | ) 11 | 12 | // Stolen from danser-go 13 | 14 | func CheckForUpdates() { 15 | if strings.Contains(build.VERSION, "dev") { //false positive, those are changed during compile 16 | return 17 | } 18 | 19 | request, err := http.NewRequest(http.MethodGet, "https://api.github.com/repos/vladaad/discordcompressor/releases/latest", nil) 20 | if err != nil { 21 | log.Println("Failed to check for updates - Can't create request") 22 | return 23 | } 24 | 25 | client := new(http.Client) 26 | response, err := client.Do(request) 27 | 28 | if err != nil || response.StatusCode != 200 { 29 | log.Println("Failed to check for updates - Can't get release info from GitHub") 30 | return 31 | } 32 | 33 | defer func() { 34 | err := response.Body.Close() 35 | if err != nil { 36 | panic(err) 37 | } 38 | }() 39 | 40 | var data struct { 41 | URL string `json:"html_url"` 42 | Tag string `json:"tag_name"` 43 | } 44 | 45 | err = json.NewDecoder(response.Body).Decode(&data) 46 | if err != nil { 47 | log.Println("Failed to check for updates - Failed to decode the response from GitHub") 48 | return 49 | } 50 | 51 | if data.Tag != build.VERSION { 52 | log.Println("You're using an older version of DiscordCompressor.") 53 | log.Println("You can download a newer version here:", data.URL) 54 | time.Sleep(time.Second * 2) 55 | } else { 56 | log.Println("DiscordCompressor is up to date!") 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /utils/utils.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "github.com/atotto/clipboard" 5 | "github.com/vladaad/discordcompressor/build" 6 | "log" 7 | "os" 8 | "os/exec" 9 | "path/filepath" 10 | "runtime" 11 | "strings" 12 | ) 13 | 14 | func SettingsDir() string { 15 | if build.BUILD == "portable" { 16 | fpath, _ := os.Executable() 17 | return filepath.Dir(fpath) 18 | } else { 19 | switch runtime.GOOS { 20 | case "windows": 21 | return os.Getenv("APPDATA") + "\\vladaad\\dc" 22 | default: 23 | home, _ := os.UserHomeDir() 24 | return home + "/.config/vladaad/dc" 25 | } 26 | } 27 | } 28 | 29 | func CheckIfPresent(filename string) bool { 30 | _, err := exec.Command(filename).Output() 31 | if err == nil { 32 | return true 33 | } 34 | return !strings.Contains(err.Error(), "executable file not found") 35 | } 36 | 37 | func GetArg(args string, argToFind string) string { 38 | split1 := strings.Split(args, argToFind) 39 | if len(split1) < 2 { 40 | return "" 41 | } 42 | split2 := strings.Split(split1[1], " ") 43 | return split2[1] 44 | } 45 | 46 | func PasteIntoClipboard(string string) { 47 | err := clipboard.WriteAll(string) 48 | if err != nil { 49 | log.Println("Error pasting into clipboard") 50 | } 51 | } 52 | --------------------------------------------------------------------------------