diff --git a/README.md b/README.md index 2680156..e0a2a48 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ Clone this repository, or open the directory of the example you want. Each examp - [agency-client-social-videos](examples/agency-client-social-videos) renders one short vertical video per agency client from that client's own photos and video clips, ending on a card in the client's brand color. The Edit JSON is built in code, one clip per media item. - [ai-content-pipeline](examples/ai-content-pipeline) makes an on-brand 9:16 video for each product in a CSV, from a brand guide in JSON. Claude writes each script, AI models generate the still and the clip, and checks on the words and the pictures hold anything off-brand for review. Companion code for [AI content pipeline automation with video creation for brands](https://shotstack.io/learn/ai-content-pipeline-automation-brands/). +- [automate-after-effects-templates](examples/automate-after-effects-templates) turns a Bodymovin (Lottie) export of an After Effects design into a template with merge fields, then renders one video per row of a CSV. A designer can update the design later without changes to the data or the render script. Companion code for [Automate After Effects templates with Lottie and the Shotstack API](https://shotstack.io/learn/automate-after-effects-templates/). - [automotive-inventory-videos](examples/automotive-inventory-videos) renders one vertical video per vehicle in a dealer inventory from a JSON feed: the photos in sequence with a pan or zoom on each, and an animated specification card. The Edit JSON is built in code, one clip per photo. - [bulk-csv-videos](examples/bulk-csv-videos) renders one video per row of a CSV from a single template with merge fields, tracked in a resumable manifest, with an optional AI step where Claude writes each row's headline and image prompt. Companion code for [Generate videos in bulk with an API and an AI agent](https://shotstack.io/learn/bulk-create-videos-from-csv-and-ai/). - [elevenlabs-voiceover-video](examples/elevenlabs-voiceover-video) narrates a video in an ElevenLabs voice, cloned from your own sample if you want, uploads the audio through the Ingest API and renders a captioned video. diff --git a/examples/automate-after-effects-templates/.env.example b/examples/automate-after-effects-templates/.env.example new file mode 100644 index 0000000..f417842 --- /dev/null +++ b/examples/automate-after-effects-templates/.env.example @@ -0,0 +1,6 @@ +# https://dashboard.shotstack.io/register +SHOTSTACK_API_KEY= + +# Optional. v1 (production, the default) or stage (sandbox). Use the key from the same environment. +# Both keys are in the dashboard under API Keys: https://dashboard.shotstack.io/ +SHOTSTACK_ENV= diff --git a/examples/automate-after-effects-templates/.gitignore b/examples/automate-after-effects-templates/.gitignore new file mode 100644 index 0000000..c5a001f --- /dev/null +++ b/examples/automate-after-effects-templates/.gitignore @@ -0,0 +1,13 @@ +node_modules/ +.env + +# Downloaded media. The Mixkit license does not allow sharing these files. +footage.mp4 +music.mp3 + +# Files that the scripts write +assets.json +template.json +template-id.txt +render-results.json +videos/ diff --git a/examples/automate-after-effects-templates/Montserrat-OFL.txt b/examples/automate-after-effects-templates/Montserrat-OFL.txt new file mode 100644 index 0000000..fe576a2 --- /dev/null +++ b/examples/automate-after-effects-templates/Montserrat-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2024 The Montserrat.Git Project Authors (https://github.com/JulietaUla/Montserrat.git) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/examples/automate-after-effects-templates/README.md b/examples/automate-after-effects-templates/README.md new file mode 100644 index 0000000..5dc1ff9 --- /dev/null +++ b/examples/automate-after-effects-templates/README.md @@ -0,0 +1,62 @@ +# Automate After Effects templates + +Turn a Bodymovin (Lottie) export of an After Effects design into a Shotstack template. Then render one video for each row of a CSV file. You get one MP4 file for each row in the `videos` directory. + +Related guide: [Automate After Effects templates with Lottie and the Shotstack API](https://shotstack.io/learn/automate-after-effects-templates/). + +## Requirements + +- A [Shotstack account](https://dashboard.shotstack.io/register) and its production API key. Production renders use credits. The rates are on the [pricing page](https://shotstack.io/pricing/). +- Node.js 22 or later. The code uses only built-in modules. There are no packages to install. +- After Effects and the Bodymovin extension, only to change the design. The rendering does not use After Effects. + +## Setup + +```bash +git clone https://github.com/shotstack/shotstack-cookbook.git +cd shotstack-cookbook/examples/automate-after-effects-templates +``` + +Download the footage and the music. The Mixkit license does not let us include these files: + +- Footage: [A barista preparing coffee with milk and ice](https://mixkit.co/free-stock-video/a-barista-preparing-coffee-with-milk-and-ice-796/). Download the Full HD version. Save it as `footage.mp4`. +- Music: an MP3 file from [Mixkit's happy music](https://mixkit.co/free-stock-music/happy/). Save it as `music.mp3`. + +You can use your own footage and music instead. Keep the same file names. + +Set your API key. The `.env.example` file lists the variables that the scripts read. + +```bash +export SHOTSTACK_API_KEY="your_api_key" +``` + +## Run + +Upload the footage, the music and the logo. Then save the template and render one video for each row of `data.csv`: + +```bash +node setup-assets.js +node create-template.js +node render-videos.js +``` + +To try a design change, update the template from the navy version of the card. Then render one row: + +```bash +node update-template.js product-card-v2.json +node render-videos.js one-row.csv +``` + +## What happens + +`setup-assets.js` uploads the three files to the Ingest API and writes their URLs to `assets.json`. The uploads take about one minute. + +`create-template.js` builds the template from `product-card.json` and saves it to your account. It writes the template ID to `template-id.txt`. + +`render-videos.js` sends one render request for each row, one request each second. Each video is 6 seconds long at 1920 x 1080. The renders take about one minute. The script downloads each video to `videos/` and writes the status of each row to `render-results.json`. + +The script skips a row if a value is longer than the limit in `MAX_LENGTH`. If you run the script again, it does not render the rows that it downloaded before. It also gets the renders that it sent but did not download. + +The `after-effects` directory has the After Effects projects for both versions of the card. To change the design, export it again with Bodymovin. Turn off the Glyphs setting. Keep the names of the text layers `PRODUCT` and `PRICE`. + +To add a field, name a new text layer in capitals. Then add a column with the same name to the CSV file. Each font in the export needs a `.woff2` file next to the scripts, named after the font in lower case, for example `montserrat-bold.woff2`. diff --git a/examples/automate-after-effects-templates/after-effects/product-card-v2.aep b/examples/automate-after-effects-templates/after-effects/product-card-v2.aep new file mode 100644 index 0000000..ed39a23 Binary files /dev/null and b/examples/automate-after-effects-templates/after-effects/product-card-v2.aep differ diff --git a/examples/automate-after-effects-templates/after-effects/product-card.aep b/examples/automate-after-effects-templates/after-effects/product-card.aep new file mode 100644 index 0000000..6d948f8 Binary files /dev/null and b/examples/automate-after-effects-templates/after-effects/product-card.aep differ diff --git a/examples/automate-after-effects-templates/build-template.js b/examples/automate-after-effects-templates/build-template.js new file mode 100644 index 0000000..9e39fde --- /dev/null +++ b/examples/automate-after-effects-templates/build-template.js @@ -0,0 +1,211 @@ +// Builds the Shotstack template: the After Effects card (a Bodymovin export) in an html5 clip, +// over a footage clip, with a logo and music. +const fs = require('fs'); +const path = require('path'); + +const MIN_FONT_SIZE = 24; // auto-shrink never goes below this size (px) + +// Every text layer in the export, including the ones inside precompositions. +const textLayers = lottie => + [lottie.layers, ...(lottie.assets || []).map(asset => asset.layers)] + .flat() + .filter(layer => layer?.ty === 5); + +// Text layers named in capitals (PRODUCT, PRICE) are the fields that change in each video. +function fieldNames(lottie) { + const names = textLayers(lottie) + .map(layer => layer.nm) + .filter(name => /^[A-Z][A-Z0-9_]*$/.test(name)); + return [...new Set(names)]; +} + +// The sample text the designer typed in each field, used as the template's default merge values. +function sampleText(lottie) { + const text = {}; + for (const layer of textLayers(lottie)) text[layer.nm] ??= layer.t.d.k[0].s.t; + return text; +} + +// The html5 clip that plays the card. Merge placeholders sit in hidden divs in the html; +// the script copies their text into the matching text layers before the animation starts. +function cardClip(lottie, fontDir) { + const fields = fieldNames(lottie); + const fonts = lottie.fonts?.list || []; + if (!fonts.length) { + throw new Error( + 'The export lists no font. Export it again from Bodymovin with Glyphs off.' + ); + } + // Each font comes from a file named after it in the export: Montserrat-Bold -> montserrat-bold.woff2. + const faces = fonts.map(font => { + const file = path.join(fontDir, `${font.fName.toLowerCase()}.woff2`); + if (!fs.existsSync(file)) { + throw new Error( + `Can't find ${path.basename(file)}, the font file for ${font.fName}, next to the scripts.` + ); + } + return { + family: font.fFamily, + weight: /bold/i.test(font.fStyle) ? 700 : 400, + data: fs.readFileSync(file).toString('base64') + }; + }); + + const html = ['
'] + .concat( + fields.map(name => ``) + ) + .join('\n'); + + const css = [ + ...faces.map( + face => + `@font-face { font-family: '${face.family}'; font-weight: ${face.weight}; src: url(data:font/woff2;base64,${face.data}) format('woff2'); }` + ), + `html, body { margin: 0; width: ${lottie.w}px; height: ${lottie.h}px; overflow: hidden; background: transparent; }`, + `#card { width: ${lottie.w}px; height: ${lottie.h}px; }` + ].join('\n'); + + const js = ` +const animationData = ${JSON.stringify(lottie)}; + +// Put each field's value into the text layer with the same name. +const values = {}; +document.querySelectorAll('[data-field]').forEach((el) => { + values[el.dataset.field] = el.textContent.replace(/\\r?\\n/g, '\\r'); +}); +const layerLists = [animationData.layers].concat((animationData.assets || []).filter((a) => a.layers).map((a) => a.layers)); +layerLists.forEach((layers) => layers.forEach((layer) => { + if (layer.ty === 5 && values[layer.nm] !== undefined) { + layer.t.d.k.forEach((keyframe) => { keyframe.s.t = values[layer.nm]; }); + } +})); + +// Shrink text that doesn't fit its text box, down to ${MIN_FONT_SIZE}px. +function shrinkToFit(elements) { + (elements || []).forEach((el) => { + if (!el) return; + if (el.data && el.data.ty === 5 && el.canResizeFont) { + el.canResizeFont(true); + el.setMinimumFontSize(${MIN_FONT_SIZE}); + } + if (el.elements) shrinkToFit(el.elements); + }); +} + +function start() { + const anim = lottie.loadAnimation({ + container: document.getElementById('card'), + renderer: 'svg', + loop: false, + autoplay: false, + animationData: animationData, + }); + if (anim.isLoaded) shrinkToFit(anim.renderer.elements); + else anim.addEventListener('DOMLoaded', () => shrinkToFit(anim.renderer.elements)); +} + +// lottie-web lays text out from the font's measurements, so start once the fonts have loaded. +const fonts = ${JSON.stringify(faces.map(face => `${face.weight} 40px "${face.family}"`))}; +Promise.all(fonts.map((font) => document.fonts.load(font))).then(start, start);`; + + for (const [field, value] of Object.entries({ css, js })) { + if (value.length > 500000) { + throw new Error( + `The html5 ${field} is ${value.length} characters, over the limit of 500,000. Use a smaller font file or a simpler animation.` + ); + } + } + + return { + asset: { type: 'html5', html, css, js }, + length: Math.round(((lottie.op - lottie.ip) / lottie.fr) * 1000) / 1000, + width: lottie.w, + height: lottie.h, + position: 'bottomLeft', + offset: { x: 0.04, y: 0.08 } + }; +} + +// The full template: card on top, logo in the top-right corner, footage underneath, music on its own track. +function buildTemplate({ lottie, assets, fontDir = __dirname }) { + const card = cardClip(lottie, fontDir); + const cardStart = 0.5; + const total = cardStart + card.length + 0.5; + const defaults = sampleText(lottie); + + return { + timeline: { + tracks: [ + { clips: [{ ...card, start: cardStart }] }, + { + clips: [ + { + asset: { type: 'image', src: assets.logo }, + start: 0, + length: total, + fit: 'none', + position: 'topRight', + offset: { x: -0.03, y: -0.04 } + } + ] + }, + { + clips: [ + { + asset: { type: 'video', src: assets.footage, volume: 0 }, + start: 0, + length: total + } + ] + }, + { + clips: [ + { + asset: { + type: 'audio', + src: assets.music, + effect: 'fadeInFadeOut', + volume: 0.6 + }, + start: 0, + length: total + } + ] + } + ] + }, + output: { format: 'mp4', size: { width: 1920, height: 1080 }, fps: 25 }, + merge: fieldNames(lottie).map(name => ({ + find: name, + replace: defaults[name] || '' + })) + }; +} + +// Reads a Bodymovin export and checks it can become a template. +function readExport(file) { + if (!fs.existsSync(file)) + throw new Error(`Can't find ${path.basename(file)}.`); + let lottie; + try { + lottie = JSON.parse(fs.readFileSync(file, 'utf8')); + } catch { + throw new Error( + `${path.basename(file)} isn't valid JSON. Export it again from Bodymovin.` + ); + } + if (lottie.chars) { + throw new Error( + 'This export has Glyphs on. Turn Glyphs off in Bodymovin and export again.' + ); + } + if (!fieldNames(lottie).length) { + throw new Error( + 'No text layer is named in capitals (like PRODUCT), so nothing could change between videos. Rename the layers in After Effects and export again.' + ); + } + return lottie; +} + +module.exports = { buildTemplate, fieldNames, readExport }; diff --git a/examples/automate-after-effects-templates/create-template.js b/examples/automate-after-effects-templates/create-template.js new file mode 100644 index 0000000..c35884d --- /dev/null +++ b/examples/automate-after-effects-templates/create-template.js @@ -0,0 +1,36 @@ +// Saves the card, footage, logo and music as a Shotstack template. +// Usage: node create-template.js [export.json] (defaults to product-card.json) +const fs = require('fs'); +const path = require('path'); +const { EDIT_API, api, readStep } = require('./shotstack'); +const { buildTemplate, fieldNames, readExport } = require('./build-template'); + +async function main() { + const lottie = readExport( + path.join(__dirname, process.argv[2] || 'product-card.json') + ); + const assets = JSON.parse(readStep('assets.json', 'setup-assets.js')); + + const template = buildTemplate({ lottie, assets }); + const { response } = await api('POST', `${EDIT_API}/templates`, { + name: 'Product card', + template + }); + if (!response?.id) + throw new Error('The API saved the template but returned no id.'); + // Written only after the API has the template, because render-videos.js resumes from it. + fs.writeFileSync( + path.join(__dirname, 'template.json'), + JSON.stringify(template, null, 2) + ); + fs.writeFileSync(path.join(__dirname, 'template-id.txt'), response.id); + console.log(`Fields: ${fieldNames(lottie).join(', ')}`); + console.log( + `Template saved: ${response.id} (also in template-id.txt and template.json)` + ); +} + +main().catch(err => { + console.error(err.message); + process.exit(1); +}); diff --git a/examples/automate-after-effects-templates/data.csv b/examples/automate-after-effects-templates/data.csv new file mode 100644 index 0000000..3f7008d --- /dev/null +++ b/examples/automate-after-effects-templates/data.csv @@ -0,0 +1,5 @@ +PRODUCT,PRICE +Iced vanilla latte,$5.49 +Pumpkin spice cold brew with oat milk and cinnamon,$6.25 +"Joe's ""Famous"" mocha",$4.75 +Agua fresca de sandía,$4.25 diff --git a/examples/automate-after-effects-templates/logo.png b/examples/automate-after-effects-templates/logo.png new file mode 100644 index 0000000..e99ef0d Binary files /dev/null and b/examples/automate-after-effects-templates/logo.png differ diff --git a/examples/automate-after-effects-templates/montserrat-bold.woff2 b/examples/automate-after-effects-templates/montserrat-bold.woff2 new file mode 100644 index 0000000..1a510da Binary files /dev/null and b/examples/automate-after-effects-templates/montserrat-bold.woff2 differ diff --git a/examples/automate-after-effects-templates/one-row.csv b/examples/automate-after-effects-templates/one-row.csv new file mode 100644 index 0000000..cd8875d --- /dev/null +++ b/examples/automate-after-effects-templates/one-row.csv @@ -0,0 +1,2 @@ +PRODUCT,PRICE +Iced vanilla latte,$5.49 diff --git a/examples/automate-after-effects-templates/product-card-v2.json b/examples/automate-after-effects-templates/product-card-v2.json new file mode 100644 index 0000000..fef862d --- /dev/null +++ b/examples/automate-after-effects-templates/product-card-v2.json @@ -0,0 +1,198 @@ +{ + "v": "5.12.2", + "fr": 25, + "ip": 0, + "op": 125, + "w": 1000, + "h": 260, + "nm": "product-card", + "ddd": 0, + "assets": [], + "fonts": { + "list": [ + { + "origin": 0, + "fPath": "", + "fClass": "", + "fFamily": "Montserrat", + "fWeight": "", + "fStyle": "Bold", + "fName": "Montserrat-Bold", + "ascent": 74.1989135742188 + } + ] + }, + "layers": [ + { + "ddd": 0, + "ind": 1, + "ty": 5, + "nm": "PRICE", + "parent": 3, + "sr": 1, + "ks": { + "o": { + "a": 1, + "k": [ + { + "i": { "x": [0.833], "y": [0.833] }, + "o": { "x": [0.167], "y": [0.167] }, + "t": 25, + "s": [0] + }, + { "t": 40, "s": [100] } + ], + "ix": 11 + }, + "r": { "a": 0, "k": 0, "ix": 10 }, + "p": { "a": 0, "k": [238.971, 205.357, 0], "ix": 2, "l": 2 }, + "a": { "a": 0, "k": [0, 0, 0], "ix": 1, "l": 2 }, + "s": { "a": 0, "k": [100, 100, 100], "ix": 6, "l": 2 } + }, + "ao": 0, + "t": { + "d": { + "k": [ + { + "s": { + "sz": [290.966369628906, 78.7815093994141], + "ps": [-145.483184814453, -39.390754699707], + "s": 44, + "f": "Montserrat-Bold", + "t": "$4.99", + "ca": 0, + "j": 0, + "tr": 0, + "lh": 52.8000030517578, + "ls": 0, + "fc": [1, 0.82, 0.4] + }, + "t": 0 + } + ] + }, + "p": {}, + "m": { "g": 1, "a": { "a": 0, "k": [0, 0], "ix": 2 } }, + "a": [] + }, + "ip": 0, + "op": 125, + "st": 0, + "ct": 1, + "bm": 0 + }, + { + "ddd": 0, + "ind": 2, + "ty": 5, + "nm": "PRODUCT", + "parent": 3, + "sr": 1, + "ks": { + "o": { + "a": 1, + "k": [ + { + "i": { "x": [0.833], "y": [0.833] }, + "o": { "x": [0.167], "y": [0.167] }, + "t": 10, + "s": [0] + }, + { "t": 25, "s": [100] } + ], + "ix": 11 + }, + "r": { "a": 0, "k": 0, "ix": 10 }, + "p": { "a": 0, "k": [503.151, 82.458, 0], "ix": 2, "l": 2 }, + "a": { "a": 0, "k": [0, 0, 0], "ix": 1, "l": 2 }, + "s": { "a": 0, "k": [100, 100, 100], "ix": 6, "l": 2 } + }, + "ao": 0, + "t": { + "d": { + "k": [ + { + "s": { + "sz": [825.630249023438, 106.092437744141], + "ps": [-412.815124511719, -53.0462188720703], + "s": 56, + "f": "Montserrat-Bold", + "t": "Fresh mango juice", + "ca": 0, + "j": 0, + "tr": 0, + "lh": 67.2000045776367, + "ls": 0, + "fc": [1, 1, 1] + }, + "t": 0 + } + ] + }, + "p": {}, + "m": { "g": 1, "a": { "a": 0, "k": [0, 0], "ix": 2 } }, + "a": [] + }, + "ip": 0, + "op": 125, + "st": 0, + "ct": 1, + "bm": 0 + }, + { + "ddd": 0, + "ind": 3, + "ty": 1, + "nm": "Panel", + "sr": 1, + "ks": { + "o": { "a": 0, "k": 100, "ix": 11 }, + "r": { "a": 0, "k": 0, "ix": 10 }, + "p": { + "a": 1, + "k": [ + { + "i": { "x": 0.667, "y": 1 }, + "o": { "x": 0.333, "y": 0 }, + "t": 0, + "s": [-500, 130, 0], + "to": [0, 0, 0], + "ti": [0, 0, 0] + }, + { + "i": { "x": 0.667, "y": 0.667 }, + "o": { "x": 0.333, "y": 0.333 }, + "t": 15, + "s": [500, 130, 0], + "to": [0, 0, 0], + "ti": [0, 0, 0] + }, + { + "i": { "x": 0.667, "y": 1 }, + "o": { "x": 0.333, "y": 0 }, + "t": 110, + "s": [500, 130, 0], + "to": [0, 0, 0], + "ti": [0, 0, 0] + }, + { "t": 124, "s": [1500, 130, 0] } + ], + "ix": 2, + "l": 2 + }, + "a": { "a": 0, "k": [500, 130, 0], "ix": 1, "l": 2 }, + "s": { "a": 0, "k": [100, 100, 100], "ix": 6, "l": 2 } + }, + "ao": 0, + "sw": 1000, + "sh": 260, + "sc": "#1f3a5f", + "ip": 0, + "op": 125, + "st": 0, + "bm": 0 + } + ], + "markers": [], + "props": {} +} diff --git a/examples/automate-after-effects-templates/product-card.json b/examples/automate-after-effects-templates/product-card.json new file mode 100644 index 0000000..75f71d1 --- /dev/null +++ b/examples/automate-after-effects-templates/product-card.json @@ -0,0 +1,198 @@ +{ + "v": "5.12.2", + "fr": 25, + "ip": 0, + "op": 125, + "w": 1000, + "h": 260, + "nm": "product-card", + "ddd": 0, + "assets": [], + "fonts": { + "list": [ + { + "origin": 0, + "fPath": "", + "fClass": "", + "fFamily": "Montserrat", + "fWeight": "", + "fStyle": "Bold", + "fName": "Montserrat-Bold", + "ascent": 74.1989135742188 + } + ] + }, + "layers": [ + { + "ddd": 0, + "ind": 1, + "ty": 5, + "nm": "PRICE", + "parent": 3, + "sr": 1, + "ks": { + "o": { + "a": 1, + "k": [ + { + "i": { "x": [0.833], "y": [0.833] }, + "o": { "x": [0.167], "y": [0.167] }, + "t": 25, + "s": [0] + }, + { "t": 40, "s": [100] } + ], + "ix": 11 + }, + "r": { "a": 0, "k": 0, "ix": 10 }, + "p": { "a": 0, "k": [238.971, 205.357, 0], "ix": 2, "l": 2 }, + "a": { "a": 0, "k": [0, 0, 0], "ix": 1, "l": 2 }, + "s": { "a": 0, "k": [100, 100, 100], "ix": 6, "l": 2 } + }, + "ao": 0, + "t": { + "d": { + "k": [ + { + "s": { + "sz": [290.966369628906, 78.7815093994141], + "ps": [-145.483184814453, -39.390754699707], + "s": 44, + "f": "Montserrat-Bold", + "t": "$4.99", + "ca": 0, + "j": 0, + "tr": 0, + "lh": 52.8000030517578, + "ls": 0, + "fc": [1, 0.82, 0.4] + }, + "t": 0 + } + ] + }, + "p": {}, + "m": { "g": 1, "a": { "a": 0, "k": [0, 0], "ix": 2 } }, + "a": [] + }, + "ip": 0, + "op": 125, + "st": 0, + "ct": 1, + "bm": 0 + }, + { + "ddd": 0, + "ind": 2, + "ty": 5, + "nm": "PRODUCT", + "parent": 3, + "sr": 1, + "ks": { + "o": { + "a": 1, + "k": [ + { + "i": { "x": [0.833], "y": [0.833] }, + "o": { "x": [0.167], "y": [0.167] }, + "t": 10, + "s": [0] + }, + { "t": 25, "s": [100] } + ], + "ix": 11 + }, + "r": { "a": 0, "k": 0, "ix": 10 }, + "p": { "a": 0, "k": [503.151, 82.458, 0], "ix": 2, "l": 2 }, + "a": { "a": 0, "k": [0, 0, 0], "ix": 1, "l": 2 }, + "s": { "a": 0, "k": [100, 100, 100], "ix": 6, "l": 2 } + }, + "ao": 0, + "t": { + "d": { + "k": [ + { + "s": { + "sz": [825.630249023438, 106.092437744141], + "ps": [-412.815124511719, -53.0462188720703], + "s": 56, + "f": "Montserrat-Bold", + "t": "Fresh mango juice", + "ca": 0, + "j": 0, + "tr": 0, + "lh": 67.2000045776367, + "ls": 0, + "fc": [1, 1, 1] + }, + "t": 0 + } + ] + }, + "p": {}, + "m": { "g": 1, "a": { "a": 0, "k": [0, 0], "ix": 2 } }, + "a": [] + }, + "ip": 0, + "op": 125, + "st": 0, + "ct": 1, + "bm": 0 + }, + { + "ddd": 0, + "ind": 3, + "ty": 1, + "nm": "Panel", + "sr": 1, + "ks": { + "o": { "a": 0, "k": 100, "ix": 11 }, + "r": { "a": 0, "k": 0, "ix": 10 }, + "p": { + "a": 1, + "k": [ + { + "i": { "x": 0.667, "y": 1 }, + "o": { "x": 0.333, "y": 0 }, + "t": 0, + "s": [-500, 130, 0], + "to": [0, 0, 0], + "ti": [0, 0, 0] + }, + { + "i": { "x": 0.667, "y": 0.667 }, + "o": { "x": 0.333, "y": 0.333 }, + "t": 15, + "s": [500, 130, 0], + "to": [0, 0, 0], + "ti": [0, 0, 0] + }, + { + "i": { "x": 0.667, "y": 1 }, + "o": { "x": 0.333, "y": 0 }, + "t": 110, + "s": [500, 130, 0], + "to": [0, 0, 0], + "ti": [0, 0, 0] + }, + { "t": 124, "s": [1500, 130, 0] } + ], + "ix": 2, + "l": 2 + }, + "a": { "a": 0, "k": [500, 130, 0], "ix": 1, "l": 2 }, + "s": { "a": 0, "k": [100, 100, 100], "ix": 6, "l": 2 } + }, + "ao": 0, + "sw": 1000, + "sh": 260, + "sc": "#0b5d3b", + "ip": 0, + "op": 125, + "st": 0, + "bm": 0 + } + ], + "markers": [], + "props": {} +} diff --git a/examples/automate-after-effects-templates/render-videos.js b/examples/automate-after-effects-templates/render-videos.js new file mode 100644 index 0000000..7a35423 --- /dev/null +++ b/examples/automate-after-effects-templates/render-videos.js @@ -0,0 +1,225 @@ +// Renders one video per row of data.csv from the saved template, and downloads each one. +// Run it again after a failure: rows already downloaded are skipped, and renders that were +// sent but not downloaded are picked up again instead of being rendered twice. A render +// request that got no answer is sent again, so it can render twice if Shotstack did get it. +// Usage: node render-videos.js [data.csv] +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); +const { + EDIT_API, + api, + waitForRender, + download, + readStep, + sleep +} = require('./shotstack'); + +// The fields come from the saved template, so a new text layer only needs a new CSV column. +// These limits are a safety net, not a guarantee: the card shrinks long text, but very long values still won't fit. +const MAX_LENGTH = { PRODUCT: 60, PRICE: 10 }; + +// Reads a CSV file with a header row. Handles quoted values with commas and "" quotes. +function readCsv(file, fields) { + const name = path.basename(file); + if (!fs.existsSync(file)) throw new Error(`Can't find ${name}.`); + const rows = []; + let row = []; + let value = ''; + let quoted = false; + const text = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''); + for (let i = 0; i < text.length; i++) { + const char = text[i]; + if (quoted) { + if (char === '"' && text[i + 1] === '"') { + value += '"'; + i++; + } else if (char === '"') quoted = false; + else value += char; + } else if (char === '"' && value === '') quoted = true; + else if (char === ',') { + row.push(value); + value = ''; + } else if (char === '\n' || char === '\r') { + if (char === '\r' && text[i + 1] === '\n') i++; + row.push(value); + rows.push(row); + row = []; + value = ''; + } else value += char; + } + if (quoted) throw new Error(`${name} has a quote that is never closed.`); + if (value || row.length) { + row.push(value); + rows.push(row); + } + const [header, ...data] = rows.filter(r => + r.some(cell => cell.trim() !== '') + ); + const columns = (header || []).map(cell => cell.trim()); + if (fields.some(field => !columns.includes(field))) + throw new Error( + `${name} needs a header row with the columns ${fields.join(', ')}.` + ); + return data.map(cells => + Object.fromEntries(columns.map((col, i) => [col, (cells[i] || '').trim()])) + ); +} + +// Merge values go into HTML, so escape the characters HTML treats as markup. +function escapeHtml(value) { + return value + .replace(/&/g, '&') + .replace(//g, '>'); +} + +function problemsWith(row, fields) { + const problems = []; + for (const field of fields) { + const max = MAX_LENGTH[field] ?? Infinity; + if (!row[field]) problems.push(`${field} is empty`); + else if (row[field].length > max) + problems.push( + `${field} is ${row[field].length} characters (limit ${max})` + ); + } + return problems; +} + +function slug(text) { + return text + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, '') + .slice(0, 40); +} + +async function main() { + const id = readStep('template-id.txt', 'create-template.js').trim(); + // The key below includes the API, the template id and the design, so a design update renders every row again. + const templateJson = readStep('template.json', 'create-template.js'); + const fields = JSON.parse(templateJson).merge.map(m => m.find); + const rows = readCsv( + path.join(__dirname, process.argv[2] || 'data.csv'), + fields + ); + fs.mkdirSync(path.join(__dirname, 'videos'), { recursive: true }); + + // Results of earlier runs, keyed by template + values, so a new run can resume them. + const resultsFile = path.join(__dirname, 'render-results.json'); + let earlier = []; + if (fs.existsSync(resultsFile)) { + try { + earlier = JSON.parse(fs.readFileSync(resultsFile, 'utf8')); + } catch { + throw new Error( + 'render-results.json is not valid JSON. Delete it to start again.' + ); + } + } + const results = new Map(earlier.map(r => [r.key, r])); + const save = () => + fs.writeFileSync( + resultsFile, + JSON.stringify([...results.values()], null, 2) + ); + const current = []; + + // Send one render request per row, about one per second. + for (const [index, row] of rows.entries()) { + const name = `${String(index + 1).padStart(2, '0')}-${slug(row.PRODUCT || 'row')}`; + const merge = fields.map(field => ({ + find: field, + replace: escapeHtml(row[field] || '') + })); + const key = crypto + .createHash('sha1') + .update(EDIT_API + id + templateJson + JSON.stringify(merge)) + .digest('hex'); + const before = results.get(key); + if ( + before?.status === 'done' && + before.video && + fs.existsSync(path.join(__dirname, before.video)) + ) { + console.log(` ${name}: already rendered (${before.video})`); + continue; + } + if (before?.id && before.status !== 'failed') { + console.log(` ${name}: picking up render ${before.id}`); + current.push(before); + continue; + } + const result = { key, name, row }; + results.set(key, result); + current.push(result); + const problems = problemsWith(row, fields); + if (problems.length) { + result.status = 'skipped'; + result.error = problems.join('; '); + console.log(` ${name}: skipped (${result.error})`); + save(); + continue; + } + try { + const { response } = await api('POST', `${EDIT_API}/templates/render`, { + id, + merge + }); + if (!response?.id) throw new Error('The API returned no render id.'); + result.id = response.id; + result.status = 'queued'; + console.log(` ${name}: queued (${response.id})`); + } catch (err) { + result.status = 'not sent'; + result.error = err.message; + console.log(` ${name}: not sent. ${err.message}`); + } + save(); + await sleep(1000); + } + + // Wait for each render, then download the video. + const pending = current.filter(r => r.id); + if (pending.length) console.log('Waiting for renders to finish...'); + for (const result of pending) { + try { + const render = await waitForRender(result.id); + result.status = render.status; + result.url = render.url || null; + result.error = render.error || null; + if (render.status === 'done' && !render.url) { + result.status = 'unknown'; + result.error = + 'The render finished without a video URL. Run the script again to check it.'; + } + if (result.status === 'done') { + result.video = path.join( + 'videos', + `${result.name}-${result.key.slice(0, 6)}.mp4` + ); + await download(render.url, path.join(__dirname, result.video)); + } + } catch (err) { + // 403 or 404: the render or its video is gone (another environment, or a deleted file), + // so the next run renders it again. A timeout or a dropped connection keeps the render id + // for the next run to check. + result.status = [403, 404].includes(err.status) ? 'failed' : 'unknown'; + result.video = null; + result.error = err.message; + } + save(); + console.log( + ` ${result.name}: ${result.status}${result.video ? ` saved ${result.video}` : ''}${result.error ? ` ${result.error}` : ''}` + ); + } + console.log(`Saved results to ${path.basename(resultsFile)}`); +} + +main().catch(err => { + console.error(err.message); + process.exit(1); +}); diff --git a/examples/automate-after-effects-templates/setup-assets.js b/examples/automate-after-effects-templates/setup-assets.js new file mode 100644 index 0000000..cd095d2 --- /dev/null +++ b/examples/automate-after-effects-templates/setup-assets.js @@ -0,0 +1,65 @@ +// Uploads the footage, music and logo to Shotstack's Ingest API, which hosts them at public URLs +// the template can use. Saves the URLs in assets.json. +// Usage: node setup-assets.js +const fs = require('fs'); +const path = require('path'); +const { INGEST_API, api, sleep } = require('./shotstack'); + +const FILES = { footage: 'footage.mp4', music: 'music.mp3', logo: 'logo.png' }; +const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000; + +async function upload(file) { + // 1. Ask Ingest for a signed upload URL. + const { data } = await api('POST', `${INGEST_API}/upload`); + // 2. PUT the file to that URL. + let res; + try { + res = await fetch(data.attributes.url, { + method: 'PUT', + body: fs.readFileSync(file), + signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS) + }); + } catch { + throw new Error( + `Uploading ${path.basename(file)} failed. Check your network connection and run the script again.` + ); + } + if (!res.ok) + throw new Error( + `Uploading ${path.basename(file)} failed: HTTP ${res.status}` + ); + // 3. Wait until Ingest has stored it, then return its URL. + for (let attempt = 0; attempt < 60; attempt++) { + const source = await api('GET', `${INGEST_API}/sources/${data.id}`); + const { status, source: url } = source.data.attributes; + if (status === 'ready') return url; + if (status === 'failed') + throw new Error(`Ingest couldn't process ${path.basename(file)}.`); + await sleep(5000); + } + throw new Error(`${path.basename(file)} wasn't ready after 5 minutes.`); +} + +async function main() { + for (const file of Object.values(FILES)) { + if (!fs.existsSync(path.join(__dirname, file))) { + throw new Error(`Can't find ${file} next to this script.`); + } + } + const assets = {}; + for (const [name, file] of Object.entries(FILES)) { + console.log(`Uploading ${file}...`); + assets[name] = await upload(path.join(__dirname, file)); + console.log(` ${assets[name]}`); + } + fs.writeFileSync( + path.join(__dirname, 'assets.json'), + JSON.stringify(assets, null, 2) + ); + console.log('Saved the URLs to assets.json'); +} + +main().catch(err => { + console.error(err.message); + process.exit(1); +}); diff --git a/examples/automate-after-effects-templates/shotstack.js b/examples/automate-after-effects-templates/shotstack.js new file mode 100644 index 0000000..e9c45e7 --- /dev/null +++ b/examples/automate-after-effects-templates/shotstack.js @@ -0,0 +1,137 @@ +// Small helpers for the Shotstack Edit and Ingest APIs (Node.js 22 or newer, no packages). +const fs = require('fs'); +const path = require('path'); + +const KEY = process.env.SHOTSTACK_API_KEY; +if (!KEY) { + console.error('Set SHOTSTACK_API_KEY to your Shotstack API key first.'); + process.exit(1); +} + +// v1 is the production API. +const ENV = process.env.SHOTSTACK_ENV || 'v1'; +if (!['v1', 'stage'].includes(ENV)) { + console.error('SHOTSTACK_ENV must be v1 or stage.'); + process.exit(1); +} +const EDIT_API = `https://api.shotstack.io/edit/${ENV}`; +const INGEST_API = `https://api.shotstack.io/ingest/${ENV}`; + +const REQUEST_TIMEOUT_MS = 30 * 1000; +const DOWNLOAD_TIMEOUT_MS = 2 * 60 * 1000; +const POLL_INTERVAL_MS = 5 * 1000; +const RENDER_TIMEOUT_MS = 10 * 60 * 1000; + +const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); + +// Calls the API and returns the parsed JSON. +// Retries after a 429 (too many requests). Reads and updates also retry after a dropped +// connection or a server error. Create and render requests (POST) don't, so one run never sends them twice. +async function api(method, url, body) { + for (let attempt = 1; ; attempt++) { + let res; + try { + res = await fetch(url, { + method, + headers: { + 'x-api-key': KEY, + 'content-type': 'application/json', + accept: 'application/json' + }, + body: body ? JSON.stringify(body) : undefined, + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) + }); + } catch { + if (method === 'POST' || attempt >= 4) { + throw new Error( + "Can't reach the Shotstack API. Check your network connection and run the script again." + ); + } + await sleep(2000 * attempt); + continue; + } + const text = await res.text(); + if (res.status === 401 || res.status === 403) { + throw new Error( + `The API rejected the key (HTTP ${res.status}). Check SHOTSTACK_API_KEY and SHOTSTACK_ENV.` + ); + } + if (res.ok) { + try { + return JSON.parse(text); + } catch { + throw new Error( + `${method} ${url} returned a response that isn't JSON.` + ); + } + } + const retry = + res.status === 429 || (method !== 'POST' && res.status >= 500); + if (retry && attempt < 4) { + await sleep( + Number(res.headers.get('retry-after')) * 1000 || 2000 * attempt + ); + continue; + } + let detail = text; + try { + const err = JSON.parse(text); + detail = err.errors?.[0]?.detail || err.response?.error || err.message; + } catch {} + throw Object.assign( + new Error( + `${method} ${url} returned ${res.status}: ${String(detail || text).slice(0, 300)}` + ), + { status: res.status } + ); + } +} + +// Polls a render until it's done or failed. +async function waitForRender(id) { + for (let waited = 0; waited < RENDER_TIMEOUT_MS; waited += POLL_INTERVAL_MS) { + const { response } = await api('GET', `${EDIT_API}/render/${id}`); + if (response?.status === 'done' || response?.status === 'failed') { + return response; + } + await sleep(POLL_INTERVAL_MS); + } + throw new Error( + `Render ${id} didn't finish within ${RENDER_TIMEOUT_MS / 60000} minutes.` + ); +} + +// Saves a file from a URL. If it fails, the next run of render-videos.js tries again. +async function download(url, file) { + const res = await fetch(url, { + signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) + }).catch(() => null); + if (!res?.ok) { + throw Object.assign( + new Error('The download failed. Run the script again.'), + { + status: res?.status + } + ); + } + fs.writeFileSync(file, Buffer.from(await res.arrayBuffer())); +} + +// Reads a file an earlier step wrote next to the scripts, or says which step to run first. +function readStep(file, step) { + const full = path.join(__dirname, file); + if (!fs.existsSync(full)) { + throw new Error(`Can't find ${file}. Run node ${step} first.`); + } + return fs.readFileSync(full, 'utf8'); +} + +module.exports = { + EDIT_API, + INGEST_API, + api, + waitForRender, + download, + readStep, + sleep +}; diff --git a/examples/automate-after-effects-templates/update-template.js b/examples/automate-after-effects-templates/update-template.js new file mode 100644 index 0000000..7c5a23c --- /dev/null +++ b/examples/automate-after-effects-templates/update-template.js @@ -0,0 +1,44 @@ +// Updates the saved template after the designer re-exports the card from After Effects. +// The new export must keep the same field layer names, so the render script and data still match. +// Usage: node update-template.js [export.json] (defaults to product-card-v2.json) +const fs = require('fs'); +const path = require('path'); +const { EDIT_API, api, readStep } = require('./shotstack'); +const { buildTemplate, fieldNames, readExport } = require('./build-template'); + +async function main() { + const exportFile = path.join( + __dirname, + process.argv[2] || 'product-card-v2.json' + ); + const lottie = readExport(exportFile); + const assets = JSON.parse(readStep('assets.json', 'setup-assets.js')); + const id = readStep('template-id.txt', 'create-template.js').trim(); + + // Check the new export still has every field the current template uses. + const { response: current } = await api('GET', `${EDIT_API}/templates/${id}`); + const oldFields = (current?.template?.merge || []).map(m => m.find); + const missing = oldFields.filter(name => !fieldNames(lottie).includes(name)); + if (missing.length) { + throw new Error( + `The new export is missing ${missing.join(', ')}. Ask the designer to keep those layer names.` + ); + } + + const template = buildTemplate({ lottie, assets }); + await api('PUT', `${EDIT_API}/templates/${id}`, { + name: 'Product card', + template + }); + // Written only after the API has the new design, because render-videos.js resumes from it. + fs.writeFileSync( + path.join(__dirname, 'template.json'), + JSON.stringify(template, null, 2) + ); + console.log(`Template ${id} updated from ${path.basename(exportFile)}.`); +} + +main().catch(err => { + console.error(err.message); + process.exit(1); +});