livestream
Go-live from a LiveKit room to MUX via RTMP egress — supports MUX, YouTube, Twitch, and custom RTMP destinations. Auto-archives to MUX VOD when stream ends. Use this skill when the user says "add livestream", "go live", "stream to mux", "rtmp stream", "broadcast", or "live streaming".
What this skill does
# Livestream (LiveKit Egress + MUX)
Livestreaming from a [LiveKit](https://livekit.io) room to external platforms via RTMP egress. Creates a MUX live stream, starts an RTMP egress from the LiveKit room to the MUX ingest URL, and auto-archives to a MUX VOD asset when the stream ends. Also supports custom RTMP destinations like YouTube Live and Twitch.
## Prerequisites
- Next.js app with `src/` directory and App Router
- `video-room` skill applied (provides `livekit-server-sdk`, LiveKit server configuration)
- `stream-mux` skill applied (provides `@mux/mux-node` client, MUX API credentials)
- `recording` skill applied (provides the `recordings` schema and Egress patterns)
- `env-config` skill applied (provides Zod env validation)
## Installation
No additional packages required. Uses `livekit-server-sdk` from the `video-room` skill and `@mux/mux-node` from the `stream-mux` skill.
## Environment Variables
Uses existing environment variables from dependencies:
```env
# LiveKit (from video-room)
LIVEKIT_API_KEY=your_api_key
LIVEKIT_API_SECRET=your_api_secret
NEXT_PUBLIC_LIVEKIT_URL=wss://your-project.livekit.cloud
# MUX (from stream-mux)
MUX_TOKEN_ID=your_mux_token_id
MUX_TOKEN_SECRET=your_mux_token_secret
```
Add to `src/env.ts` server schema (if not already present):
```typescript
MUX_TOKEN_ID: z.string().min(1),
MUX_TOKEN_SECRET: z.string().min(1),
```
## What Gets Created
```
src/
├── lib/
│ ├── video/
│ │ ├── livestream.ts # startLivestream, stopLivestream, getLivestreamStatus
│ │ └── stream-destinations.ts # StreamDestination type, RTMP URL helpers
│ └── db/
│ └── schema/
│ └── livestreams.ts # Drizzle schema: livestreams table
└── app/
└── api/
└── video/
└── livestream/
├── route.ts # POST go live, DELETE stop stream
└── status/
└── route.ts # GET current stream status + viewer count
```
## Setup Steps
### Step 1: Create `src/lib/video/stream-destinations.ts`
```typescript
export type StreamDestinationType = "mux" | "youtube" | "twitch" | "custom";
export type StreamDestination = {
type: StreamDestinationType;
name: string;
rtmpUrl: string;
streamKey: string;
};
/**
* Constructs the full RTMP URL for a MUX live stream.
* MUX RTMP ingest endpoint: rtmp://global-live.mux.com:5222/app/{stream_key}
*/
export function buildMuxRtmpUrl(streamKey: string): string {
return `rtmp://global-live.mux.com:5222/app/${streamKey}`;
}
/**
* Constructs the full RTMP URL for YouTube Live.
* YouTube RTMP ingest: rtmp://a.rtmp.youtube.com/live2/{stream_key}
*/
export function buildYouTubeRtmpUrl(streamKey: string): string {
return `rtmp://a.rtmp.youtube.com/live2/${streamKey}`;
}
/**
* Constructs the full RTMP URL for Twitch.
* Twitch RTMP ingest: rtmp://live.twitch.tv/app/{stream_key}
* Use the nearest ingest server for lower latency.
*/
export function buildTwitchRtmpUrl(
streamKey: string,
ingestServer?: string
): string {
const server = ingestServer ?? "live.twitch.tv";
return `rtmp://${server}/app/${streamKey}`;
}
/**
* Builds a StreamDestination from a destination type and stream key.
*/
export function buildDestination(
type: StreamDestinationType,
streamKey: string,
options?: { name?: string; customRtmpUrl?: string; twitchIngestServer?: string }
): StreamDestination {
const name = options?.name ?? type;
switch (type) {
case "mux":
return {
type,
name,
rtmpUrl: buildMuxRtmpUrl(streamKey),
streamKey,
};
case "youtube":
return {
type,
name,
rtmpUrl: buildYouTubeRtmpUrl(streamKey),
streamKey,
};
case "twitch":
return {
type,
name,
rtmpUrl: buildTwitchRtmpUrl(streamKey, options?.twitchIngestServer),
streamKey,
};
case "custom":
if (!options?.customRtmpUrl) {
throw new Error("customRtmpUrl is required for custom destinations");
}
return {
type,
name,
rtmpUrl: `${options.customRtmpUrl}/${streamKey}`,
streamKey,
};
}
}
/**
* Constructs the full RTMP URL with stream key appended, ready for LiveKit egress.
* LiveKit expects the full URL including the stream key.
*/
export function getFullRtmpUrl(destination: StreamDestination): string {
// For MUX, the rtmpUrl already includes the stream key in the path
return destination.rtmpUrl;
}
/**
* Gets a MUX HLS playback URL from a playback ID.
*/
export function getMuxPlaybackUrl(playbackId: string): string {
return `https://stream.mux.com/${playbackId}.m3u8`;
}
/**
* Gets a MUX thumbnail URL from a playback ID.
*/
export function getMuxThumbnailUrl(
playbackId: string,
options?: { width?: number; height?: number; time?: number }
): string {
const params = new URLSearchParams();
if (options?.width) params.set("width", String(options.width));
if (options?.height) params.set("height", String(options.height));
if (options?.time) params.set("time", String(options.time));
const queryString = params.toString();
return `https://image.mux.com/${playbackId}/thumbnail.jpg${queryString ? `?${queryString}` : ""}`;
}
```
### Step 2: Create `src/lib/db/schema/livestreams.ts`
```typescript
import {
pgTable,
text,
timestamp,
uuid,
} from "drizzle-orm/pg-core";
export const livestreams = pgTable("livestreams", {
id: uuid("id").primaryKey().defaultRandom(),
roomName: text("room_name").notNull(),
egressId: text("egress_id"),
muxLiveStreamId: text("mux_live_stream_id"),
muxPlaybackId: text("mux_playback_id"),
muxStreamKey: text("mux_stream_key"),
rtmpUrl: text("rtmp_url"),
status: text("status", {
enum: ["idle", "starting", "active", "stopping", "completed", "failed"],
})
.notNull()
.default("idle"),
muxAssetId: text("mux_asset_id"),
startedAt: timestamp("started_at", { withTimezone: true }),
endedAt: timestamp("ended_at", { withTimezone: true }),
userId: text("user_id").notNull(),
createdAt: timestamp("created_at", { withTimezone: true })
.notNull()
.defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true })
.notNull()
.defaultNow(),
});
export type Livestream = typeof livestreams.$inferSelect;
export type NewLivestream = typeof livestreams.$inferInsert;
```
### Step 3: Add export to `src/lib/db/schema/index.ts`
```typescript
export * from "./livestreams";
```
### Step 4: Create `src/lib/video/livestream.ts`
```typescript
import { EgressClient, EncodingOptions, StreamOutput, StreamProtocol } from "livekit-server-sdk";
import Mux from "@mux/mux-node";
import { db } from "@/lib/db";
import { livestreams, type Livestream } from "@/lib/db/schema";
import { eq, and, desc } from "drizzle-orm";
import {
buildMuxRtmpUrl,
getMuxPlaybackUrl,
getFullRtmpUrl,
} from "./stream-destinations";
import type { StreamDestination } from "./stream-destinations";
type MuxLiveStream = {
id: string;
stream_key: string;
playback_ids?: Array<{ id: string; policy: string }>;
status: string;
};
type MuxAsset = {
id: string;
playback_ids?: Array<{ id: string; policy: string }>;
status: string;
duration?: number;
};
function getEgressClient(): EgressClient {
const livekitUrl = process.env.NEXT_PUBLIC_LIVEKIT_URL;
const apiKey = process.env.LIVEKIT_API_KEY;
const apiSecret = process.env.LIVEKIT_API_SECRET;
if (!livekitUrl || !apiKey || !apiSecret) {
throw new Error(
"Missing NEXT_PUBLIC_LIVEKIT_URL, LIVEKIT_API_KEY, or LIVEKIT_API_SECRET"
);
}
// Convert wss:// to https:// for REST API
const httpUrl = livekitUrl
.replace("wss://", "https://")
.replace("ws://", "http://");
return new EgressClient(httpUrl, apiKey, apiSecret);
}
function getMuxClient(): Mux {
const tokenId = process.env.MUX_TOKEN_ID;
const tokenSecret = process.env.MUX_TOKEN_SECRET;
if (!tokenId || !tokenSRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.