GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — plugdata/Source/PluginProcessor.cpp at develop · plugdata-team/plugdata Expand file tree/ Copy pathPluginProcessor.cppMore file actions 2369 lines (1960 loc) · 83.5 KB / Copy pathPluginProcessor.cppFile metadata and controls2369 lines (1960 loc) · 83.5 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 /* // Copyright (c) 2021-2025 Timothy Schoen // For information on usage and redistribution, and for a DISCLAIMER OF ALL // WARRANTIES, see the file, "LICENSE.txt," in this distribution. */ #include <clocale> #include <memory> #include <fstream> #include <juce_gui_basics/juce_gui_basics.h> #include <juce_audio_basics/juce_audio_basics.h> #include <juce_dsp/juce_dsp.h> #include "PluginProcessor.h" #include "Pd/Library.h" #include "Utility/Config.h" #include "Utility/Fonts.h" #include "Utility/SettingsFile.h" #include "Utility/PluginParameter.h" #include "Utility/OSUtils.h" #include "Utility/MidiDeviceManager.h" #include "Utility/Autosave.h" #include "Utility/Decompress.h" #include "Standalone/InternalSynth.h" #include "Utility/Presets.h" #include "Canvas.h" #include "PluginMode.h" #include "PluginEditor.h" #include "LookAndFeel.h" #include "Object.h" #include "Statusbar.h" #include "Toolbar.h" #include "Dialogs/Dialogs.h" #include "Components/ConnectionMessageDisplay.h" #include "Utility/Recorder.h" #include "Sidebar/Sidebar.h" #include "Object.h" extern "C" { #include <pd-cyclone/shared/common/file.h> EXTERN char* pd_version; } AudioProcessor::BusesProperties PluginProcessor::buildBusesProperties() { #if JUCE_IOS if (ProjectInfo::isStandalone) { return BusesProperties().withOutput("Output", AudioChannelSet::stereo(), true).withInput("Input", AudioChannelSet::mono(), true); } // If you intend to build AUv3 on macOS, you'll also need these if (ProjectInfo::isFx) { return BusesProperties().withOutput("Output", AudioChannelSet::stereo(), true).withInput("Input", AudioChannelSet::stereo(), true); } else { return BusesProperties().withOutput("Output", AudioChannelSet::stereo(), true); } #else AudioProcessor::BusesProperties busesProperties; if (ProjectInfo::isStandalone) { busesProperties.addBus(true, "Main Input", AudioChannelSet::stereo(), true); busesProperties.addBus(false, "Main Output", AudioChannelSet::stereo(), true); } else { busesProperties.addBus(true, "Main Input", AudioChannelSet::stereo(), true); for (int i = 1; i < numInputBuses; i++) busesProperties.addBus(true, "Aux Input " + String(i), AudioChannelSet::stereo(), false); busesProperties.addBus(false, "Main Output", AudioChannelSet::stereo(), true); for (int i = 1; i < numOutputBuses; i++) busesProperties.addBus(false, "Aux Output" + String(i), AudioChannelSet::stereo(), false); } return busesProperties; #endif } // ag: Note that this is just a fallback, we update this with live version // data from the external if we have it. String PluginProcessor::pdlua_version = "pdlua 0.12.0 (lua 5.4)"; PluginProcessor::PluginProcessor() : AudioProcessor(buildBusesProperties()) , internalSynth(std::make_unique<InternalSynth>()) , hostInfoUpdater(this) { #if PERFETTO MelatoninPerfetto::get().beginSession(); #endif // Make sure to use dots for decimal numbers, pd requires that std::setlocale(LC_NUMERIC, "C"); { MessageManagerLock const mmLock; // Do we need this? Isn't this already on the messageManager? LookAndFeel::setDefaultLookAndFeel(&lnf.get()); // Initialise directory structure and settings file, do this only once if we're inside the DAW static bool filesystemInitialised = false; if (!filesystemInitialised) { auto succeeded = initialiseFilesystem(); if (!succeeded) { logError("Failed to initialise filesystem. Is the disk full?"); } filesystemInitialised = true; } settingsFile = SettingsFile::getInstance()->initialise(); } toolbarSource = std::make_unique<ToolbarSource>(); auto* volumeParameter = new PlugDataParameter(this, "volume", 0.8f, true, 0, 0.0f, 1.0f); addParameter(volumeParameter); volume = volumeParameter->getValuePointer(); // XML tree for storing additional data in DAW session extraData = std::make_unique<XmlElement>("ExtraData"); // General purpose automation parameters you can get by using "receive param1" etc. for (int n = 0; n < numParameters; n++) { auto* parameter = new PlugDataParameter(this, "param" + String(n + 1), 0.0f, false, n + 1, 0.0f, 1.0f); addParameter(parameter); } // Make sure that the parameter valuetree has a name, to prevent assertion failures // parameters.replaceState(ValueTree("plugdata")); logMessage("plugdata v" + String(ProjectInfo::versionString)); auto const gitHash = String(PLUGDATA_GIT_HASH); if (gitHash.isNotEmpty()) { logMessage("Nightly build: " + gitHash); } logMessage("Based on " + String(pd_version).upToFirstOccurrenceOf("(", false, false)); logMessage("Libraries:"); logMessage(else_version); logMessage(cyclone_version); #if ENABLE_GEM logMessage(gem_version); #endif logMessage(heavylib_version); // Set up midi buffers midiBufferInternalSynth.ensureSize(2048); atoms_playhead.reserve(3); atoms_playhead.resize(1); autosave = std::make_unique<Autosave>(this); auto themeName = settingsFile->getProperty<String>("theme"); // Make sure theme exists if (!settingsFile->getTheme(themeName)) { settingsFile->setProperty("theme", PlugDataLook::selectedThemes[0]); themeName = PlugDataLook::selectedThemes[0]; } setTheme(themeName, true); settingsFile->saveSettings(); oversampling = std::clamp(settingsFile->getProperty<int>("oversampling"), 0, 3); setEnableLimiter(settingsFile->getProperty<int>("protected")); setLimiterThreshold(settingsFile->getProperty<int>("limiter_threshold")); if (ProjectInfo::isStandalone) { midiDeviceManager.setInternalSynthPort(settingsFile->getProperty<int>("internal_synth")); } else { midiDeviceManager.setInternalSynthPort(0); } recorder = std::make_unique<Recorder>(); auto currentThemeTree = settingsFile->getCurrentTheme(); // ag: This needs to be done *after* the library data has been unpacked on // first launch. initialisePd(pdlua_version); logMessage(pdlua_version); updateSearchPaths(); objectLibrary = std::make_unique<pd::Library>(this); setLatencySamples(pd::Instance::getBlockSize()); settingsFile->startChangeListener(); midiDeviceManager.loadMidiSettings(); sendMessagesFromQueue(); startDSP(); } PluginProcessor::~PluginProcessor() { // Deleting the pd instance in ~PdInstance() will also free all the Pd patches patches.clear(); #if PERFETTO MelatoninPerfetto::get().endSession(); #endif } void PluginProcessor::flushMessageQueue() { setThis(); messageDispatcher->dequeueMessages(); } void PluginProcessor::doubleFlushMessageQueue() { setThis(); lockAudioThread(); messageDispatcher->dequeueMessages(); messageDispatcher->dequeueMessages(); unlockAudioThread(); } #if JUCE_IOS void PluginProcessor::syncDirectoryFiles(File const& sourceDir, File const& targetDir, Time lastInitTime, bool deleteIfNotExists) { if (!sourceDir.exists() || !targetDir.exists()) { return; } // Cache frequently used values bool const hasValidLastInitTime = lastInitTime.toMilliseconds() > 0; String const deleteFlag = deleteIfNotExists ? "true" : "false"; // Get all source files once and build a lookup map for efficiency auto sourceFiles = sourceDir.findChildFiles(File::TypesOfFileToFind::findFiles, true); std::unordered_set<String> sourceFileSet; sourceFileSet.reserve(sourceFiles.size()); // Phase 1: Copy files from source to target (update newer files) for (auto const& sourceFile : sourceFiles) { auto const relativePath = sourceFile.getRelativePathFrom(sourceDir); sourceFileSet.insert(relativePath.toStdString()); auto const targetFile = targetDir.getChildFile(relativePath); // Create directory structure if needed auto const parentDir = targetFile.getParentDirectory(); if (!parentDir.exists()) { parentDir.createDirectory(); } // Copy if target doesn't exist or source is newer if (!targetFile.exists()) { sourceFile.copyFileTo(targetFile); } else { auto const sourceModTime = sourceFile.getLastModificationTime(); auto const targetModTime = targetFile.getLastModificationTime(); if (sourceModTime > targetModTime) { sourceFile.copyFileTo(targetFile); } } } // Phase 2: Delete files in target that don't exist in source (only if deleteIfNotExists is true) if (deleteIfNotExists) { auto targetFiles = targetDir.findChildFiles(File::TypesOfFileToFind::findFiles, true); // Pre-cache directory modification times to prevent updates during deletion HashMap<String, Time> directoryModTimes; std::unordered_set<String> uniqueDirPaths; for (auto const& targetFile : targetFiles) { auto const parentPath = targetFile.getParentDirectory().getFullPathName(); if (uniqueDirPaths.find(parentPath.toStdString()) == uniqueDirPaths.end()) { uniqueDirPaths.insert(parentPath.toStdString()); directoryModTimes.set(parentPath, targetFile.getParentDirectory().getLastModificationTime()); } } SmallArray<File> directoriesToCleanup; std::unordered_set<String> cleanupDirPaths; // Prevent duplicates for (auto const& targetFile : targetFiles) { auto const relativePath = targetFile.getRelativePathFrom(targetDir); // Check if file exists in source using our pre-built set if (sourceFileSet.find(relativePath.toStdString()) == sourceFileSet.end()) { // File doesn't exist in source - candidate for deletion bool shouldDelete = true; if (hasValidLastInitTime) { auto const parentPath = targetFile.getParentDirectory().getFullPathName(); auto const dirModTime = directoryModTimes[parentPath]; auto const fileModTime = targetFile.getLastModificationTime(); // Don't delete if either the directory OR the file was modified after last init // This handles both renamed files (dir mod time) and copied files (file mod time) if (dirModTime > lastInitTime || fileModTime > lastInitTime) { shouldDelete = false; } } if (shouldDelete) { auto const parentDir = targetFile.getParentDirectory(); auto const parentPath = parentDir.getFullPathName(); targetFile.deleteFile(); // Add parent directory to cleanup list (avoid duplicates) if (cleanupDirPaths.find(parentPath.toStdString()) == cleanupDirPaths.end()) { cleanupDirPaths.insert(parentPath.toStdString()); directoriesToCleanup.add(parentDir); } } } } // Clean up empty directories (process from deepest to shallowest) for (auto const& parentDir : directoriesToCleanup) { auto currentDir = parentDir; while (currentDir != targetDir) { // Check if directory is empty (ignoring hidden files) auto const filesInDir = currentDir.findChildFiles(File::TypesOfFileToFind::findFiles, false); bool isEmpty = true; for (auto const& file : filesInDir) { if (!file.isHidden()) { isEmpty = false; break; } } if (isEmpty) { auto const parentRelativePath = currentDir.getRelativePathFrom(targetDir); if (!sourceDir.getChildFile(parentRelativePath).exists()) { auto const nextParent = currentDir.getParentDirectory(); currentDir.deleteRecursively(); currentDir = nextParent; } else { break; // Directory exists in source, keep it } } else { break; // Directory is not empty, stop } } } } } #endif bool PluginProcessor::initialiseFilesystem() { auto const& homeDir = ProjectInfo::appDataDir; auto const& versionDataDir = ProjectInfo::versionDataDir; auto const dekenDir = homeDir.getChildFile("Externals"); auto const patchesDir = homeDir.getChildFile("Patches"); FileSystemWatcher::addGlobalIgnorePath(homeDir.getChildFile("Toolchain")); #if !JUCE_WINDOWS if (!homeDir.exists()) homeDir.createDirectory(); #endif auto const initMutex = homeDir.getChildFile(".initialising"); // If this is true, another instance of plugdata is already initialising // We wait a maximum of 5 seconds before we continue initialising, to prevent problems int wait = 0; while (initMutex.exists() && wait < 20) { Time::waitForMillisecondCounter(Time::getMillisecondCounter() + 500); wait++; } initMutex.create(); bool extractionCompleted = true; // Check if the abstractions directory exists, if not, unzip it from binaryData if (!versionDataDir.exists()) { extractionCompleted = false; auto filesystem = BinaryData::getResource(BinaryData::Filesystem); versionDataDir.getParentDirectory().createDirectory(); int constexpr maxRetries = 3; int retryCount = 0; while (!extractionCompleted && retryCount < maxRetries) { auto tempVersionDataDir = versionDataDir.getSiblingFile("plugdata_version"); tempVersionDataDir.deleteRecursively(); if (!tempVersionDataDir.getParentDirectory().createDirectory()) { retryCount++; continue; } if (!Decompress::extractTarXz((uint8_t*)filesystem.data(), filesystem.size(), tempVersionDataDir.getParentDirectory(), 40 * 1024 * 1024)) { retryCount++; continue; } extractionCompleted = OSUtils::moveFileTo(tempVersionDataDir, versionDataDir); if (!extractionCompleted) { retryCount++; Thread::sleep(100); } } } if (!dekenDir.exists()) { dekenDir.createDirectory(); } #if !JUCE_IOS if (!patchesDir.exists()) { patchesDir.createDirectory(); } #endif auto const testTonePatch = homeDir.getChildFile("testtone.pd"); auto const cpuTestPatch = homeDir.getChildFile("load-meter.pd"); if (testTonePatch.exists()) testTonePatch.deleteFile(); if (cpuTestPatch.exists()) cpuTestPatch.deleteFile(); File(versionDataDir.getChildFile("./Documentation/7.stuff/tools/testtone.pd")).copyFileTo(testTonePatch); File(versionDataDir.getChildFile("./Documentation/7.stuff/tools/load-meter.pd")).copyFileTo(cpuTestPatch); auto createLinkWithRetry = [&extractionCompleted](File const& linkPath, File const& targetPath, int const maxRetries = 3) { for (int retry = 0; retry < maxRetries; retry++) { #if JUCE_WINDOWS // Clean up existing link/directory if (linkPath.exists()) { linkPath.deleteRecursively(); } if (OSUtils::createJunction(linkPath.getFullPathName().replaceCharacters("/", "\\").toStdString(), targetPath.getFullPathName().toStdString())) return; #else if (linkPath.exists()) { linkPath.deleteRecursively(); } if (targetPath.createSymbolicLink(linkPath, true)) return; #endif if (retry < maxRetries - 1) { Thread::sleep(100); } } extractionCompleted = false; }; // We always want to update the symlinks in case an older version of plugdata was used #if JUCE_WINDOWS // Get paths that need symlinks auto abstractionsPath = versionDataDir.getChildFile("Abstractions").getFullPathName().replaceCharacters("/", "\\"); auto documentationPath = versionDataDir.getChildFile("Documentation").getFullPathName().replaceCharacters("/", "\\"); auto extraPath = versionDataDir.getChildFile("Extra").getFullPathName().replaceCharacters("/", "\\"); createLinkWithRetry(homeDir.getChildFile("Abstractions"), versionDataDir.getChildFile("Abstractions")); createLinkWithRetry(homeDir.getChildFile("Documentation"), versionDataDir.getChildFile("Documentation")); createLinkWithRetry(homeDir.getChildFile("Extra"), versionDataDir.getChildFile("Extra")); auto shortcut = File::getSpecialLocation(File::SpecialLocationType::userDocumentsDirectory).getChildFile("plugdata.LNK"); ProjectInfo::appDataDir.createShortcut("plugdata", shortcut); #elif JUCE_IOS createLinkWithRetry(homeDir.getChildFile("Abstractions"), versionDataDir.getChildFile("Abstractions")); createLinkWithRetry(homeDir.getChildFile("Documentation"), versionDataDir.getChildFile("Documentation")); createLinkWithRetry(homeDir.getChildFile("Extra"), versionDataDir.getChildFile("Extra")); auto docsPatchesDir = File::getSpecialLocation(File::SpecialLocationType::userDocumentsDirectory).getChildFile("Patches"); if (patchesDir.isSymbolicLink()) { patchesDir.deleteRecursively(); } if (docsPatchesDir.isSymbolicLink()) { docsPatchesDir.deleteRecursively(); } patchesDir.createDirectory(); docsPatchesDir.createDirectory(); // On iOS, only the standalone can actually access the "patches" folder through the file manager. So we have to do this copying step to make sure it gets synced with our shared "Patches" folder // Thanks to Reinissance for figuring out the copying logic! if (ProjectInfo::isStandalone) { // Read last standalone initialization time auto timestampFile = homeDir.getChildFile(".standalone_last_init"); Time lastInitTime; if (timestampFile.existsAsFile()) { auto timestampString = timestampFile.loadFileAsString().trim(); if (timestampString.isNotEmpty()) { lastInitTime = Time(timestampString.getLargeIntValue()); } } else { // If the file doesn't exist, we assume this is the first run lastInitTime = Time::getCurrentTime(); // Create the file to store the current time timestampFile.create(); } // Sync files both ways: documents -> shared and shared -> documents // Pass the last init time to prevent deletion of files created by AUv3 apps after standalone was last initialized syncDirectoryFiles(patchesDir, docsPatchesDir, lastInitTime, true); // Copy newer files from shared to documents and delete files that don't exist there in shared syncDirectoryFiles(docsPatchesDir, patchesDir, lastInitTime); // Copy newer files from documents to shared // Store current time as the last initialization time for next run... auto currentTime = Time::getCurrentTime(); timestampFile.replaceWithText(String(currentTime.toMilliseconds())); } #else createLinkWithRetry(homeDir.getChildFile("Abstractions"), versionDataDir.getChildFile("Abstractions")); createLinkWithRetry(homeDir.getChildFile("Documentation"), versionDataDir.getChildFile("Documentation")); createLinkWithRetry(homeDir.getChildFile("Extra"), versionDataDir.getChildFile("Extra")); #endif initMutex.deleteFile(); return extractionCompleted; } void PluginProcessor::updateSearchPaths() { // Reload pd search paths from settings auto const& pathTree = settingsFile->getProperty<VarArray>("paths"); setThis(); lockAudioThread(); libpd_clear_search_path(); auto paths = SmallArray<File, 12>(pd::Library::defaultPaths.begin(), pd::Library::defaultPaths.end()); for (auto child : pathTree) { auto path = child.toString().replace("\\", "/"); paths.add_unique(path); } for (auto const& path : paths) { libpd_add_to_search_path(path.getFullPathName().toRawUTF8()); } for (auto const& path : DekenInterface::getExternalPaths()) { libpd_add_to_search_path(path.replace("\\", "/").toRawUTF8()); } auto librariesTree = settingsFile->getProperty<VarArray>("libraries"); for (auto& library : librariesTree) { if (library.toString().isEmpty()) { librariesTree.remove(&library); } } // Load startup libraries that the user defined in settings for (auto library : librariesTree) { auto const libName = library.toString(); // Load the library: this must be done after updating paths // If the library is already loaded, it will return true // This will load the libraries directly instead of on restart, not sure if Pd does that but it's actually nice if (!loadLibrary(libName)) { logError("Failed to load library: " + libName); } } if (SettingsFile::getInstance()->getProperty<bool>("enable_gem")) { libpd_add_to_search_path(ProjectInfo::appDataDir.getChildFile("Abstractions").getChildFile("Gem").getFullPathName().toRawUTF8()); loadLibrary("Gem"); } unlockAudioThread(); } String const PluginProcessor::getName() const { return ProjectInfo::projectName; } bool PluginProcessor::acceptsMidi() const { #if JUCE_IOS return !ProjectInfo::isFx; #endif return true; } bool PluginProcessor::producesMidi() const { #if JUCE_IOS return ProjectInfo::isStandalone; #endif return true; } bool PluginProcessor::isMidiEffect() const { return ProjectInfo::isMidiEffect(); } double PluginProcessor::getTailLengthSeconds() const { return getValue<float>(tailLength); } int PluginProcessor::getNumPrograms() { return Presets::presets.size(); } int PluginProcessor::getCurrentProgram() { return lastSetProgram; } void PluginProcessor::setCurrentProgram(int const index) { if (isPositiveAndBelow(index, Presets::presets.size())) { MemoryOutputStream data; Base64::convertFromBase64(data, Presets::presets[index].second); if (data.getDataSize() > 0) { setStateInformation(data.getData(), static_cast<int>(data.getDataSize())); lastSetProgram = index; } } } String const PluginProcessor::getProgramName(int const index) { if (isPositiveAndBelow(index, Presets::presets.size())) { return Presets::presets[index].first; } return "Init preset"; } void PluginProcessor::changeProgramName(int index, String const& newName) { } void PluginProcessor::setOversampling(int const amount) { settingsFile->setProperty("oversampling", var(amount)); if (oversampling == amount) return; oversampling = amount; auto const blockSize = AudioProcessor::getBlockSize(); auto const sampleRate = AudioProcessor::getSampleRate(); suspendProcessing(true); prepareToPlay(sampleRate, blockSize); suspendProcessing(false); } void PluginProcessor::setLimiterThreshold(int const amount) { auto const threshold = StackArray<float, 4> { -12.f, -6.f, 0.f, 3.f }[amount]; limiter.setThreshold(threshold); settingsFile->setProperty("limiter_threshold", var(amount)); } void PluginProcessor::setEnableLimiter(bool const enabled) { enableLimiter = enabled; } bool PluginProcessor::getEnableLimiter() { return enableLimiter; } void PluginProcessor::numChannelsChanged() { auto const blockSize = AudioProcessor::getBlockSize(); auto const sampleRate = AudioProcessor::getSampleRate(); suspendProcessing(true); prepareToPlay(sampleRate, blockSize); suspendProcessing(false); } void PluginProcessor::prepareToPlay(double const sampleRate, int const samplesPerBlock) { if (approximatelyEqual(sampleRate, 0.0)) return; float const oversampleFactor = 1 << oversampling; auto maxChannels = std::max(getTotalNumInputChannels(), getTotalNumOutputChannels()); prepareDSP(getTotalNumInputChannels(), getTotalNumOutputChannels(), sampleRate * oversampleFactor); oversampler = std::make_unique<dsp::Oversampling<float>>(std::max(1, maxChannels), oversampling, dsp::Oversampling<float>::filterHalfBandPolyphaseIIR, false); oversampler->initProcessing(samplesPerBlock); auto const internalSynthPort = midiDeviceManager.getInternalSynthPort(); if (internalSynthPort >= 0 && ProjectInfo::isStandalone) { internalSynth->prepare(sampleRate, samplesPerBlock); } recorder->prepare(sampleRate, getTotalNumOutputChannels()); audioAdvancement = 0; auto const pdBlockSize = static_cast<size_t>(Instance::getBlockSize()); audioBufferIn.setSize(maxChannels, pdBlockSize); audioBufferOut.setSize(maxChannels, pdBlockSize); audioVectorIn.resize(maxChannels * pdBlockSize, 0.0f); audioVectorOut.resize(maxChannels * pdBlockSize, 0.0f); // If the block size is a multiple of 64 and we are not a plugin, we can optimise the process loop // Audio plugins can choose to send in a smaller block size when automation is happening variableBlockSize = !ProjectInfo::isStandalone || samplesPerBlock < pdBlockSize || samplesPerBlock % pdBlockSize != 0; if (variableBlockSize) { inputFifo = std::make_unique<AudioMidiFifo>(maxChannels, std::max<int>(pdBlockSize, samplesPerBlock * oversampleFactor) * 3); outputFifo = std::make_unique<AudioMidiFifo>(maxChannels, std::max<int>(pdBlockSize, samplesPerBlock * oversampleFactor) * 3); outputFifo->writeSilence(Instance::getBlockSize()); } midiByteIndex = 0; midiByteBuffer[0] = 0; midiByteBuffer[1] = 0; midiByteBuffer[2] = 0; midiBufferInternalSynth.ensureSize(2048); midiDeviceManager.prepareToPlay(sampleRate * oversampleFactor); cpuLoadMeasurer.reset(sampleRate, samplesPerBlock); toolbarSource->setSampleRate(sampleRate); toolbarSource->setBufferSize(samplesPerBlock); toolbarSource->prepareToPlay(getTotalNumOutputChannels()); limiter.prepare({ sampleRate, static_cast<uint32>(samplesPerBlock), std::max(1u, static_cast<uint32>(maxChannels)) }); smoothedGain.reset(AudioProcessor::getSampleRate(), 0.02); if (!ProjectInfo::isStandalone) { backupRunLoopInterval = static_cast<int>(samplesPerBlock / sampleRate * 2000.0); backupRunLoopInterval = jmax(24, backupRunLoopInterval); backupRunLoop.startTimer(backupRunLoopInterval * 32); } } bool PluginProcessor::isBusesLayoutSupported(BusesLayout const& layouts) const { #if JUCE_IOS return (layouts.getMainOutputChannels() <= 2) && (layouts.getMainInputChannels() <= 2); #endif #if JucePlugin_IsMidiEffect ignoreUnused(layouts); return true; #endif int ninch = 0; int noutch = 0; for (int bus = 0; bus < layouts.outputBuses.size(); bus++) { int const nchb = layouts.getNumChannels(false, bus); if (layouts.outputBuses[bus].isDisabled()) continue; if (nchb == 0) return false; noutch += nchb; } for (int bus = 0; bus < layouts.inputBuses.size(); bus++) { int const nchb = layouts.getNumChannels(true, bus); if (layouts.inputBuses[bus].isDisabled()) continue; if (nchb == 0) return false; ninch += nchb; } return ninch <= 32 && noutch <= 32; } void PluginProcessor::settingsChanged(String const& name, var const& value) { if (settingsFile) { if (name == "theme") { setTheme(value.toString()); return; } if (name == "themes") { // The selection's Value notification may still be pending when a theme is edited. setTheme(settingsFile->getProperty<String>("theme"), true); return; } if (name == "default_font") { PlugDataLook::setDefaultFont(value.toString()); CachedStringWidth<14>::clearCache(); CachedStringWidth<15>::clearCache(); for (auto* editor : getEditors()) editor->updateDefaultFont(); updateAllEditorsLNF(); return; } } if (!instance) return; if (name == "paths" || name == "libraries" || name == "enable_gem") { updateSearchPaths(); } } void PluginProcessor::settingsFileReloaded() { setTheme(settingsFile->getProperty<String>("theme"), true); updateSearchPaths(); if (objectLibrary) objectLibrary->updateLibrary(); } void PluginProcessor::processBlockBypassed(AudioBuffer<float>& buffer, MidiBuffer& midiBuffer) { bypassBuffer.makeCopyOf(buffer); // It's better to keep sending blocks into Pd, so messaging can still work and there are no gaps in the users' audio stream processBlock(bypassBuffer, midiBuffer); } void PluginProcessor::processBlock(AudioBuffer<float>& buffer, MidiBuffer& midiBuffer) { isProcessingAudio = true; ScopedNoDenormals noDenormals; AudioProcessLoadMeasurer::ScopedTimer cpuTimer(cpuLoadMeasurer, buffer.getNumSamples()); auto const totalNumInputChannels = getTotalNumInputChannels(); auto const totalNumOutputChannels = getTotalNumOutputChannels(); auto midiInputHistory = midiBuffer; setThis(); if (!ProjectInfo::isStandalone) { backupLoopLock.enter(); backupRunLoop.stopTimer(); backupLoopLock.exit(); } sendPlayhead(); for (int i = totalNumInputChannels; i < totalNumOutputChannels; ++i) { buffer.clear(i, 0, buffer.getNumSamples()); } auto targetBlock = dsp::AudioBlock<float>(buffer); auto const blockOut = oversampling > 0 ? oversampler->processSamplesUp(targetBlock) : targetBlock; if (variableBlockSize) { processVariable(blockOut, midiBuffer); } else { midiBuffer.clear(); processConstant(blockOut); } if (oversampling > 0) { oversampler->processSamplesDown(targetBlock); } auto const targetGain = volume->load(); float mappedTargetGain = 0.0f; // Slider value 0.8 is default unity // The top part of the slider 0.8 - 1.0 is mapped to linear gain 1.0 - 2.0 // The lower part of the slider 0.0 - 0.8 is mapped to a power function that approximates a log curve between 0.0 - 1.0 // // +---------+-----------------+-------+--------------+ // | Dynamic | a | b | Approximation| // | range | | | | // +---------+-----------------+-------+--------------+ // | 50 dB | 3.1623e-3 | 5.757 | x^3 | // | 60 dB | 1e-3 | 6.908 | x^4 | // | 70 dB | 3.1623e-4 | 8.059 | x^5 | // | 80 dB | 1e-4 | 9.210 | x^6 | // | 90 dB | 3.1623e-5 | 10.36 | x^6 | // | 100 dB | 1e-5 | 11.51 | x^7 | // +---------+-----------------+-------+--------------+ // Table 1: Values for a and b in the equation a·exp(b·x) // // https://www.dr-lex.be/info-stuff/volumecontrols.html if (targetGain <= 0.8f) mappedTargetGain = pow(jmap(targetGain, 0.0f, 0.8f, 0.0f, 1.0f), 2.5f); else mappedTargetGain = jmap(targetGain, 0.8f, 1.0f, 1.0f, 2.0f); // apply smoothing to the main volume control smoothedGain.setTargetValue(mappedTargetGain); smoothedGain.applyGain(buffer, buffer.getNumSamples()); midiDeviceManager.sendAndCollectMidiOutput(midiBuffer); auto const internalSynthPort = midiDeviceManager.getInternalSynthPort(); // If the internalSynth is enabled and loaded, let it process the midi if (internalSynthPort >= 0 && internalSynth->isReady()) { midiBufferInternalSynth.clear(); midiDeviceManager.dequeueMidiOutput(internalSynthPort, midiBufferInternalSynth, blockOut.getNumSamples()); internalSynth->process(buffer, midiBufferInternalSynth); } else if (internalSynthPort < 0 && internalSynth->isReady()) { internalSynth->unprepare(); } else if (internalSynthPort >= 0 && !internalSynth->isReady()) { internalSynth->prepare(getSampleRate(), AudioProcessor::getBlockSize()); } midiBufferInternalSynth.clear(); midiInputHistory.addEvents(midiDeviceManager.getInputHistory(), 0, buffer.getNumSamples(), 0); toolbarSource->process(midiInputHistory, midiDeviceManager.getOutputHistory()); midiDeviceManager.clearMidiOutputBuffers(blockOut.getNumSamples()); toolbarSource->setCPUUsage(cpuLoadMeasurer.getLoadAsPercentage()); toolbarSource->peakBuffer.write(buffer); // Record before limiter if (recorder->isRecording()) { recorder->write(buffer); toolbarSource->setRecorderTime(recorder->getElapsedSeconds()); } if (enableLimiter && buffer.getNumChannels() > 0) { // Take out inf and NaN values auto* const* writePtr = buffer.getArrayOfWritePointers(); for (int ch = 0; ch < buffer.getNumChannels(); ch++) { for (int n = 0; n < buffer.getNumSamples(); n++) { if (!std::isfinite(writePtr[ch][n])) { writePtr[ch][n] = 0.0f; } } } auto block = dsp::AudioBlock<float>(buffer); limiter.process(block); } // If we miss 4 audio blocks, start the backup scheduler if (!ProjectInfo::isStandalone) { backupLoopLock.enter(); backupRunLoop.startTimer(backupRunLoopInterval * 4); backupLoopLock.exit(); } isProcessingAudio = false; #if ENABLE_TESTING buffer.clear(); #endif } // only used for standalone, and if blocksize if a multiple of 64 void PluginProcessor::processConstant(dsp::AudioBlock<float> buffer) { int const pdBlockSize = Instance::getBlockSize(); int const numBlocks = buffer.getNumSamples() / pdBlockSize; for (int block = 0; block < numBlocks; block++) { if (producesMidi()) { midiByteIndex = 0; midiByteBuffer[0] = 0; midiByteBuffer[1] = 0; midiByteBuffer[2] = 0; } midiDeviceManager.dequeueMidiInput(pdBlockSize, [this](int const port, MidiBuffer const& buffer) { sendMidiBuffer(port, buffer); }); for (int ch = 0; ch < buffer.getNumChannels(); ch++) { // Copy the channel data into the vector FloatVectorOperations::copy( audioVectorIn.data() + ch * pdBlockSize, buffer.getChannelPointer(ch) + audioAdvancement, pdBlockSize); } setThis(); sendParameters(); keyHandler.sendKeyUpMessages(); sendMessagesFromQueue(); // Process audio performDSP(audioVectorIn.data(), audioVectorOut.data()); if (connectionListener && plugdata_debugging_enabled()) connectionListener.load()->updateSignalData(); for (int ch = 0; ch < buffer.getNumChannels(); ch++) { |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |