shotstack/shotstack-sdk-php

Official PHP SDK for the Shotstack Cloud Video Editing API

0.2.6 2024-05-20 05:58 UTC

README

PHP SDK for the Shotstack PHP video editor and cloud video editing API.

Shotstack is a cloud based video editing platform that enables the editing of videos using code.

The platform uses an API and a JSON format for specifying how videos should be edited and what assets and titles should be used.

A server based render farm takes care of rendering the videos allowing multiple videos to be created simultaneously.

For examples of how to use the SDK to create videos using code checkout the PHP demo repo: https://github.com/shotstack/php-demos

Contents

Using the PHP SDK

Requirements

Requires PHP7.4+ and uses Guzzle7.3+.

Installation

The recommended way to use the SDK is as a composer package. Install using the command:

composer require shotstack/shotstack-sdk-php

Video Editing

The Shotstack SDK enables programmatic video editing via the Edit API render endpoint. Prepare JSON edits using the provided schema classes and POST to the API for rendering.

Video Editing Example

The example below trims the start of a video clip and plays it for 8 seconds. The edit is prepared using the SDK models and then sent to the API for rendering.

<?php
require 'vendor/autoload.php';

use Shotstack\Client\Api\EditApi;
use Shotstack\Client\Configuration;
use Shotstack\Client\Model\Edit;
use Shotstack\Client\Model\Output;
use Shotstack\Client\Model\Timeline;
use Shotstack\Client\Model\Track;
use Shotstack\Client\Model\Clip;
use Shotstack\Client\Model\VideoAsset;

$config = Configuration::getDefaultConfiguration()
    ->setHost('https://api.shotstack.io/stage')
    ->setApiKey('x-api-key', 'H7jKyj90kd09lbLOF7J900jNbSWS67X87xs9j0cD'); // use the correct API key

$client = new EditApi(null, $config);

$videoAsset = new VideoAsset();
$videoAsset
    ->setSrc('https://s3-ap-southeast-2.amazonaws.com/shotstack-assets/footage/skater.hd.mp4')
    ->setTrim(3);

$videoClip = new Clip();
$videoClip
    ->setAsset($videoAsset)
    ->setLength(8)
    ->setStart(0);

$track = new Track();
$track->setClips([$videoClip]);

$timeline = new Timeline();
$timeline->setTracks([$track]);

$output = new Output();
$output
    ->setFormat('mp4')
    ->setResolution('sd');

$edit = new Edit();
$edit
    ->setTimeline($timeline)
    ->setOutput($output);

$render = $client->postRender($edit)->getResponse();

Status Check Example

The example request below can be called a few seconds after the render above is posted. It will return the status of the render, which can take several seconds to process. It uses the render->getId() method returned by the postRender request.

use Shotstack\Client\Api\EditApi;
use Shotstack\Client\Configuration;

$config = Configuration::getDefaultConfiguration()
    ->setHost('https://api.shotstack.io/stage')
    ->setApiKey('x-api-key', 'H7jKyj90kd09lbLOF7J900jNbSWS67X87xs9j0cD'); // use the correct API key

$client = new EditApi(null, $config);

$video = $client->getRender($render->getId())->getResponse();

if ($video->getStatus() === 'done') {
    echo $video->getUrl();
}

Save a Template Example

The example below uses the Edit we create in the Video Editing Example and saves it as a template. The template can be rendered at a later date and can include placeholders. Placeholders can be replaced when rendered using merge fields.

This example uses a placeholder for the video src (URL), trim (TRIM), and length (LENGTH) to allow you to trim any video using a template.

<?php
require 'vendor/autoload.php';

use Shotstack\Client\Api\EditApi;
use Shotstack\Client\ApiException;
use Shotstack\Client\Configuration;
use Shotstack\Client\Model\Edit;
use Shotstack\Client\Model\Output;
use Shotstack\Client\Model\Timeline;
use Shotstack\Client\Model\Track;
use Shotstack\Client\Model\Clip;
use Shotstack\Client\Model\VideoAsset;
use Shotstack\Client\Model\Template;

$config = Configuration::getDefaultConfiguration()
    ->setHost('https://api.shotstack.io/stage')
    ->setApiKey('x-api-key', 'H7jKyj90kd09lbLOF7J900jNbSWS67X87xs9j0cD'); // use the correct API key

$client = new EditApi(null, $config);

$videoAsset = new videoAsset();
$videoAsset
    ->setSrc('{{ URL }}')
    ->setTrim('{{ TRIM }}');

$videoClip = new Clip();
$videoClip
    ->setAsset($videoAsset)
    ->setStart(0)
    ->setLength('{{ LENGTH }}');

$track = new Track();
$track
    ->setClips([$videoClip]);

$timeline = new Timeline();
$timeline
    ->setTracks([$track]);

$output = new Output();
$output
    ->setFormat('mp4')
    ->setResolution('sd');

$edit = new Edit();
$edit
    ->setTimeline($timeline)
    ->setOutput($output);

$template = new Template();
$template
    ->setName('Trim Template')
    ->setTemplate($edit);

$response = $client->postTemplate($template)->getResponse();

Render a Template Example

The example below renders the template we created in the previous example and includes merge fields that will replace the placeholders. Once submitted use the returned render ID and call the Status Check Example to get the render progress. It uses the response->getId() method returned by the postTemplate request.

use Shotstack\Client\Api\EditApi;
use Shotstack\Client\Configuration;

$config = Configuration::getDefaultConfiguration()
    ->setHost('https://api.shotstack.io/stage')
    ->setApiKey('x-api-key', 'H7jKyj90kd09lbLOF7J900jNbSWS67X87xs9j0cD'); // use the correct API key

$client = new EditApi(null, $config);

$mergeFieldUrl = new MergeField();
$mergeFieldUrl
    ->setFind('URL')
    ->setReplace('https://s3-ap-southeast-2.amazonaws.com/shotstack-assets/footage/skater.hd.mp4');

$mergeFieldTrim = new MergeField();
$mergeFieldTrim
    ->setFind('TRIM')
    ->setReplace(3);

$mergeFieldLength = new MergeField();
$mergeFieldLength
    ->setFind('LENGTH')
    ->setReplace(6);

$template = new TemplateRender();
$template
    ->setId($response->id)
    ->setMerge([
        $mergeFieldUrl,
        $mergeFieldTrim,
        $mergeFieldLength,
    ]);

$video = $client->postTemplateRender($template)->getResponse();

if ($video->getStatus() === 'done') {
    echo $video->getUrl();
}

Video Editing Schemas

The following schemas are used to prepare a video edit.

Edit()

An Edit defines the arrangement of a video on a timeline, an audio edit or an image design and the output format.

Example:

use Shotstack\Client\Model\Edit;

$edit = new Edit();
$edit
  ->setTimeline($timeline)
  ->setOutput($output)
  ->setMerge($merge)
  ->setCallback('https://my-server.com/callback.php')
  ->setDisk('local');

Methods:

Timeline()

A Timeline represents the contents of a video edit over time, an audio edit over time, in seconds, or an image layout. A timeline consists of layers called tracks. Tracks are composed of titles, images, audio, html or video segments referred to as clips which are placed along the track at specific starting point and lasting for a specific amount of time.

Example:

use Shotstack\Client\Model\Timeline;

$timeline = new Timeline();
$timeline
  ->setSoundtrack($soundtrack)
  ->setBackground('#000000')
  ->setFonts($fonts)
  ->setTracks($tracks)
  ->setCache(true);

Methods:

Soundtrack()

A music or audio file in mp3 format that plays for the duration of the rendered video or the length of the audio file, which ever is shortest.

Example:

use Shotstack\Client\Model\Soundtrack;

$soundtrack = new Soundtrack();
$soundtrack
  ->setSrc('https://s3-ap-southeast-2.amazonaws.com/shotstack-assets/music/disco.mp3')
  ->setEffect('fadeIn')
  ->setVolume(1);

Methods:

Font()

Download a custom font to use with the HTML asset type, using the font name in the CSS or font tag. See our custom fonts getting started guide for more details.

Example:

use Shotstack\Client\Model\Font;

$font = new Font();
$font
  ->setSrc('https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/fonts/OpenSans-Regular.ttf');

Methods:

Track()

A track contains an array of clips. Tracks are layered on top of each other in the order in the array. The top most track will render on top of those below it.

Example:

use Shotstack\Client\Model\Track;

$track = new Track();
$track
  ->setClips($clips);

Methods:

Clip()

A Clip is a container for a specific type of asset, i.e. a title, image, video, audio or html. You use a Clip to define when an asset will display on the timeline, how long it will play for and transitions, filters and effects to apply to it.

Example:

use Shotstack\Client\Model\Clip;

$clip = new Clip();
$clip
  ->setAsset($asset)
  ->setStart(2)
  ->setLength(5)
  ->setFit('crop')
  ->setScale(0)
  ->setPosition('center')
  ->setOffset($offset)
  ->setTransition($transition)
  ->setEffect('zoomIn')
  ->setFilter('greyscale')
  ->setOpacity(1)
  ->setTransform($transform);

Methods:

VideoAsset()

The VideoAsset is used to create video sequences from video files. The src must be a publicly accessible URL to a video resource such as an mp4 file.

Example:

use Shotstack\Client\Model\VideoAsset;

$videoAsset = new VideoAsset();
$videoAsset
  ->setSrc('https://shotstack-assets.s3.aws.com/mountain.mp4')
  ->setTrim(5)
  ->setVolume(0.5)
  ->setVolumeEffect('fadeIn')
  ->setCrop($crop);

Methods:

ImageAsset()

The ImageAsset is used to create video from images to compose an image. The src must be a publicly accessible URL to an image resource such as a jpg or png file.

Example:

use Shotstack\Client\Model\ImageAsset;

$imageAsset = new ImageAsset();
$imageAsset
  ->setSrc('https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/images/earth.jpg')
  ->setCrop($crop);

Methods:

TitleAsset()

The TitleAsset clip type lets you create video titles from a text string and apply styling and positioning.

Example:

use Shotstack\Client\Model\TitleAsset;

$titleAsset = new TitleAsset();
$titleAsset
  ->setText('My Title')
  ->setStyle('minimal')
  ->setColor('#ffffff')
  ->setSize('medium')
  ->setBackground('#000000')
  ->setPosition('center')
  ->setOffset($offset);

Methods:

HtmlAsset()

The HtmlAsset clip type lets you create text based layout and formatting using HTML and CSS. You can also set the height and width of a bounding box for the HTML content to sit within. Text and elements will wrap within the bounding box.

Example:

use Shotstack\Client\Model\HtmlAsset;

$htmlAsset = new HtmlAsset();
$htmlAsset
  ->setHtml('<p>Hello <b>World</b></p>')
  ->setCss('p { color: #ffffff; } b { color: #ffff00; }')
  ->setWidth(400)
  ->setHeight(200)
  ->setBackground('transparent')
  ->setPosition('center);

Methods:

AudioAsset()

The AudioAsset is used to add sound effects and audio at specific intervals on the timeline. The src must be a publicly accessible URL to an audio resource such as an mp3 file.

Example:

use Shotstack\Client\Model\AudioAsset;

$audioAsset = new AudioAsset();
$audioAsset
  ->setSrc('https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/music/unminus/lit.mp3')
  ->setTrim(2)
  ->setVolume(0.5)
  ->setEffect('fadeInFadeOut');

Methods:

LumaAsset()

The LumaAsset is used to create luma matte masks, transitions and effects between other assets. A luma matte is a grey scale image or animated video where the black areas are transparent and the white areas solid. The luma matte animation should be provided as an mp4 video file. The src must be a publicly accessible URL to the file.

Example:

use Shotstack\Client\Model\LumaAsset;

$lumaAsset = new LumaAsset();
$lumaAsset
  ->setSrc('https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/examples/luma-mattes/paint-left.mp4')
  ->setTrim(5);

Methods:

Transition()

The Transition clip type lets you define in and out transitions for a clip - i.e. fade in and fade out

Example:

use Shotstack\Client\Model\Transition;

$transition = new Transition();
$transition
  ->setIn('fade')
  ->setOut('fade');

Methods:

Offset()

Offsets the position of an asset horizontally or vertically by a relative distance.

Example:

use Shotstack\Client\Model\Offset;

$offset = new Offset();
$offset
  ->setX(0.1)
  ->setY(-0.2);

Methods:

Crop()

Crop the sides of an asset by a relative amount. The size of the crop is specified using a scale between 0 and 1, relative to the screen width - i.e a left crop of 0.5 will crop half of the asset from the left, a top crop of 0.25 will crop the top by quarter of the asset.

Example:

use Shotstack\Client\Model\Crop;

$crop = new Crop();
$crop
  ->setTop(0.15)
  ->setBottom(0.15)
  ->setLeft(0)
  ->setRight(0);

Methods:

Transformation()

Apply one or more transformations to a clip. Transformations alter the visual properties of a clip and can be combined to create new shapes and effects.

Example:

use Shotstack\Client\Model\Transformation;

$transformation = new Transformation();
$transformation
  ->setRotate($rotate)
  ->setSkew($skew)
  ->setFlip($flip);

Methods:

RotateTransformation()

Rotate a clip by the specified angle in degrees. Rotation origin is set based on the clips position.

Example:

use Shotstack\Client\Model\RotateTransformation;

$rotateTransformation = new RotateTransformation();
$rotateTransformation
  ->setAngle(45);

Methods:

SkewTransformation()

Skew a clip so its edges are sheared at an angle. Use values between 0 and 3. Over 3 the clip will be skewed almost flat.

Example:

use Shotstack\Client\Model\SkewTransformation;

$skewTransformation = new SkewTransformation();
$skewTransformation
  ->setX(0.5)
  ->setY(0.5);

Methods:

FlipTransformation()

Flip a clip vertically or horizontally. Acts as a mirror effect of the clip along the selected plane.

Example:

use Shotstack\Client\Model\FlipTransformation;

$flipTransformation = new FlipTransformation();
$flipTransformation
  ->setHorizontal(true)
  ->setVertical(true);

Methods:

MergeField()

A merge field consists of a key; find, and a value; replace. Merge fields can be used to replace placeholders within the JSON edit to create re-usable templates. Placeholders should be a string with double brace delimiters, i.e. "{{NAME}}". A placeholder can be used for any value within the JSON edit.

Example:

use Shotstack\Client\Model\MergeField;

$mergeField = new MergeField();
$mergeField
  ->setFind('NAME')
  ->setReplace('Jane');

Methods:

Template Schemas

The following schemas specify how to use templates to store and render templates. A template lets you save an Edit that can be rendered by its template ID and optionally include merge fields that are merged with the template when rendered.

Template()

A template is a saved Edit than can be loaded and re-used.

Example:

use Shotstack\Client\Model\Template;

$template = new Template();
$template
  ->setName('My Template')
  ->setTemplate($edit);

Methods:

TemplateRender()

Configure the id and optional merge fields to render a template by id.

Example:

use Shotstack\Client\Model\TemplateRender;

$render = new TemplateRender();
$render
  ->setId('21e781c0-8232-4418-fec1-cc99f0280c21')
  ->setMerge($merge);

Methods:

Output Schemas

The following schemas specify the output format and settings.

Output()

The output format, render range and type of media to generate.

Example:

use Shotstack\Client\Model\Output;

$output = new Output();
$output
  ->setFormat('mp4')
  ->setResolution('sd')
  ->setAspectRatio('16:9')
  ->setSize($size)
  ->setFps(25)
  ->setScaleTo('preview')
  ->setQuality('mediue')
  ->setRepeat(true)
  ->setMute(false)
  ->setRange($range)
  ->setPoster($poster)
  ->setThumbnail($thumbnail)
  ->setDestinations($destinations);

Methods:

Size()

Set a custom size for a video or image. When using a custom size omit the resolution and aspectRatio. Custom sizes must be divisible by 2 based on the encoder specifications.

Example:

use Shotstack\Client\Model\Size;

$size = new Size();
$size
  ->setWidth(1200)
  ->setHeight(800);

Methods:

Range()

Specify a time range to render, i.e. to render only a portion of a video or audio file. Omit this setting to export the entire video. Range can also be used to render a frame at a specific time point - setting a range and output format as jpg will output a single frame image at the range start point.

Example:

use Shotstack\Client\Model\Range;

$range = new Range();
$range
  ->setStart(3)
  ->setLength(6);

Methods:

Poster()

Generate a Poster image for the video at a specific point from the timeline. The poster image size will match the size of the output video.

Example:

use Shotstack\Client\Model\Poster;

$poster = new Poster();
$poster
  ->setCapture(1);

Methods:

Thumbnail()

Generate a thumbnail image for the video or image at a specific point from the timeline.

Example:

use Shotstack\Client\Model\Thumbnail;

$thumbnail = new Thumbnail();
$thumbnail
  ->setCapture(1)
  ->setScale(0.3);

Methods:

Destinations

ShotstackDestination()

Send rendered assets to the Shotstack hosting and CDN service. This destination is enabled by default.

Example:

use Shotstack\Client\Model\ShotstackDestination;

$shotstackDestination = new ShotstackDestination();
$shotstackDestination
  ->setProvider('shotstack')
  ->setExclude(false);

Methods:

MuxDestination()

Send rendered videos to the Mux video hosting and streaming service. Mux credentials are required and added via the dashboard, not in the request.

Example:

use Shotstack\Client\Model\MuxDestination;

$muxDestination = new MuxDestination();
$muxDestination
  ->setProvider('mux')
  ->setOptions($muxDestinationOptions);

Methods:

MuxDestinationOptions()

Pass additional options to control how Mux processes video. Currently supports playback policy option.

Example:

use Shotstack\Client\Model\MuxDestinationOptions;

$muxDestinationOptions = new MuxDestinationOptions();
$muxDestinationOptions
  ->setPlaybackPolicy(['public']);

Methods:

S3Destination()

Send rendered videos to an Amazon S3 bucket. Send files to any region with your own prefix and filename. AWS credentials are required and added via the dashboard, not in the request.

Example:

use Shotstack\Client\Model\S3Destination;

$s3Destination = new S3Destination();
$s3Destination
  ->setProvider('s3')
  ->setOptions($s3DestinationOptions);

Methods:

S3DestinationOptions()

Pass additional options to control how files are stored in S3.

Example:

use Shotstack\Client\Model\S3DestinationOptions;

$s3DestinationOptions = new S3DestinationOptions();
$s3DestinationOptions
  ->setRegion('us-east-1');
  ->setBucket('my-bucket');
  ->setPrefix('my-renders');
  ->setFilename('my-file');
  ->setAcl('public-read');

Methods:

Render Response Schemas

The following schemas are returned by the render request and status request.

QueuedResponse()

The response received after a render request is submitted. The render task is queued for rendering and a unique render id is returned.

Methods:

QueuedResponseData()

The QueuedResponseData is the response data returned with the QueuedResponse.

Methods:

RenderResponse()

The RenderResponse is the response received after a render status request is submitted. The response includes details about status of a render and the output URL.

Methods:

RenderResponseData()

The RenderResponseData is the response data returned with the RenderResponse request including status and URL.

Methods:

Template Response Schemas

The following schemas are returned by the templates endpoint, including create, update and rendering a template.

TemplateResponse()

The response received after a template is submitted. The template is saved and a unique template id is returned.

Methods:

TemplateResponseData()

The response data returned with the TemplateResponse.

Methods:

TemplateDataResponse()

The template data including the template name and Edit.

Methods:

TemplateDataResponseData()

The response data returned with the TemplateDataResponse.

Methods:

TemplateListResponse()

A list of previously saved templates.

Methods:

TemplateListResponseData()

The response data returned with the TemplateListResponse.

Methods:

TemplateListResponseItem()

The individual template item returned with the TemplateListResponseData templates list.

Methods:

Inspecting Media

The SDK probe endpoint can be used to inspect media hosted online. Simply pass the URL of an asset to inspect.

Probe Example

The example below inspects (probes) a video hosted on GitHub and returns metadata about the file.

use Shotstack\Client\Api\EditApi;
use Shotstack\Client\Configuration;

$config = Configuration::getDefaultConfiguration()
    ->setHost('https://api.shotstack.io/stage')
    ->setApiKey('x-api-key', 'H7jKyj90kd09lbLOF7J900jNbSWS67X87xs9j0cD'); // use the correct API key

$client = new EditApi(null, $config);

$url = 'https://github.com/shotstack/test-media/raw/main/captioning/scott-ko.mp4';

$response = $client->probe($url)->getResponse();

foreach ($response['metadata']->streams as $stream) {
    if ($stream->codec_type === 'video') {
        echo 'Example settings for: ' . $response['metadata']->format->filename, PHP_EOL, PHP_EOL;
        echo 'Width: ' . $stream->width . 'px', PHP_EOL;
        echo 'Height: ' . $stream->height . 'px', PHP_EOL;
        echo 'Framerate: ' . $stream->r_frame_rate . ' fps', PHP_EOL;
        echo 'Duration: ' . $stream->duration . ' secs', PHP_EOL;
    }
}

Probe Schemas

The following schemas are returned by the probe request.

ProbeResponse()

The ProbeResponse is the response returned after a probe request is submitted. The probe requests returns data from FFprobe formatted as JSON.

Methods:

Managing Assets

By default, all assets generated by the editing API are hosted by Shotstack and served via our CDN. The SDK provides access to the Serve API to retrieve information about hosted files. Files can also be deleted.

Assets by Render ID Example

The example below uses a render ID to look up hosted assets associated with the render. Note that multiple assets can be created for a render, i.e. video, thumb and poster. Each asset has a unique asset ID different to the render ID.

use Shotstack\Client\Api\ServeApi;
use Shotstack\Client\Configuration;

$config = Configuration::getDefaultConfiguration()
    ->setHost('https://api.shotstack.io/stage')
    ->setApiKey('x-api-key', 'H7jKyj90kd09lbLOF7J900jNbSWS67X87xs9j0cD'); // use the correct API key

$client = new ServeApi(null, $config);

$renderId = '140924c6-077d-4334-a89f-94befcfc0155'; // Use a valid render ID

$response = $client->getAssetByRenderId($renderId)->getData();

foreach ($response as $asset) {
    if ($asset->getAttributes()->getStatus() === 'ready') {
        echo "Status: " . strtoupper($asset->getAttributes()->getStatus()), PHP_EOL, PHP_EOL;
        echo ">> Asset CDN URL: " . $asset->getAttributes()->getUrl(), PHP_EOL, PHP_EOL;
        echo ">> Asset ID: " . $asset->getAttributes()->getId(), PHP_EOL, PHP_EOL;
        echo ">> Render ID: " . $asset->getAttributes()->getRenderId(), PHP_EOL, PHP_EOL;
    }
}

Assets by Asset ID Example

Every asset has a unique asset ID, the example below looks up an asset by its asset ID.

use Shotstack\Client\Api\ServeApi;
use Shotstack\Client\Configuration;

$config = Configuration::getDefaultConfiguration()
    ->setHost('https://api.shotstack.io/stage')
    ->setApiKey('x-api-key', 'H7jKyj90kd09lbLOF7J900jNbSWS67X87xs9j0cD'); // use the correct API key

$client = new ServeApi(null, $config);

$renderId = 'ed43eae3-4825-4c03-979d-f7dc47b9997c'; // Use a valid asset ID

$response = $client->getAsset($renderId)->getData();

foreach ($response as $asset) {
    if ($asset->getAttributes()->getStatus() === 'ready') {
        echo "Status: " . strtoupper($asset->getAttributes()->getStatus()), PHP_EOL, PHP_EOL;
        echo ">> Asset CDN URL: " . $asset->getAttributes()->getUrl(), PHP_EOL, PHP_EOL;
        echo ">> Asset ID: " . $asset->getAttributes()->getId(), PHP_EOL, PHP_EOL;
        echo ">> Render ID: " . $asset->getAttributes()->getRenderId(), PHP_EOL, PHP_EOL;
    }
}

Asset Schemas

The following schemas are returned by requests to the Serve API.

AssetResponse()

The AssetResponse is the response returned by the Serve API get asset request. Includes details of a hosted video, image, audio file, thumbnail or poster image. The response follows the json:api specification.

Methods:

AssetRenderResponse()

The AssetRenderResponse is the response returned by the Serve API get asset by render id request. The response is an array of asset resources, including video, image, audio, thumbnail and poster image. The response follows the json:api specification.

Methods:

AssetResponseData()

The AssetResponseData contains the type of resource (an asset) and attributes of the asset.

Methods:

AssetResponseAttributes()

The AssetResponseAttributes contains the list of asset attributes and their values.

Methods:

API Documentation and Guides