diff --git a/.editorconfig b/.editorconfig index 1d407f8..3ef9d03 100644 --- a/.editorconfig +++ b/.editorconfig @@ -10,6 +10,6 @@ indent_size = 4 insert_final_newline = true trim_trailing_whitespace = true -[*.{yml,yaml}] +[*.{jsx,yml,yaml}] indent_style = space indent_size = 2 diff --git a/CHANGELOG.md b/CHANGELOG.md index 249d41e..1d23972 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Version history +## Unreleased + +* **Fixed** After Effects script on macOS ([issue #77](https://github.com/DanielSWolf/rhubarb-lip-sync/issues/77), [issue #128](https://github.com/DanielSWolf/rhubarb-lip-sync/issues/128)) +* **Changed** the way you make Rhubarb available to After Effects on macOS. This used to be a `/usr/local/bin/` symlink but is now a `PATH` entry ([issue #143](https://github.com/DanielSWolf/rhubarb-lip-sync/issues/143)). For details, see the README file for Rhubarb for After Effects. + ## Version 1.13.0 * **Improved** animation rules for "F" sound when using just the basic mouth shapes. diff --git a/extras/AdobeAfterEffects/.prettierrc.yml b/extras/AdobeAfterEffects/.prettierrc.yml new file mode 100644 index 0000000..cdc3204 --- /dev/null +++ b/extras/AdobeAfterEffects/.prettierrc.yml @@ -0,0 +1,8 @@ +# Config file for Prettier, a JavaScript/TypeScript code formatter. + +useTabs: false +tabWidth: 2 +printWidth: 100 +singleQuote: true +arrowParens: avoid +trailingComma: none diff --git a/extras/AdobeAfterEffects/README.adoc b/extras/AdobeAfterEffects/README.adoc index f25a144..54f133b 100644 --- a/extras/AdobeAfterEffects/README.adoc +++ b/extras/AdobeAfterEffects/README.adoc @@ -1,4 +1,15 @@ -= Animation script for Adobe After Effects += Rhubarb for After Effects +:experimental: +:imagesdir: ../../img +:A: Ⓐ +:B: Ⓑ +:C: Ⓒ +:D: Ⓓ +:E: Ⓔ +:F: Ⓕ +:G: Ⓖ +:H: Ⓗ +:X: Ⓧ The script in this directory generates After Effects compositions with mouth animation. @@ -8,22 +19,69 @@ The script in this directory generates After Effects compositions with mouth ani Download the archive file containing Rhubarb Lip Sync, then extract in a directory on your computer. -=== 2. Make Rhubarb available to After Effects +=== 2. Add Rhubarb to the PATH environment variable -On *Windows*, add the Rhubarb directory (the directory containing `rhubarb.exe`) to your `PATH` environment variable. +After Effects needs to know where to find Rhubarb Lip Sync. +So you need to add the Rhubarb directory to your computer's PATH environment variable as follows: -On *OS X*, create a symbolic link to the executable (`rhubarb`) in `/usr/local/bin/`. You can do that by executing `ln -s /rhubarb-directory/rhubarb /usr/local/bin/` (make sure to replace `rhubarb-directory` with the actual directory). +*On Windows:* + +. *Copy the full path of the Rhubarb directory:* +* In the File Explorer, press and hold the kbd:[Shift] key while right-clicking on the Rhubarb directory (the directory containing `rhubarb`, `README.adoc`, etc.). +* In the context menu, select _Copy as path_. + +. *Add the Rhubarb directory to the PATH variable:* +* Press kbd:[Start] + kbd:[R] to open the Run dialog. +* Type `sysdm.cpl` and press kbd:[Enter] to open the System Properties window. +* In the System Properties window, go to the _Advanced_ tab and click the _Environment Variables..._ button. +* In the _Environment Variables_ window, under _System variables_, select the _Path_ variable, then click _Edit..._. +* In the Edit Environment Variable window, click _New_, then paste the path you copied earlier. +* Click _OK_ to close all windows. +* To make sure everything is working, open a new Command Prompt window by pressing kbd:[Start] + kbd:[R], typing `cmd`, and pressing kbd:[Enter]. Type `rhubarb --version` and press kbd:[Enter]. You should see the version number of Rhubarb Lip Sync. + +*On macOS:* + +. *Copy the full path of the Rhubarb directory:* +* In the Finder app, right-click on the Rhubarb directory (the directory containing `rhubarb`, `README.adoc`, etc.). +* While the context menu is open, press and hold the kbd:[Option] key. This will change some of the menu items. +* Select _Copy [...] as Pathname_. + +. *Open the Terminal app:* +* Click on the Spotlight search icon (the little magnifying glass) at the top-right of your screen. +* Into the search bar that opens, type "`terminal`", then press kbd:[Enter]. + +. *Add the Rhubarb directory to the PATH variable:* +* In the Terminal window, type `touch ~/.zshrc` and confirm with kbd:[Enter]. +* Next, type `open -e ~/.zshrc` and confirm with kbd:[Enter]. The TextEdit app should open with a file. +* If the file already contains text, move to the end of the file and add a new line. +* Type `export PATH="`, press kbd:[Cmd] + kbd:[V] to paste the path you copied earlier, then type `:$PATH"`. + +The resulting line should look something like `export PATH="/Users/Daniel/Rhubarb-Lip-Sync:$PATH"`. +* Save the file and close TextEdit. +* To make sure everything is working, close the terminal window, then open it again as described above. Type `rhubarb --version` and confirm with kbd:[Enter]. You should see the version number of Rhubarb Lip Sync. === 3. Install After Effects script -Copy (or symlink) the script file `Rhubarb Lip Sync.jsx` into your After Effects scripts directory. +In After Effects, go to _File_ > _Scripts_ > _Install Script File..._, then select the script file `Rhubarb Lip Sync.jsx` from the `extras/AdobeAfterEffects` subdirectory of Rhubarb Lip Sync. -On *Windows*, that directory is usually `C:\Program Files\Adobe\Adobe After Effects \Support Files\Scripts`. +Older After Effects versions don't have this command, so you'll have to manually copy (or symlink) the script file into your After Effects scripts directory. -On *OS X*, that directory is usually `Applications/Adobe After Effects /Scripts`. +* On *Windows*, that directory is usually `C:\Program Files\Adobe\Adobe After Effects \Support Files\Scripts`. +* On *OS X*, that directory is usually `Applications/Adobe After Effects /Scripts`. === 4. (Re-)start After Effects == How to use -In After Effects, select _File > Scripts > Rhubarb Lip Sync.jsx_. That will open a dialog window where you can specify the audio file with the dialog recording and a number of other options. To get information about any input field, just hover above it with your mouse and you’ll see a tooltip. +=== Create your mouth composition + +To start, you need a composition containing all your mouth shapes. +The first frame (`00:00`) should contain the {A} mouth shape, the second frame (`00:01`) should contain the {B} mouth shape, and so on. +The optional mouth shapes {G}, {H}, and {X} belong at `00:06`, `00:07`, and `00:08`, respectively. + +For your first experiments, check out the demo project in the `extras/AdobeAfterEffects/demo` directory. + +image:after-effects-setup.png[] + +=== Run Rhubarb for After Effects + +In After Effects, select _File > Scripts > Rhubarb Lip Sync.jsx_. That will open a dialog window where you can specify the audio file with the dialog recording and a number of other options. To get information about any input field, just hover above it with your mouse and you'll see a tooltip. diff --git a/extras/AdobeAfterEffects/Rhubarb Lip Sync.jsx b/extras/AdobeAfterEffects/Rhubarb Lip Sync.jsx index 6383b38..e7deafc 100644 --- a/extras/AdobeAfterEffects/Rhubarb Lip Sync.jsx +++ b/extras/AdobeAfterEffects/Rhubarb Lip Sync.jsx @@ -1,278 +1,336 @@ -// Polyfill for Object.assign -"function"!=typeof Object.assign&&(Object.assign=function(a,b){"use strict";if(null==a)throw new TypeError("Cannot convert undefined or null to object");for(var c=Object(a),d=1;d>>0;if("function"!=typeof r)throw new TypeError(r+" is not a function");for(arguments.length>1&&(t=arguments[1]),n=new Array(i),o=0;o>>0;if("function"!=typeof r)throw new TypeError(r+" is not a function");for(arguments.length>1&&(t=arguments[1]),n=new Array(i),o=0;o>>0;if("function"!=typeof r)throw new TypeError;for(arguments.length>1&&(e=t),n=0;n>>0,o=arguments[1],e=0;e>>0;if("function"!=typeof r)throw new TypeError;for(var i=[],o=arguments.length>=2?arguments[1]:void 0,n=0;n>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(arguments.length>1&&(c=b),d=0;d>>0;if(0===n)return!1;for(var i=0|t,o=Math.max(i>=0?i:n-Math.abs(i),0);o>>0;if(0===i)return-1;var o=0|t;if(o>=i)return-1;for(n=Math.max(o>=0?o:i-Math.abs(o),0);n>>0,t=arguments.length>=2?arguments[1]:void 0,n=0;np.length)p+=p.repeat(Math.ceil(l/p.length));return p.slice(0,l)+String(this)}); + // String.prototype.trim + String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}); + // JSON + "object"!=typeof JSON&&(JSON={}),function(){"use strict";function f(a){return a<10?"0"+a:a}function this_value(){return this.valueOf()}function quote(a){return rx_escapable.lastIndex=0,rx_escapable.test(a)?'"'+a.replace(rx_escapable,function(a){var b=meta[a];return"string"==typeof b?b:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function str(a,b){var c,d,e,f,h,g=gap,i=b[a];switch(i&&"object"==typeof i&&"function"==typeof i.toJSON&&(i=i.toJSON(a)),"function"==typeof rep&&(i=rep.call(b,a,i)),typeof i){case"string":return quote(i);case"number":return isFinite(i)?String(i):"null";case"boolean":case"null":return String(i);case"object":if(!i)return"null";if(gap+=indent,h=[],"[object Array]"===Object.prototype.toString.apply(i)){for(f=i.length,c=0;c>>0;if("function"!=typeof r)throw new TypeError;for(arguments.length>1&&(e=t),n=0;n>>0,o=arguments[1],e=0;e>>0;if("function"!=typeof r)throw new TypeError;for(var i=[],o=arguments.length>=2?arguments[1]:void 0,n=0;n>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(arguments.length>1&&(c=b),d=0;d>>0;if(0===n)return!1;for(var i=0|t,o=Math.max(i>=0?i:n-Math.abs(i),0);o>>0;if(0===i)return-1;var o=0|t;if(o>=i)return-1;for(n=Math.max(o>=0?o:i-Math.abs(o),0);n>>0,t=arguments.length>=2?arguments[1]:void 0,n=0;n= width ? n : new Array(width - n.length + 1).join(z) + n; +/** Indicates whether we're on a Windows machine. If `false`, we're on macOS. */ +var osIsWindows = (system.osName || $.os).match(/windows/i); + +/** + * Joins the given path elements with the OS-appropriate path separator. + * + * @param {...string} elements - The path elements. + */ +function joinPath() { + var separator = osIsWindows ? '\\' : '/'; + return toArray(arguments).join(separator); } -// Checks whether scripts are allowed to write files by creating and deleting a dummy file +/** Returns a `File` object in the temp directory with a unique file name based on the given one. */ +function getTempFile(fileName) { + var fileNameElements = fileName.split('.'); + fileNameElements.splice(fileNameElements.length > 1 ? -1 : 1, 0, createGuid()); + var uniqueFileName = fileNameElements.join('.'); + + return new File(joinPath(Folder.temp.fsName, uniqueFileName)); +} + +/** Indicates whether this AE script is allowed to write files. */ function canWriteFiles() { - try { - var file = new File(); - file.open('w'); - file.writeln(''); - file.close(); - file.remove(); - return true; - } catch (e) { - return false; - } + try { + var file = new File(); + file.open('w'); + file.writeln(''); + file.close(); + file.remove(); + return true; + } catch (e) { + return false; + } } +/** Returns the string contents of the given file. */ +function readTextFile(fileOrPath) { + var filePath = fileOrPath.fsName || fileOrPath; + var file = new File(filePath); + function check() { + if (file.error) throw new Error(format('Error reading file "{}": {}', filePath, file.error)); + } + + try { + file.open('r'); + check(); + file.encoding = 'UTF-8'; + check(); + var result = file.read(); + check(); + file.close(); + check(); + return result; + } catch (error) { + try { + file.close(); + } catch (e) {} + throw error; + } +} + +/** Creates of overwrites a file with the given string contents. */ +function writeTextFile(fileOrPath, text) { + var filePath = fileOrPath.fsName || fileOrPath; + var file = new File(filePath); + function check() { + if (file.error) throw new Error(format('Error writing file "{}": {}', filePath, file.error)); + } + + try { + file.open('w'); + check(); + file.encoding = 'UTF-8'; + check(); + file.write(text); + check(); + file.close(); + check(); + } catch (error) { + try { + file.close(); + } catch (e) {} + throw error; + } +} + +/** Escapes a CLI argument using OS-specific syntax. */ +function cliEscape(arg) { + if (osIsWindows) { + var trivial = arg.length > 0 && !/[ \t"]/.test(arg); + return trivial ? arg : format('"{}"', arg.replace(/([\\"])/g, '\\$1')); + } else { + var trivial = arg.length > 0 && !/[ \t\\$"'`]/i.test(arg); + return trivial ? arg : format('"{}"', arg.replace(/([\\$"`])/g, '\\$1')); + } +} + +/** + * Executes the given program with the given arguments. + * + * @param command - The name/path of the executable to run. + * @param {...*} args - The CLI arguments. + */ +function exec() { + var commandLine = toArray(arguments).map(cliEscape).join(' '); + + // On macOS, we need to run the command through zsh to get PATH resolution. + if (!osIsWindows) commandLine = format('zsh -i -c {}', cliEscape(commandLine)); + + return system.callSystem(commandLine); +} + +/** + * Shows a dialog with the given message strings or `Error` objects. + * + * @param {...*} args - The message strings or `Error` objects to display. + */ +function showErrorDialog() { + var message = toArray(arguments) + .map(function (arg) { + return arg instanceof Error ? arg.message : arg; + }) + .join('\n\n'); + Window.alert(message, scriptName, true /* show error icon */); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// After Effects-specific utils +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/** Converts a frame number within a given comp to an offset in seconds. */ function frameToTime(frameNumber, compItem) { - return frameNumber * compItem.frameDuration; + return frameNumber * compItem.frameDuration; } +/** Converts an offset in seconds within a given comp to a frame number. */ function timeToFrame(time, compItem) { - return time * compItem.frameRate; + return time * compItem.frameRate; +} + +/** + * Converts a frame number to a timecode string like '00:08'. + * The frame number is expected to be in the range [0, frame rate[. + */ +function frameToTimecode(frameNumber) { + return '00:' + String(frameNumber).padStart(2, '0'); } // To prevent rounding errors var epsilon = 0.001; +/** Indicates whether the given comp has visible content at the given frame number. */ function isFrameVisible(compItem, frameNumber) { - if (!compItem) return false; + if (!compItem) return false; - var time = frameToTime(frameNumber + epsilon, compItem); - var videoLayers = toArrayBase1(compItem.layers).filter(function(layer) { - return layer.hasVideo; - }); - var result = videoLayers.find(function(layer) { - return layer.activeAtTime(time); - }); - return Boolean(result); + var time = frameToTime(frameNumber + epsilon, compItem); + return toArray(compItem.layers).some(function (layer) { + return layer.hasVideo && layer.activeAtTime(time); + }); } -var appName = 'Rhubarb Lip Sync'; +/** Returns the path of a project item within the current project. */ +function getItemPath(item) { + if (item === app.project.rootFolder) return '/'; + if (item.parentFolder === app.project.rootFolder) return format('/ {}', item.name); + return format('{} / {}', getItemPath(item.parentFolder), item.name); +} + +/** Returns all project items representing audio files. */ +function getAudioFileProjectItems() { + return toArray(app.project.items).filter(function (item) { + var isAudioFootage = item instanceof FootageItem && item.hasAudio && !item.hasVideo; + return isAudioFootage; + }); +} + +/** + * In the given item control, selects the item with the specified text. + * If no such item exists, selects the first item, if present. + */ +function selectByTextOrFirst(itemControl, text) { + var targetItem = toArray(itemControl.items).find(function (item) { + return item.text === text; + }); + if (!targetItem && itemControl.items.length) { + targetItem = itemControl.items[0]; + } + if (targetItem) { + itemControl.selection = targetItem; + } +} + +/** + * Takes a callback returning a tree of controls created using factory functions and converts it + * into an ExtendScript resource string. + * This is less painful then writing the resource string manually. + */ +function createResourceString(callback) { + // prettier-ignore + var controlTypes = [ + 'dialog', 'palette', 'Panel', 'Group', 'TabbedPanel', 'Tab', 'Button', 'IconButton', 'Image', + 'StaticText', 'EditText', 'Checkbox', 'RadioButton', 'Progressbar', 'Slider', 'Scrollbar', + 'ListBox', 'DropDownList', 'TreeView', 'ListItem', 'FlashPlayer' + ]; + var factories = Object.fromEntries( + controlTypes.map(function (type) { + var key = type[0].toLowerCase() + type.slice(1); + return [ + key, + function (options) { + return Object.assign({ __type__: type }, options); + } + ]; + }) + ); + + var tree = callback(factories); + var jsonTree = JSON.stringify(tree, null, 2); + return jsonTree.replace(/(\{\s*)"__type__":\s*"(\w+)",?\s*/g, '$2 $1'); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Rhubarb-specific utils +//////////////////////////////////////////////////////////////////////////////////////////////////// var settingsFilePath = Folder.userData.fullName + '/rhubarb-ae-settings.json'; -function readTextFile(fileOrPath) { - var filePath = fileOrPath.fsName || fileOrPath; - var file = new File(filePath); - function check() { - if (file.error) throw new Error('Error reading file "' + filePath + '": ' + file.error); - } - try { - file.open('r'); check(); - file.encoding = 'UTF-8'; check(); - var result = file.read(); check(); - return result; - } finally { - file.close(); check(); - } -} - -function writeTextFile(fileOrPath, text) { - var filePath = fileOrPath.fsName || fileOrPath; - var file = new File(filePath); - function check() { - if (file.error) throw new Error('Error writing file "' + filePath + '": ' + file.error); - } - try { - file.open('w'); check(); - file.encoding = 'UTF-8'; check(); - file.write(text); check(); - } finally { - file.close(); check(); - } -} - +/** + * Returns the plugin settings previously stored using {@link writeSettingsFile}. + * Returns an empty object if no stored settings exist. + */ function readSettingsFile() { - try { - return JSON.parse(readTextFile(settingsFilePath)); - } catch (e) { - return {}; - } + try { + return JSON.parse(readTextFile(settingsFilePath)); + } catch (e) { + return {}; + } } +/** Stores an object containing plugin settings for later retrieval. */ function writeSettingsFile(settings) { - try { - writeTextFile(settingsFilePath, JSON.stringify(settings, null, 2)); - } catch (e) { - alert('Error persisting settings. ' + e.message); - } + try { + writeTextFile(settingsFilePath, JSON.stringify(settings, null, 2)); + } catch (e) { + throw new Error(format('Error persisting settings. {}', e.message)); + } } -var osIsWindows = (system.osName || $.os).match(/windows/i); - -// Depending on the operating system, the syntax for escaping command-line arguments differs. -function cliEscape(argument) { - return osIsWindows - ? '"' + argument + '"' - : "'" + argument.replace(/'/g, "'\\''") + "'"; -} - -function exec(command) { - return system.callSystem(command); -} - -function execInWindow(command) { - if (osIsWindows) { - system.callSystem('cmd /C "' + command + '"'); - } else { - // I didn't think it could be so complicated on OS X to open a new Terminal window, - // execute a command, then close the Terminal window. - // If you know a better solution, let me know! - var escapedCommand = command.replace(/"/g, '\\"'); - var appleScript = '\ - tell application "Terminal" \ - -- Quit terminal \ - -- Yes, that\'s undesirable if there was an open window before. \ - -- But all solutions I could find were at least as hacky. \ - quit \ - -- Open terminal \ - activate \ - -- Run command in new tab \ - set newTab to do script ("' + escapedCommand + '") \ - -- Wait until command is done \ - tell newTab \ - repeat while busy \ - delay 0.1 \ - end repeat \ - end tell \ - quit \ - end tell'; - exec('osascript -e ' + cliEscape(appleScript)); - } -} - -var rhubarbPath = osIsWindows ? 'rhubarb.exe' : '/usr/local/bin/rhubarb'; - -// ExtendScript's resource strings are a pain to write. -// This function allows them to be written in JSON notation, then converts them into the required -// format. -// For instance, this string: '{ "__type__": "StaticText", "text": "Hello world" }' -// is converted to this: 'StaticText { "text": "Hello world" }'. -// This code relies on the fact that, contrary to the language specification, all major JavaScript -// implementations keep object properties in insertion order. -function createResourceString(tree) { - var result = JSON.stringify(tree, null, 2); - result = result.replace(/(\{\s*)"__type__":\s*"(\w+)",?\s*/g, '$2 $1'); - return result; -} - -// Object containing functions to create control description trees. -// For instance, `controls.StaticText({ text: 'Hello world' })` -// returns `{ __type__: StaticText, text: 'Hello world' }`. -var controlFunctions = (function() { - var controlTypes = [ - // Strangely, 'dialog' and 'palette' need to start with a lower-case character - ['Dialog', 'dialog'], ['Palette', 'palette'], - 'Panel', 'Group', 'TabbedPanel', 'Tab', 'Button', 'IconButton', 'Image', 'StaticText', - 'EditText', 'Checkbox', 'RadioButton', 'Progressbar', 'Slider', 'Scrollbar', 'ListBox', - 'DropDownList', 'TreeView', 'ListItem', 'FlashPlayer' - ]; - var result = {}; - controlTypes.forEach(function(type){ - var isArray = Array.isArray(type); - var key = isArray ? type[0] : type; - var value = isArray ? type[1] : type; - result[key] = function(options) { - return Object.assign({ __type__: value }, options); - }; - }); - return result; -})(); - -// Returns the path of a project item within the project -function getItemPath(item) { - if (item === app.project.rootFolder) { - return '/'; - } - - var result = item.name; - while (item.parentFolder !== app.project.rootFolder) { - result = item.parentFolder.name + ' / ' + result; - item = item.parentFolder; - } - return '/ ' + result; -} - -// Selects the item within an item control whose text matches the specified text. -// If no such item exists, selects the first item, if present. -function selectByTextOrFirst(itemControl, text) { - var targetItem = toArray(itemControl.items).find(function(item) { - return item.text === text; - }); - if (!targetItem && itemControl.items.length) { - targetItem = itemControl.items[0]; - } - if (targetItem) { - itemControl.selection = targetItem; - } -} - -function getAudioFileProjectItems() { - var result = toArrayBase1(app.project.items).filter(function(item) { - var isAudioFootage = item instanceof FootageItem && item.hasAudio && !item.hasVideo; - return isAudioFootage; - }); - return result; -} +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Script-specific code +//////////////////////////////////////////////////////////////////////////////////////////////////// var mouthShapeNames = 'ABCDEFGHX'.split(''); var basicMouthShapeCount = 6; @@ -281,478 +339,554 @@ var basicMouthShapeNames = mouthShapeNames.slice(0, basicMouthShapeCount); var extendedMouthShapeNames = mouthShapeNames.slice(basicMouthShapeCount); function getMouthCompHelpTip() { - var result = 'A composition containing the mouth shapes, one drawing per frame. They must be ' - + 'arranged as follows:\n'; - mouthShapeNames.forEach(function(mouthShapeName, i) { - var isOptional = i >= basicMouthShapeCount; - result += '\n00:' + pad(i, 2) + '\t' + mouthShapeName + (isOptional ? ' (optional)' : ''); - }); - return result; -} - -function createExtendedShapeCheckboxes() { - var result = {}; - extendedMouthShapeNames.forEach(function(shapeName) { - result[shapeName.toLowerCase()] = controlFunctions.Checkbox({ - text: shapeName, - helpTip: 'Controls whether to use the optional ' + shapeName + ' shape.' - }); - }); - return result; + var table = mouthShapeNames + .map(function (mouthShapeName, i) { + var isOptional = i >= basicMouthShapeCount; + return format( + '{}\t{}', + frameToTimecode(i), + mouthShapeName + (isOptional ? ' (optional)' : '') + ); + }) + .join('\n'); + return ( + 'A composition containing the mouth shapes, one drawing per frame. ' + + 'They must be arranged as follows:\n' + + table + ); } function createDialogWindow() { - var resourceString; - with (controlFunctions) { - resourceString = createResourceString( - Dialog({ - text: appName, - settings: Group({ - orientation: 'column', - alignChildren: ['left', 'top'], - audioFile: Group({ - label: StaticText({ - text: 'Audio file:', - // If I don't explicitly activate a control, After Effects has trouble - // with keyboard focus, so I can't type in the text edit field below. - active: true - }), - value: DropDownList({ - helpTip: 'An audio file containing recorded dialog.\n' - + 'This field shows all audio files that exist in ' - + 'your After Effects project.' - }) - }), - recognizer: Group({ - label: StaticText({ text: 'Recognizer:' }), - value: DropDownList({ - helpTip: 'The dialog recognizer.' - }) - }), - dialogText: Group({ - label: StaticText({ text: 'Dialog text (optional):' }), - value: EditText({ - properties: { multiline: true }, - characters: 60, - minimumSize: [0, 100], - helpTip: 'For better animation results, you can specify the text of ' - + 'the recording here. This field is optional.' - }) - }), - mouthComp: Group({ - label: StaticText({ text: 'Mouth composition:' }), - value: DropDownList({ helpTip: getMouthCompHelpTip() }) - }), - extendedMouthShapes: Group( - Object.assign( - { label: StaticText({ text: 'Extended mouth shapes:' }) }, - createExtendedShapeCheckboxes() - ) - ), - targetFolder: Group({ - label: StaticText({ text: 'Target folder:' }), - value: DropDownList({ - helpTip: 'The project folder in which to create the animation ' - + 'composition. The composition will be named like the audio file.' - }) - }), - frameRate: Group({ - label: StaticText({ text: 'Frame rate:' }), - value: EditText({ - characters: 8, - helpTip: 'The frame rate for the animation.' - }), - auto: Checkbox({ - text: 'From mouth composition', - helpTip: 'If checked, the animation will use the same frame rate as ' - + 'the mouth composition.' - }) - }) - }), - separator: Group({ preferredSize: ['', 3] }), - buttons: Group({ - alignment: 'right', - animate: Button({ - properties: { name: 'ok' }, - text: 'Animate' - }), - cancel: Button({ - properties: { name: 'cancel' }, - text: 'Cancel' - }) - }) - }) - ); - } + var resourceString = createResourceString(function (f) { + return f.dialog({ + text: scriptName, + settings: f.group({ + orientation: 'column', + alignChildren: ['left', 'top'], + audioFile: f.group({ + label: f.staticText({ + text: 'Audio file:', + // If I don't explicitly activate a control, After Effects has trouble + // with keyboard focus, so I can't type in the text edit field below. + active: true + }), + value: f.dropDownList({ + helpTip: + 'An audio file containing recorded dialog.\n' + + 'This field shows all audio files that exist in your After Effects project.' + }) + }), + recognizer: f.group({ + label: f.staticText({ text: 'Recognizer:' }), + value: f.dropDownList({ + helpTip: 'The dialog recognizer.' + }) + }), + dialogText: f.group({ + label: f.staticText({ text: 'Dialog text (optional):' }), + value: f.editText({ + properties: { multiline: true }, + characters: 60, + minimumSize: [0, 100], + helpTip: + 'For better animation results, you can specify the text of the recording here. ' + + 'This field is optional.' + }) + }), + mouthComp: f.group({ + label: f.staticText({ text: 'Mouth composition:' }), + value: f.dropDownList({ helpTip: getMouthCompHelpTip() }) + }), + extendedMouthShapes: f.group( + Object.assign( + { label: f.staticText({ text: 'Extended mouth shapes:' }) }, + Object.fromEntries( + extendedMouthShapeNames.map(function (shapeName) { + return [ + shapeName.toLowerCase(), + f.checkbox({ + text: shapeName, + helpTip: format('Controls whether to use the optional {} shape.', shapeName) + }) + ]; + }) + ) + ) + ), + targetFolder: f.group({ + label: f.staticText({ text: 'Target folder:' }), + value: f.dropDownList({ + helpTip: + 'The project folder in which to create the animation composition. ' + + 'The composition will be named like the audio file.' + }) + }), + frameRate: f.group({ + label: f.staticText({ text: 'Frame rate:' }), + value: f.editText({ + characters: 8, + helpTip: 'The frame rate for the animation.' + }), + auto: f.checkbox({ + text: 'From mouth composition', + helpTip: + 'If checked, the animation will use the same frame rate as the mouth composition.' + }) + }) + }), + separator: f.group({ preferredSize: ['', 3] }), + warningLabel: osIsWindows + ? null + : f.staticText({ + text: + 'Note: Generating the animation may take a while. ' + + 'During this time, After Effects will not be responsive.' + }), + buttons: f.group({ + alignment: 'right', + animate: f.button({ + properties: { name: 'ok' }, + text: 'Animate' + }), + cancel: f.button({ + properties: { name: 'cancel' }, + text: 'Cancel' + }) + }) + }); + }); - // Create window and child controls - var window = new Window(resourceString); - var controls = { - audioFile: window.settings.audioFile.value, - dialogText: window.settings.dialogText.value, - recognizer: window.settings.recognizer.value, - mouthComp: window.settings.mouthComp.value, - targetFolder: window.settings.targetFolder.value, - frameRate: window.settings.frameRate.value, - autoFrameRate: window.settings.frameRate.auto, - animateButton: window.buttons.animate, - cancelButton: window.buttons.cancel - }; - extendedMouthShapeNames.forEach(function(shapeName) { - controls['mouthShape' + shapeName] = - window.settings.extendedMouthShapes[shapeName.toLowerCase()]; - }); + // Create window + var window = new Window(resourceString); - // Add audio file options - getAudioFileProjectItems().forEach(function(projectItem) { - var listItem = controls.audioFile.add('item', getItemPath(projectItem)); - listItem.projectItem = projectItem; - }); + // Get controls + var controls = { + audioFile: window.settings.audioFile.value, + dialogText: window.settings.dialogText.value, + recognizer: window.settings.recognizer.value, + mouthComp: window.settings.mouthComp.value, + targetFolder: window.settings.targetFolder.value, + frameRate: window.settings.frameRate.value, + autoFrameRate: window.settings.frameRate.auto, + animateButton: window.buttons.animate, + cancelButton: window.buttons.cancel + }; + extendedMouthShapeNames.forEach(function (shapeName) { + controls['mouthShape' + shapeName] = + window.settings.extendedMouthShapes[shapeName.toLowerCase()]; + }); - // Add recognizer options - const recognizerOptions = [ - { text: 'PocketSphinx (use for English recordings)', value: 'pocketSphinx' }, - { text: 'Phonetic (use for non-English recordings)', value: 'phonetic' } - ]; - recognizerOptions.forEach(function(option) { - var listItem = controls.recognizer.add('item', option.text); - listItem.value = option.value; - }); + // Add drop down options - // Add mouth composition options - var comps = toArrayBase1(app.project.items).filter(function (item) { - return item instanceof CompItem; - }); - comps.forEach(function(projectItem) { - var listItem = controls.mouthComp.add('item', getItemPath(projectItem)); - listItem.projectItem = projectItem; - }); + // ...audio file + getAudioFileProjectItems().forEach(function (projectItem) { + var listItem = controls.audioFile.add('item', getItemPath(projectItem)); + listItem.projectItem = projectItem; + }); - // Add target folder options - var projectFolders = toArrayBase1(app.project.items).filter(function (item) { - return item instanceof FolderItem; - }); - projectFolders.unshift(app.project.rootFolder); - projectFolders.forEach(function(projectFolder) { - var listItem = controls.targetFolder.add('item', getItemPath(projectFolder)); - listItem.projectItem = projectFolder; - }); + // ...recognizer + var recognizerOptions = [ + { text: 'PocketSphinx (use for English recordings)', value: 'pocketSphinx' }, + { text: 'Phonetic (use for non-English recordings)', value: 'phonetic' } + ]; + recognizerOptions.forEach(function (option) { + var listItem = controls.recognizer.add('item', option.text); + listItem.value = option.value; + }); - // Load persisted settings - var settings = readSettingsFile(); - selectByTextOrFirst(controls.audioFile, settings.audioFile); - controls.dialogText.text = settings.dialogText || ''; - selectByTextOrFirst(controls.recognizer, settings.recognizer); - selectByTextOrFirst(controls.mouthComp, settings.mouthComp); - extendedMouthShapeNames.forEach(function(shapeName) { - controls['mouthShape' + shapeName].value = - (settings.extendedMouthShapes || {})[shapeName.toLowerCase()]; - }); - selectByTextOrFirst(controls.targetFolder, settings.targetFolder); - controls.frameRate.text = settings.frameRate || ''; - controls.autoFrameRate.value = settings.autoFrameRate; + // ...mouth composition + var comps = toArray(app.project.items).filter(function (item) { + return item instanceof CompItem; + }); + comps.forEach(function (comp) { + var listItem = controls.mouthComp.add('item', getItemPath(comp)); + listItem.projectItem = comp; + }); - // Align controls - window.onShow = function() { - // Give uniform width to all labels - var groups = toArray(window.settings.children); - var labelWidths = groups.map(function(group) { return group.children[0].size.width; }); - var maxLabelWidth = Math.max.apply(Math, labelWidths); - groups.forEach(function (group) { - group.children[0].size.width = maxLabelWidth; - }); + // ...target folder + var projectFolders = toArray(app.project.items).filter(function (item) { + return item instanceof FolderItem; + }); + projectFolders.unshift(app.project.rootFolder); + projectFolders.forEach(function (projectFolder) { + var listItem = controls.targetFolder.add('item', getItemPath(projectFolder)); + listItem.projectItem = projectFolder; + }); - // Give uniform width to inputs - var valueWidths = groups.map(function(group) { - return last(group.children).bounds.right - group.children[1].bounds.left; - }); - var maxValueWidth = Math.max.apply(Math, valueWidths); - groups.forEach(function (group) { - var multipleControls = group.children.length > 2; - if (!multipleControls) { - group.children[1].size.width = maxValueWidth; - } - }); + // Load persisted settings + var settings = readSettingsFile(); + selectByTextOrFirst(controls.audioFile, settings.audioFile); + controls.dialogText.text = settings.dialogText || ''; + selectByTextOrFirst(controls.recognizer, settings.recognizer); + selectByTextOrFirst(controls.mouthComp, settings.mouthComp); + extendedMouthShapeNames.forEach(function (shapeName) { + controls['mouthShape' + shapeName].value = (settings.extendedMouthShapes || {})[ + shapeName.toLowerCase() + ]; + }); + selectByTextOrFirst(controls.targetFolder, settings.targetFolder); + controls.frameRate.text = settings.frameRate || ''; + controls.autoFrameRate.value = settings.autoFrameRate; - window.layout.layout(true); - }; + // Align controls + window.onShow = function () { + // Give uniform width to all labels + var groups = toArray(window.settings.children).filter(function (control) { + return control instanceof Group; + }); + var labelWidths = groups.map(function (group) { + return group.children[0].size.width; + }); + var maxLabelWidth = Math.max.apply(Math, labelWidths); + groups.forEach(function (group) { + group.children[0].size.width = maxLabelWidth; + }); - var updating = false; + // Give uniform width to inputs + var valueWidths = groups.map(function (group) { + return last(group.children).bounds.right - group.children[1].bounds.left; + }); + var maxValueWidth = Math.max.apply(Math, valueWidths); + groups.forEach(function (group) { + var multipleControls = group.children.length > 2; + if (!multipleControls) { + group.children[1].size.width = maxValueWidth; + } + }); - function update() { - if (updating) return; + window.layout.layout(true); + }; - updating = true; - try { - // Handle auto frame rate - var autoFrameRate = controls.autoFrameRate.value; - controls.frameRate.enabled = !autoFrameRate; - if (autoFrameRate) { - // Take frame rate from mouth comp - var mouthComp = (controls.mouthComp.selection || {}).projectItem; - controls.frameRate.text = mouthComp ? mouthComp.frameRate : ''; - } else { - // Sanitize frame rate - var sanitizedFrameRate = controls.frameRate.text.match(/\d*\.?\d*/)[0]; - if (sanitizedFrameRate !== controls.frameRate.text) { - controls.frameRate.text = sanitizedFrameRate; - } - } + var updating = false; - // Store settings - var settings = { - audioFile: (controls.audioFile.selection || {}).text, - recognizer: (controls.recognizer.selection || {}).text, - dialogText: controls.dialogText.text, - mouthComp: (controls.mouthComp.selection || {}).text, - extendedMouthShapes: {}, - targetFolder: (controls.targetFolder.selection || {}).text, - frameRate: Number(controls.frameRate.text), - autoFrameRate: controls.autoFrameRate.value - }; - extendedMouthShapeNames.forEach(function(shapeName) { - settings.extendedMouthShapes[shapeName.toLowerCase()] = - controls['mouthShape' + shapeName].value; - }); - writeSettingsFile(settings); - } finally { - updating = false; - } - } + function update() { + if (updating) return; - // Validate user input. Possible return values: - // * Non-empty string: Validation failed. Show error message. - // * Empty string: Validation failed. Don't show error message. - // * Undefined: Validation succeeded. - function validate() { - // Check input values - if (!controls.audioFile.selection) return 'Please select an audio file.'; - if (!controls.mouthComp.selection) return 'Please select a mouth composition.'; - if (!controls.targetFolder.selection) return 'Please select a target folder.'; - if (Number(controls.frameRate.text) < 12) { - return 'Please enter a frame rate of at least 12 fps.'; - } + updating = true; + try { + // Handle auto frame rate + var autoFrameRate = controls.autoFrameRate.value; + controls.frameRate.enabled = !autoFrameRate; + if (autoFrameRate) { + // Take frame rate from mouth comp + var mouthComp = (controls.mouthComp.selection || {}).projectItem; + controls.frameRate.text = mouthComp ? mouthComp.frameRate : ''; + } else { + // Sanitize frame rate + var sanitizedFrameRate = controls.frameRate.text.match(/\d*\.?\d*/)[0]; + if (sanitizedFrameRate !== controls.frameRate.text) { + controls.frameRate.text = sanitizedFrameRate; + } + } - // Check mouth shape visibility - var comp = controls.mouthComp.selection.projectItem; - for (var i = 0; i < mouthShapeCount; i++) { - var shapeName = mouthShapeNames[i]; - var required = i < basicMouthShapeCount || controls['mouthShape' + shapeName].value; - if (required && !isFrameVisible(comp, i)) { - return 'The mouth comp does not seem to contain an image for shape ' - + shapeName + ' at frame ' + i + '.'; - } - } + // Store settings + var settings = { + audioFile: (controls.audioFile.selection || {}).text, + recognizer: (controls.recognizer.selection || {}).text, + dialogText: controls.dialogText.text, + mouthComp: (controls.mouthComp.selection || {}).text, + extendedMouthShapes: {}, + targetFolder: (controls.targetFolder.selection || {}).text, + frameRate: Number(controls.frameRate.text), + autoFrameRate: controls.autoFrameRate.value + }; + extendedMouthShapeNames.forEach(function (shapeName) { + settings.extendedMouthShapes[shapeName.toLowerCase()] = + controls['mouthShape' + shapeName].value; + }); + writeSettingsFile(settings); + } finally { + updating = false; + } + } - if (!comp.preserveNestedFrameRate) { - var fix = Window.confirm( - 'The setting "Preserve frame rate when nested or in render queue" is not active ' - + 'for the mouth composition. This can result in incorrect animation.\n\n' - + 'Activate this setting now?', - false, - 'Fix composition setting?'); - if (fix) { - app.beginUndoGroup(appName + ': Mouth composition setting'); - comp.preserveNestedFrameRate = true; - app.endUndoGroup(); - } else { - return ''; - } - } + // Validate user input. Possible return values: + // * Non-empty string: Validation failed. Show error message. + // * Empty string: Validation failed. Don't show error message. + // * Undefined: Validation succeeded. + function validate() { + // Check input values + if (!controls.audioFile.selection) return 'Please select an audio file.'; + if (!controls.mouthComp.selection) return 'Please select a mouth composition.'; + if (!controls.targetFolder.selection) return 'Please select a target folder.'; + if (Number(controls.frameRate.text) < 12) { + return 'Please enter a frame rate of at least 12 fps.'; + } - // Check for correct Rhubarb version - var version = exec(rhubarbPath + ' --version') || ''; - var match = version.match(/Rhubarb Lip Sync version ((\d+)\.(\d+).(\d+)(-[0-9A-Za-z-.]+)?)/); - if (!match) { - var instructions = osIsWindows - ? 'Make sure your PATH environment variable contains the ' + appName + ' ' - + 'application directory.' - : 'Make sure you have created this file as a symbolic link to the ' + appName + ' ' - + 'executable (rhubarb).'; - return 'Cannot find executable file "' + rhubarbPath + '". \n' + instructions; - } - var versionString = match[1]; - var major = Number(match[2]); - var minor = Number(match[3]); - var requiredMajor = 1; - var minRequiredMinor = 9; - if (major != requiredMajor || minor < minRequiredMinor) { - return 'This script requires ' + appName + ' ' + requiredMajor + '.' + minRequiredMinor - + '.0 or a later ' + requiredMajor + '.x version. ' - + 'Your installed version is ' + versionString + ', which is not compatible.'; - } - } + // Check mouth shape visibility + var comp = controls.mouthComp.selection.projectItem; + for (var i = 0; i < mouthShapeCount; i++) { + var shapeName = mouthShapeNames[i]; + var required = i < basicMouthShapeCount || controls['mouthShape' + shapeName].value; + if (required && !isFrameVisible(comp, i)) { + return format( + 'The mouth comp does not seem to contain an image for shape {} at frame {}.', + shapeName, + frameToTimecode(i) + ); + } + } - function generateMouthCues(audioFileFootage, recognizer, dialogText, mouthComp, extendedMouthShapeNames, - targetProjectFolder, frameRate) - { - var basePath = Folder.temp.fsName + '/' + createGuid(); - var dialogFile = new File(basePath + '.txt'); - var logFile = new File(basePath + '.log'); - var jsonFile = new File(basePath + '.json'); - try { - // Create text file containing dialog - writeTextFile(dialogFile, dialogText); + if (!comp.preserveNestedFrameRate) { + var fix = Window.confirm( + 'The setting "Preserve frame rate when nested or in render queue" is not active for the ' + + 'mouth composition. This can result in incorrect animation.\n\n' + + 'Activate this setting now?', + false, + 'Fix composition setting?' + ); + if (fix) { + app.beginUndoGroup(format('{}: Mouth composition setting', scriptName)); + comp.preserveNestedFrameRate = true; + app.endUndoGroup(); + } else { + return ''; + } + } + } - // Create command line - var commandLine = rhubarbPath - + ' --dialogFile ' + cliEscape(dialogFile.fsName) - + ' --recognizer ' + recognizer - + ' --exportFormat json' - + ' --extendedShapes ' + cliEscape(extendedMouthShapeNames.join('')) - + ' --logFile ' + cliEscape(logFile.fsName) - + ' --logLevel fatal' - + ' --output ' + cliEscape(jsonFile.fsName) - + ' ' + cliEscape(audioFileFootage.file.fsName); + function generateMouthCues(audioFileFootage, recognizer, dialogText, extendedMouthShapeNames) { + var dialogFile = getTempFile('dialog.txt'); + var logFile = getTempFile('log.txt'); + var jsonFile = getTempFile('output.json'); + try { + // Create text file containing dialog + writeTextFile(dialogFile, dialogText); - // Run Rhubarb - execInWindow(commandLine); + // Run Rhubarb + // prettier-ignore + var commandParts = [ + 'rhubarb', + '--dialogFile', dialogFile.fsName, + '--recognizer', recognizer, + '--extendedShapes', extendedMouthShapeNames.join(''), + // TODO: Pass the frame rate once Rhubarb does something sensible with it + '--exportFormat', 'json', + '--logFile', logFile.fsName, + '--logLevel', 'fatal', + '--output', jsonFile.fsName, + audioFileFootage.file.fsName + ]; - // Check log for fatal errors - if (logFile.exists) { - var fatalLog = readTextFile(logFile).trim(); - if (fatalLog) { - // Try to extract only the actual error message - var match = fatalLog.match(/\[Fatal\] ([\s\S]*)/); - var message = match ? match[1] : fatalLog; - throw new Error('Error running ' + appName + '.\n' + message); - } - } + if (osIsWindows) { + // Run the command via cmd. This opens a new window, letting the user see the progress and + // abort if desired. + // cmd treats quotes weirdly; see https://stackoverflow.com/a/62198274 + // Also, cmd treats carets specially, so escape them. + var commandLine = commandParts.map(cliEscape).join(' '); + system.callSystem(format('cmd /S /C "{}"', commandLine.replace(/\^/g, '^^'))); + } else { + // There is no simple way to run a command in a visible window on macOS. + // The user will have to wait for the command to finish. + exec.apply(undefined, commandParts); + } - var result; - try { - result = JSON.parse(readTextFile(jsonFile)); - } catch (e) { - throw new Error('No animation result. Animation was probably canceled.'); - } - return result; - } finally { - dialogFile.remove(); - logFile.remove(); - jsonFile.remove(); - } - } + // Check log for fatal errors + if (logFile.exists) { + var fatalLog = readTextFile(logFile).trim(); + if (fatalLog) { + // Try to extract only the actual error message + var match = fatalLog.match(/\[Fatal\] ([\s\S]*)/); + var message = match ? match[1] : fatalLog; + throw new Error(format('Error running Rhubarb Lip Sync.\n{}', message)); + } + } - function animateMouthCues(mouthCues, audioFileFootage, mouthComp, targetProjectFolder, - frameRate) - { - // Find an unconflicting comp name - // ... strip extension, if present - var baseName = audioFileFootage.name.match(/^(.*?)(\..*)?$/i)[1]; - var compName = baseName; - // ... add numeric suffix, if needed - var existingItems = toArrayBase1(targetProjectFolder.items); - var counter = 1; - while (existingItems.some(function(item) { return item.name === compName; })) { - counter++; - compName = baseName + ' ' + counter; - } + try { + return JSON.parse(readTextFile(jsonFile)).mouthCues; + } catch (e) { + throw new Error('No animation result. Animation was probably canceled.'); + } + } finally { + dialogFile.remove(); + logFile.remove(); + jsonFile.remove(); + } + } - // Create new comp - var comp = targetProjectFolder.items.addComp(compName, mouthComp.width, mouthComp.height, - mouthComp.pixelAspect, audioFileFootage.duration, frameRate); + function animateMouthCues( + mouthCues, + audioFileFootage, + mouthComp, + targetProjectFolder, + frameRate + ) { + // Find a non-conflicting comp name + // ... strip extension, if present + var baseName = audioFileFootage.name.match(/^(.*?)(\..*)?$/i)[1]; + var compName = baseName; + // ... add numeric suffix, if needed + var existingItems = toArray(targetProjectFolder.items); + var counter = 1; + while ( + existingItems.some(function (item) { + return item.name === compName; + }) + ) { + counter++; + compName = format('{} {}', baseName, counter); + } - // Show new comp - comp.openInViewer(); + // Create new comp + var comp = targetProjectFolder.items.addComp( + compName, + mouthComp.width, + mouthComp.height, + mouthComp.pixelAspect, + audioFileFootage.duration, + frameRate + ); - // Add audio layer - comp.layers.add(audioFileFootage); + // Show new comp + comp.openInViewer(); - // Add mouth layer - var mouthLayer = comp.layers.add(mouthComp); - mouthLayer.timeRemapEnabled = true; - mouthLayer.outPoint = comp.duration; + // Add audio layer + comp.layers.add(audioFileFootage); - // Animate mouth layer - var timeRemap = mouthLayer['Time Remap']; - // Enabling time remapping automatically adds two keys. Remove the second. - timeRemap.removeKey(2); - mouthCues.mouthCues.forEach(function(mouthCue) { - // Round down keyframe time. In animation, earlier is better than later. - // Set keyframe time to *just before* the exact frame to prevent rounding errors - var frame = Math.floor(timeToFrame(mouthCue.start, comp)); - var time = frame !== 0 ? frameToTime(frame - epsilon, comp) : 0; - // Set remapped time to *just after* the exact frame to prevent rounding errors - var mouthCompFrame = mouthShapeNames.indexOf(mouthCue.value); - var remappedTime = frameToTime(mouthCompFrame + epsilon, mouthComp); - timeRemap.setValueAtTime(time, remappedTime); - }); - for (var i = 1; i <= timeRemap.numKeys; i++) { - timeRemap.setInterpolationTypeAtKey(i, KeyframeInterpolationType.HOLD); - } - } + // Add mouth layer + var mouthLayer = comp.layers.add(mouthComp); + mouthLayer.timeRemapEnabled = true; + mouthLayer.outPoint = comp.duration; - function animate(audioFileFootage, recognizer, dialogText, mouthComp, extendedMouthShapeNames, - targetProjectFolder, frameRate) - { - try { - var mouthCues = generateMouthCues(audioFileFootage, recognizer, dialogText, mouthComp, - extendedMouthShapeNames, targetProjectFolder, frameRate); + // Animate mouth layer + var timeRemap = mouthLayer['Time Remap']; + // Enabling time remapping automatically adds two keys. Remove the second. + timeRemap.removeKey(2); + mouthCues.forEach(function (mouthCue) { + // Round down keyframe time. In animation, earlier is better than later. + // Set keyframe time to *just before* the exact frame to prevent rounding errors + var frame = Math.floor(timeToFrame(mouthCue.start, comp)); + var time = frame !== 0 ? frameToTime(frame - epsilon, comp) : 0; + // Set remapped time to *just after* the exact frame to prevent rounding errors + var mouthCompFrame = mouthShapeNames.indexOf(mouthCue.value); + var remappedTime = frameToTime(mouthCompFrame + epsilon, mouthComp); + timeRemap.setValueAtTime(time, remappedTime); + }); + for (var i = 1; i <= timeRemap.numKeys; i++) { + timeRemap.setInterpolationTypeAtKey(i, KeyframeInterpolationType.HOLD); + } + } - app.beginUndoGroup(appName + ': Animation'); - animateMouthCues(mouthCues, audioFileFootage, mouthComp, targetProjectFolder, - frameRate); - app.endUndoGroup(); - } catch (e) { - Window.alert(e.message, appName, true); - return; - } - } + function animate( + audioFileFootage, + recognizer, + dialogText, + mouthComp, + extendedMouthShapeNames, + targetProjectFolder, + frameRate + ) { + try { + var mouthCues = generateMouthCues( + audioFileFootage, + recognizer, + dialogText, + extendedMouthShapeNames + ); - // Handle changes - update(); - controls.audioFile.onChange = update; - controls.recognizer.onChange = update; - controls.dialogText.onChanging = update; - controls.mouthComp.onChange = update; - extendedMouthShapeNames.forEach(function(shapeName) { - controls['mouthShape' + shapeName].onClick = update; - }); - controls.targetFolder.onChange = update; - controls.frameRate.onChanging = update; - controls.autoFrameRate.onClick = update; + app.beginUndoGroup(format('{}: Animation', scriptName)); + animateMouthCues(mouthCues, audioFileFootage, mouthComp, targetProjectFolder, frameRate); + app.endUndoGroup(); + } catch (e) { + showErrorDialog('Error creating animation.', e); + return; + } + } - // Handle animation - controls.animateButton.onClick = function() { - var validationError = validate(); - if (typeof validationError === 'string') { - if (validationError) { - Window.alert(validationError, appName, true); - } - } else { - window.close(); - animate( - controls.audioFile.selection.projectItem, - controls.recognizer.selection.value, - controls.dialogText.text || '', - controls.mouthComp.selection.projectItem, - extendedMouthShapeNames.filter(function(shapeName) { - return controls['mouthShape' + shapeName].value; - }), - controls.targetFolder.selection.projectItem, - Number(controls.frameRate.text) - ); - } - }; + // Handle changes + update(); + controls.audioFile.onChange = update; + controls.recognizer.onChange = update; + controls.dialogText.onChanging = update; + controls.mouthComp.onChange = update; + extendedMouthShapeNames.forEach(function (shapeName) { + controls['mouthShape' + shapeName].onClick = update; + }); + controls.targetFolder.onChange = update; + controls.frameRate.onChanging = update; + controls.autoFrameRate.onClick = update; - // Handle cancelation - controls.cancelButton.onClick = function() { - window.close(); - }; + // Handle animation + controls.animateButton.onClick = function () { + var validationError = validate(); + if (typeof validationError === 'string') { + if (validationError !== '') { + showErrorDialog(validationError); + } + } else { + window.close(); + animate( + controls.audioFile.selection.projectItem, + controls.recognizer.selection.value, + controls.dialogText.text || '', + controls.mouthComp.selection.projectItem, + extendedMouthShapeNames.filter(function (shapeName) { + return controls['mouthShape' + shapeName].value; + }), + controls.targetFolder.selection.projectItem, + Number(controls.frameRate.text) + ); + } + }; - return window; + // Handle cancellation + controls.cancelButton.onClick = function () { + window.close(); + }; + + return window; } function checkPreconditions() { - if (!canWriteFiles()) { - Window.alert('This script requires file system access.\n\n' - + 'Please enable Preferences > General > Allow Scripts to Write Files and Access Network.', - appName, true); - return false; - } - return true; + // Check for file system access + if (!canWriteFiles()) { + var section = app.version >= '22' ? 'Scripting & Expressions' : 'General'; + throw new Error( + format( + 'This script requires file system access.\n\n' + + 'Please enable Preferences > {} > Allow Scripts to Write Files and Access Network.', + section + ) + ); + } + + // Check for correct Rhubarb version + var versionString = exec('rhubarb', '--version') || ''; + var match = versionString.match( + /Rhubarb Lip Sync version ((\d+)\.(\d+).(\d+)(-[0-9A-Za-z-.]+)?)/ + ); + if (!match) { + throw new Error( + 'Cannot find Rhubarb Lip Sync.\n' + + 'Make sure your PATH environment variable contains the Rhubarb application directory.' + ); + } + var versionString = match[1]; + var major = Number(match[2]); + var minor = Number(match[3]); + var requiredMajor = 1; + var minRequiredMinor = 9; + if (major !== requiredMajor || minor < minRequiredMinor) { + throw new Error( + format( + 'This script requires Rhubarb Lip Sync {}.{}.0 or a later {0}.x version. ' + + 'Your installed version is {}, which is not compatible.', + requiredMajor, + minRequiredMinor, + versionString + ) + ); + } } -if (checkPreconditions()) { - createDialogWindow().show(); +function main() { + try { + loadPolyfills(); + checkPreconditions(); + createDialogWindow().show(); + } catch (error) { + showErrorDialog(error); + } } + +main(); diff --git a/img/after-effects-setup.png b/img/after-effects-setup.png new file mode 100644 index 0000000..8056f44 Binary files /dev/null and b/img/after-effects-setup.png differ