Video clip
Download a video you are allowed to download with yt-dlp in the session's shell, and cut its first 30 seconds with ffmpeg. Only the first part is fetched. If the site refuses the download, the example stops: it never disguises the downloader.
When to use it: You work with video you may download: clips, conversions or previews.
| Uses | a shell-only session, exec (pip, yt-dlp, ffmpeg, ffprobe), files.read |
|---|---|
| Needs | a plan with shell sessions; no model |
| Site | archive.org: Big Buck Bunny (Blender Foundation, CC BY 3.0). Only videos you own, have the rights to, or that have an open licence |
| Output | output/clip.mp4 and output/result.json |
| Languages | Node and Python |
The code
The example as it is in its folder. Both versions do the same job and write the same output/, so one result check covers both.
/** * Video clip: download a video you are allowed to download with yt-dlp in the session's shell, and cut its first 30 * seconds with ffmpeg. The default is Big Buck Bunny (Blender Foundation, CC BY 3.0) from archive.org. * * npx tsx node/index.ts (BOXLINE_API_KEY; VIDEO_URL, CLIP_SECONDS; a plan with shell sessions) * * Only for videos you own, have the rights to, or that have an open licence. If the site refuses the download, the * example stops: it never disguises the downloader. Writes output/clip.mp4 and output/result.json. */import { mkdirSync, writeFileSync } from "node:fs";import { join } from "node:path";import { Boxline } from "@boxline/sdk";const out = process.env.OUTPUT_DIR ?? "output";const video = process.env.VIDEO_URL ?? "https://archive.org/download/BigBuckBunny_328/BigBuckBunny_512kb.mp4";const seconds = Number(process.env.CLIP_SECONDS ?? 30);const bx = new Boxline();const session = await bx.sessions.create({ browser: false, shell: true, timeout: 900, userMetadata: { example: "video-clip" } });console.log(`Session: ${session.id}`);try { const sh = async (command: string, timeoutMs = 300_000) => { const r = await session.exec(command, { env: { VIDEO_URL: video }, timeoutMs }); if (r.exitCode !== 0) throw new Error(`${command.split(" ")[0]} failed: ${(r.stderr || r.stdout).trim().split("\n").slice(-3).join(" | ")}`); return r.stdout.trim(); }; await sh("pip install --quiet --disable-pip-version-check yt-dlp"); // Only the first part is fetched (yt-dlp hands the range to ffmpeg), not the whole film. await sh(`mkdir -p downloads output && yt-dlp --quiet --no-progress --no-playlist --download-sections "*0-${seconds + 5}" -o "downloads/video.%(ext)s" "$VIDEO_URL"`, 600_000); const source = await sh("ls downloads/video.* | head -1"); console.log(`Downloaded ${source}`); await sh(`ffmpeg -loglevel error -y -i "${source}" -t ${seconds} -c:v libx264 -preset veryfast -c:a aac -movflags +faststart output/clip.mp4`, 600_000); const duration = Number(await sh("ffprobe -v error -show_entries format=duration -of csv=p=0 output/clip.mp4")); const clip = await session.files.read("output/clip.mp4"); mkdirSync(out, { recursive: true }); writeFileSync(join(out, "clip.mp4"), clip); console.log(`output/clip.mp4: ${duration.toFixed(1)} s, ${Math.round(clip.length / 1024)} KB`); writeFileSync(join(out, "result.json"), JSON.stringify({ video, seconds, source, duration, bytes: clip.length }, null, 2));} finally { await session.stop();}"""Video clip: download a video you are allowed to download with yt-dlp in the session's shell, and cut its first 30seconds with ffmpeg. The default is Big Buck Bunny (Blender Foundation, CC BY 3.0) from archive.org. python python/main.py (BOXLINE_API_KEY; VIDEO_URL, CLIP_SECONDS; a plan with shell sessions)Only for videos you own, have the rights to, or that have an open licence. If the site refuses the download, theexample stops: it never disguises the downloader. Writes output/clip.mp4 and output/result.json."""import jsonimport osfrom pathlib import Pathfrom boxline import Boxlineout = Path(os.environ.get("OUTPUT_DIR", "output"))video = os.environ.get("VIDEO_URL", "https://archive.org/download/BigBuckBunny_328/BigBuckBunny_512kb.mp4")seconds = int(os.environ.get("CLIP_SECONDS", "30"))bx = Boxline()with bx.sessions.create(browser=False, shell=True, timeout=900, user_metadata={"example": "video-clip"}) as session: print(f"Session: {session.id}", flush=True) def sh(command: str, timeout_ms: int = 300_000) -> str: r = session.exec(command, env={"VIDEO_URL": video}, timeout_ms=timeout_ms) if r["exitCode"] != 0: tail = " | ".join((r["stderr"] or r["stdout"]).strip().split("\n")[-3:]) raise SystemExit(f"{command.split(' ')[0]} failed: {tail}") return r["stdout"].strip() sh("pip install --quiet --disable-pip-version-check yt-dlp") # Only the first part is fetched (yt-dlp hands the range to ffmpeg), not the whole film. sh(f'mkdir -p downloads output && yt-dlp --quiet --no-progress --no-playlist --download-sections "*0-{seconds + 5}" -o "downloads/video.%(ext)s" "$VIDEO_URL"', 600_000) source = sh("ls downloads/video.* | head -1") print(f"Downloaded {source}") sh(f'ffmpeg -loglevel error -y -i "{source}" -t {seconds} -c:v libx264 -preset veryfast -c:a aac -movflags +faststart output/clip.mp4', 600_000) duration = float(sh("ffprobe -v error -show_entries format=duration -of csv=p=0 output/clip.mp4")) clip = session.files.read("output/clip.mp4") out.mkdir(parents=True, exist_ok=True) (out / "clip.mp4").write_bytes(clip) print(f"output/clip.mp4: {duration:.1f} s, {len(clip) // 1024} KB") (out / "result.json").write_text(json.dumps({"video": video, "seconds": seconds, "source": source, "duration": duration, "bytes": len(clip)}, indent=2))Inputs
Environment variables the example reads:
VIDEO_URL: the video (defaulthttps://archive.org/download/BigBuckBunny_328/BigBuckBunny_512kb.mp4).CLIP_SECONDS: the clip's length (default30).
Run it
Get the examples with git clone https://github.com/Boxline-dev/examples.git and open this one: cd examples/video-clip. Put your API key in BOXLINE_API_KEY (and BOXLINE_API_URL for another API), then run either version from the example’s folder. Both write to output/ and stop their sessions when they finish.
# Node 18 or newer, in the example's folderexport BOXLINE_API_KEY=… # your API keynpm install @boxline/sdk tsxnpx tsx node/index.ts# Python 3.9 or newer, in the example's folderexport BOXLINE_API_KEY=… # your API keypip install boxline-sdkpython python/main.pyThen check the result, from the same folder: npx tsx check.ts output. It exits with 0 only when the result is right.
What its check proves
check.ts reads what the example wrote and passes only when the result is right, not merely when the example ran.
Clip.mp4 lasts about 30 s by its own MP4 header, and ffprobe in the session agrees.
Source
github.com/Boxline-dev/examples/video-clip on GitHub, with its README.md, check.ts and .env.example. The examples are open source. See all examples.
These docs describe a beta API. Endpoints, fields and SDK methods may change before general availability; breaking changes will be listed in the changelog.