Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions examples/automate-after-effects-templates/.env.example
Original file line number Diff line number Diff line change
@@ -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=
13 changes: 13 additions & 0 deletions examples/automate-after-effects-templates/.gitignore
Original file line number Diff line number Diff line change
@@ -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/
93 changes: 93 additions & 0 deletions examples/automate-after-effects-templates/Montserrat-OFL.txt
Original file line number Diff line number Diff line change
@@ -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.
62 changes: 62 additions & 0 deletions examples/automate-after-effects-templates/README.md
Original file line number Diff line number Diff line change
@@ -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`.
Binary file not shown.
Binary file not shown.
211 changes: 211 additions & 0 deletions examples/automate-after-effects-templates/build-template.js
Original file line number Diff line number Diff line change
@@ -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 = ['<div id="card"></div>']
.concat(
fields.map(name => `<div hidden data-field="${name}">{{ ${name} }}</div>`)
)
.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 };
Loading
Loading