Pure Code Video Generation: A Technical Practice for Stunning Short Videos
This article explains how to generate a visually striking 30–60 second short video using only code, with no external images, video, audio assets, or generative media APIs. It covers writing verifiable constraints, designing visual concepts and narrative pacing, core techniques such as SDF fractals, gravitational lensing, instanced particles with curl noise, anti-flicker bloom and tone mapping, and procedural audio synchronization. It also details project structure, reproducibility checklists, performance budgets with fallback strategies, acceptance criteria, and deployment suggestions on Baidu AI Cloud.
1. Why Pure Code Video Generation Is Worth Doing
A common discussion in developer communities is whether you can produce a “stunning” short video using only code, without any external image, video, or audio assets and without calling generative media APIs. The value of this exercise is not showing off. It forces developers to connect graphics, numerical computing, audio synthesis, and engineering delivery into a complete pipeline.
Traditional short video production relies on asset libraries and editing tools, so the creative bottleneck is usually “finding assets.” The pure code approach moves the bottleneck earlier, to “designing algorithms and scheduling rendering.” As a result, it demands the following capabilities:
- Mathematical modeling: describing visual elements with functions, fields, iteration, and geometry;
- Rendering pipeline knowledge: the order and cost of rasterization, ray marching, and post-processing;
- Numerical stability: time steps, floating-point error, and reproducibility of random seeds;
- Engineering delivery: dependency locking, command-based builds, frame sequence naming, and encoding.
For teams, the direct benefits are that visual assets become versionable, parameterizable, and batch-renderable on container platforms. This suits use cases such as data visualization intros, product launch backgrounds, and dynamic backdrops for monitoring dashboards.
2. Turning Requirements into Executable Constraints: A Prompt Template
To get stable output from a model or an engineer, requirements must be verifiable. Below is a general prompt skeleton that can be tailored to a project:
Role: Creative technical director + graphics programmerGoal: Generate a 30–60 second, 1920×1080, 30fps short video using code onlyHard constraints:1. No external image/video/audio assets and no generative media APIs2. Visuals produced by mathematical functions, particle systems, shaders, procedural textures, and procedural audio synthesis3. Deliver a reproducible project: source code, dependency notes, run commands, and render/export commands4. Actually output a frame sequence or video file, and explain how to encode it as MP4/GIF5. For browser solutions, provide a single-page entry and offline operation; for local rendering, provide the environment and commands6. No pseudocode; if length is limited, prioritize runnable core visualsWork requirements: a clear visual concept and narrative rhythm; at least one complex technique; a complete narrative arc; a performance budget and fallback planDelivery format: A concept B technical approach and difficulties C file structure D run commands E output naming rules F self-assessment
The key is to translate “stunning” into measurable criteria: whether the frame rate is stable, whether flicker exists, whether colors stay within the target gamut, whether audio and visuals are aligned, and whether results are reproducible across machines.
3. Visual Concept and Narrative Pacing
The most common failure in pure code work is “effects without narrative.” A four-part structure is recommended, with each part lasting 8–15 seconds:
- Opening: low saturation and sparse composition, with a single geometric motif establishing the visual grammar;
- Development: the motif begins to replicate and deform, fields and particles are introduced, and the pace accelerates;
- Turn: a clear visual event (such as the appearance of a gravity source, a color inversion, or a camera fly-through) creates a memorable moment;
- Resolution: energy converges, the composition returns to minimalism, colors return to the main palette, and the audio tail is left to ring out.
For camera design, a parameterized camera path (spline interpolation plus easing functions) can replace manual keyframes, keeping motion continuous and reproducible:
def ease_in_out(t): # Smooth easing to avoid abrupt camera starts and stopsreturn t * t * (3 - 2 * t)def camera_path(t, keyframes):# keyframes: [(time, (x,y,z)), ...], linear interpolation with easingfor i in range(len(keyframes) - 1):t0, p0 = keyframes[i]t1, p1 = keyframes[i + 1]if t0 <= t <= t1:k = ease_in_out((t - t0) / (t1 - t0))return tuple(a + (b - a) * k for a, b in zip(p0, p1))return keyframes[-1][1]
4. Core Techniques: Mapping Fancy Terms to General Principles
The list of terms in the original text is essentially a set of mature, general techniques combined in an uncommon way.
1. Hybrid Fractals and Signed Distance Fields (SDF)
A fractal is a complex form produced by repeatedly iterating simple rules. An SDF returns the distance from a point to a surface, making smooth boolean operations and blending easier. Combining the two can procedurally generate mountains, clouds, and organic textures. Complexity mainly comes from the number of iterations and intersection steps, so set a maximum step count and an escape threshold to prevent infinite loops.
2. Gravitational Lensing and Accretion Disk Visuals
This is a visual approximation of general relativity: light bends near a massive body, stretching the background into a ring. In engineering, this is usually done by integrating ray marching through curved spacetime or applying a radial distortion mapping to the background. The accretion disk can be simulated with a rotating noise field plus a Doppler-like brightness shift (one side brighter and bluer). The difficulty lies in controlling the numerical integration step size and dispersion.
3. Large-Scale Instanced Particles and Curl Fields
“Thousands of particles” means using instanced rendering to draw many geometries in one pass, leveraging GPU parallelism. A curl field (curl noise) is a divergence-free velocity field derived from the curl of a noise field. Particles move along it, looking like fluid without solving Navier–Stokes, which is cost-effective. Engineering priorities are fixing the seed, avoiding alias reads and writes on buffers, and not rebuilding buffers every frame.
4. Anti-Flicker Bloom and Tone Mapping
Bright areas are blurred at multiple downsampling levels and then added back to create bloom. If brightness fluctuates over time, stabilization is needed (limiting the rate of change and using a fixed sampling pattern). Tone mapping maps high-dynamic-range linear light into the display range. A common industry approach is to use a curve widely adopted in the film industry to avoid highlight clipping and color banding.
5. Procedural Audio and Audio-Visual Synchronization
Oscillators, noise, and envelopes can synthesize drums, pads, and sound effects, generating samples one by one at a sample rate such as 48kHz. The key to synchronization is a “shared timeline”: visual events and audio events use the same beat sheet, and rendering pulls the audio window by frame number to avoid cumulative drift.
5. Engineering Structure and Reproducible Delivery
The following directory structure works for both browser and local rendering:
project/index.html # Single-page entry (works offline)src/main.js # Main loop and scene assemblysrc/shaders/ # Vertex/fragment shaderssrc/audio.js # Procedural audio synthesissrc/timeline.js # Beats and camera keyframespackage.json # Dependencies and scripts (locked versions)scripts/render.sh # Render frame sequencescripts/encode.sh # Encode to MP4/GIFout/frames/ # Frame sequence: frame_00000.png ...out/video.mp4
Reproducibility checklist:
- Lock dependency versions and commit the lock file;
- Fix random seeds and sampling patterns;
- Name frame sequences with zero padding for ordered encoding;
- Provide a one-click script: install dependencies → render → encode;
- Freeze the environment on a container platform to avoid local differences.
For encoding, common command-line media tools are sufficient. For example, combine a frame sequence into a video at a fixed frame rate, or generate a palette and then output a GIF. Adjust specific parameters for target platform compatibility.
6. Performance Budget and Fallback Plan
Set the budget before writing effects. At 1080p/30fps, the per-frame budget is about 33ms. A suggested split is 8ms for geometry and particles, 12ms for ray marching/materials, 6ms for post-processing, 3ms for audio and scheduling, and 4ms of headroom.
Execute fallback strategies in priority order:
- Reduce ray marching steps and the fractal iteration limit;
- Halve the particle count and switch to cheaper noise;
- Reduce bloom levels and switch to a low-cost tone mapping curve;
- Lower render resolution to 720p and upscale;
- Disable the most expensive effects in the “turn” section while keeping the narrative intact.
Also set up monitoring: log per-frame time, GPU memory usage, and dropped frame rate to a logging service and monitoring alerts, making it easier to locate slow nodes during batch rendering.
7. Acceptance and Self-Assessment Criteria
Use the same yardstick for delivery to avoid subjective disputes:
- Pure code: zero external assets and zero generative APIs;
- Reproducibility: the same frame and image on a different machine;
- Visual impact: whether composition, color, and rhythm create a memorable moment;
- Technical complexity: at least one high-cost technique used stably;
- Engineering quality: structure, scripts, and dependencies meet standards;
- Performance stability: the frame budget is met and a fallback path exists.
8. Deployment Suggestions on Baidu AI Cloud
To productize this kind of rendering pipeline, you can combine general cloud capabilities: object storage for source code and frame sequences, a container platform for stateless rendering tasks with elastic scaling, a message queue for task distribution, and logging and monitoring services to track rendering success rate and duration. Baidu AI Cloud provides these general capability categories and can serve as the infrastructure foundation for batch rendering and asset versioning.
In summary, generating stunning videos with pure code is not magic. It is systems engineering that combines mathematical modeling, the rendering pipeline, audio synthesis, and engineering delivery. Write the constraints clearly, define the budget precisely, and prepare the fallback path, and you can reliably produce reproducible, high-quality work.
