Record meetings with LiveKit Egress instead of browser capture.
Deploy Ladill Meet / deploy (push) Successful in 52s

Server-side room composite egress replaces fragile MediaRecorder DOM capture when enabled, with webhook completion and browser fallback when egress is unavailable.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
isaacclad
2026-07-04 03:18:28 +00:00
co-authored by Cursor
parent c2cb9cf33a
commit 4e4bed0df3
10 changed files with 674 additions and 10 deletions
@@ -0,0 +1,57 @@
<?php
namespace App\Http\Controllers\Api;
use Agence104\LiveKit\WebhookReceiver;
use App\Http\Controllers\Controller;
use App\Models\Recording;
use App\Services\Meet\RecordingService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class LiveKitWebhookController extends Controller
{
public function __invoke(Request $request, RecordingService $recordings): JsonResponse
{
try {
$receiver = new WebhookReceiver(
(string) config('meet.media.livekit.api_key'),
(string) config('meet.media.livekit.api_secret'),
);
$event = $receiver->receive(
$request->getContent(),
$request->header('Authorization'),
);
} catch (\Throwable $e) {
Log::warning('LiveKit webhook rejected.', ['error' => $e->getMessage()]);
return response()->json(['error' => 'invalid webhook'], 401);
}
if ($event->getEvent() !== 'egress_ended' || ! $event->hasEgressInfo()) {
return response()->json(['status' => 'ignored']);
}
$info = $event->getEgressInfo();
$egressId = $info->getEgressId();
if ($egressId === '') {
return response()->json(['status' => 'ignored']);
}
$recording = Recording::query()
->whereIn('status', ['recording', 'processing'])
->where('metadata->egress_id', $egressId)
->first();
if (! $recording) {
return response()->json(['status' => 'not_found']);
}
$recordings->completeFromEgress($recording, $info);
return response()->json(['status' => 'accepted']);
}
}
@@ -9,6 +9,7 @@ use App\Models\Room;
use App\Models\Session;
use App\Services\Meet\BreakoutService;
use App\Services\Meet\ChatService;
use App\Services\Meet\Media\LiveKitEgressService;
use App\Services\Meet\Media\MediaProviderInterface;
use App\Services\Meet\ParticipantPresenter;
use App\Services\Meet\RecordingService;
@@ -94,6 +95,7 @@ class MeetingRoomController extends Controller
'mediaConfigured' => $this->media->isConfigured(),
'messages' => $this->chat->recentMessages($session),
'activeRecording' => $session->recordings()->where('status', 'recording')->first(),
'serverEgressAvailable' => app(LiveKitEgressService::class)->isAvailable(),
'watermark' => $room->organization?->securitySetting('watermark_enabled', false),
'isWebinar' => $room->isWebinar() || $room->isConference(),
'isConference' => $room->isConference(),
@@ -514,7 +516,11 @@ class MeetingRoomController extends Controller
$recording = $this->recordings->start($session, $host);
return response()->json(['recording_uuid' => $recording->uuid, 'status' => $recording->status]);
return response()->json([
'recording_uuid' => $recording->uuid,
'status' => $recording->status,
'capture_mode' => $this->recordings->captureMode($recording),
]);
}
public function stopRecording(Request $request, Session $session): JsonResponse
@@ -542,6 +548,7 @@ class MeetingRoomController extends Controller
return response()->json([
'status' => 'processing',
'recording_uuid' => $recording->uuid,
'capture_mode' => $this->recordings->captureMode($recording),
]);
}
@@ -0,0 +1,174 @@
<?php
namespace App\Services\Meet\Media;
use Agence104\LiveKit\EgressServiceClient;
use App\Models\Recording;
use App\Models\Session;
use Illuminate\Support\Facades\Log;
use Livekit\EncodedFileOutput;
use Livekit\EncodedFileType;
use Livekit\EncodingOptionsPreset;
use Livekit\EgressInfo;
use Livekit\S3Upload;
use RuntimeException;
class LiveKitEgressService
{
public function isAvailable(): bool
{
if (! (bool) config('meet.recordings.egress.enabled', false)) {
return false;
}
return app(LiveKitProvider::class)->isConfigured();
}
public function apiHost(): string
{
$override = (string) config('meet.media.livekit.api_url', '');
if ($override !== '') {
return rtrim($override, '/');
}
$url = (string) config('meet.media.livekit.url', '');
return (string) preg_replace('#^wss:#', 'https:', (string) preg_replace('#^ws:#', 'http:', $url));
}
public function startRoomRecording(Session $session, Recording $recording, bool $audioOnly = false): EgressInfo
{
$client = $this->client();
$layout = $this->egressLayout($recording->layout);
$output = $this->buildFileOutput($session, $recording);
$preset = EncodingOptionsPreset::H264_720P_30;
return $client->startRoomCompositeEgress(
$session->media_room_name,
$layout,
$output,
$preset,
$audioOnly,
);
}
public function stopEgress(string $egressId): EgressInfo
{
return $this->client()->stopEgress($egressId);
}
protected function client(): EgressServiceClient
{
return new EgressServiceClient(
$this->apiHost(),
(string) config('meet.media.livekit.api_key'),
(string) config('meet.media.livekit.api_secret'),
);
}
protected function buildFileOutput(Session $session, Recording $recording): EncodedFileOutput
{
$filepath = sprintf(
'recordings/%s/%s.mp4',
$session->uuid,
$recording->uuid,
);
$output = new EncodedFileOutput([
'file_type' => EncodedFileType::MP4,
'filepath' => $filepath,
]);
$s3 = $this->s3UploadConfig();
if ($s3 !== null) {
$output->setS3(new S3Upload($s3));
}
return $output;
}
/**
* @return array<string, string>|null
*/
protected function s3UploadConfig(): ?array
{
$egress = config('meet.recordings.egress.s3', []);
$bucket = (string) ($egress['bucket'] ?? '');
if ($bucket === '') {
return null;
}
$config = [
'bucket' => $bucket,
'region' => (string) ($egress['region'] ?? 'us-east-1'),
];
foreach (['access_key', 'secret', 'session_token', 'endpoint', 'assume_role_arn', 'assume_role_external_id'] as $key) {
$value = (string) ($egress[$key] ?? '');
if ($value !== '') {
$config[$key] = $value;
}
}
return $config;
}
protected function egressLayout(?string $layout): string
{
return match ($layout) {
'speaker', 'screen' => 'speaker',
default => 'grid',
};
}
public function tryStart(Session $session, Recording $recording): ?array
{
if (! $this->isAvailable()) {
return null;
}
try {
$audioOnly = $session->room->isAudioOnly();
$info = $this->startRoomRecording($session, $recording, $audioOnly);
$egressId = $info->getEgressId();
if ($egressId === '') {
throw new RuntimeException('LiveKit egress did not return an egress id.');
}
$filepath = sprintf('recordings/%s/%s.mp4', $session->uuid, $recording->uuid);
return [
'egress_id' => $egressId,
'egress_filepath' => $filepath,
'capture_mode' => 'egress',
'audio_only' => $audioOnly,
];
} catch (\Throwable $e) {
Log::warning('LiveKit egress start failed; falling back to browser capture.', [
'session_uuid' => $session->uuid,
'recording_uuid' => $recording->uuid,
'error' => $e->getMessage(),
]);
return null;
}
}
public function tryStop(?string $egressId): void
{
if (! filled($egressId)) {
return;
}
try {
$this->stopEgress($egressId);
} catch (\Throwable $e) {
Log::warning('LiveKit egress stop failed.', [
'egress_id' => $egressId,
'error' => $e->getMessage(),
]);
}
}
}
+133 -8
View File
@@ -5,12 +5,20 @@ namespace App\Services\Meet;
use App\Models\Recording;
use App\Models\Session;
use App\Models\User;
use App\Services\Meet\Media\LiveKitEgressService;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Livekit\EgressInfo;
use Livekit\EgressStatus;
use Livekit\FileInfo;
use RuntimeException;
class RecordingService
{
public function __construct(
protected LiveKitEgressService $egress,
) {}
public function start(Session $session, User $host, string $layout = 'gallery'): Recording
{
$active = $session->recordings()->where('status', 'recording')->first();
@@ -27,6 +35,15 @@ class RecordingService
'started_at' => now(),
]);
$egressMeta = $this->egress->tryStart($session, $recording);
if ($egressMeta !== null) {
$recording->update(['metadata' => $egressMeta]);
$recording = $recording->fresh();
} else {
$recording->update(['metadata' => ['capture_mode' => 'browser']]);
$recording = $recording->fresh();
}
AuditLogger::record(
$session->owner_ref,
'recording.started',
@@ -39,12 +56,26 @@ class RecordingService
return $recording;
}
public function captureMode(Recording $recording): string
{
return (string) ($recording->metadata['capture_mode'] ?? 'browser');
}
public function usesServerEgress(Recording $recording): bool
{
return $this->captureMode($recording) === 'egress';
}
public function stop(Recording $recording, string $actorRef): Recording
{
if ($recording->status !== 'recording') {
return $recording;
}
if ($this->usesServerEgress($recording)) {
$this->egress->tryStop($recording->metadata['egress_id'] ?? null);
}
$recording->update([
'status' => 'processing',
'ended_at' => now(),
@@ -65,6 +96,73 @@ class RecordingService
return $recording->fresh();
}
public function completeFromEgress(Recording $recording, EgressInfo $info): Recording
{
if (! in_array($recording->status, ['recording', 'processing'], true)) {
return $recording;
}
$status = $info->getStatus();
if (in_array($status, [EgressStatus::EGRESS_FAILED, EgressStatus::EGRESS_ABORTED, EgressStatus::EGRESS_LIMIT_REACHED], true)) {
return $this->fail(
$recording,
filled($info->getError()) ? $info->getError() : 'LiveKit recording failed.',
);
}
if ($status !== EgressStatus::EGRESS_COMPLETE) {
return $recording;
}
$file = $this->firstEgressFile($info);
if ($file === null) {
return $this->fail($recording, 'LiveKit recording finished without a file.');
}
$storagePath = (string) ($recording->metadata['egress_filepath'] ?? $file->getFilename());
$size = (int) $file->getSize();
if ($size <= 0) {
return $this->fail($recording, 'LiveKit recording file is empty.');
}
$durationSeconds = $this->durationSecondsFromFile($file, $recording);
$recording->update([
'status' => 'ready',
'storage_path' => $storagePath,
'file_size' => $size,
'ended_at' => $recording->ended_at ?? now(),
'duration_seconds' => $durationSeconds,
'metadata' => array_merge($recording->metadata ?? [], [
'egress_location' => $file->getLocation(),
]),
]);
$recording = $recording->fresh();
$session = $recording->session;
AuditLogger::record(
$recording->owner_ref,
'recording.ready',
$session->room->organization_id,
null,
Recording::class,
$recording->id,
);
app(MeetNotificationService::class)->recordingReady($recording);
app(\App\Services\Integrations\WebhookDispatcher::class)->recordingReady($recording);
app(MeetBillingService::class)->chargeRecordingStorageInitial($recording);
if ($session->room->setting('auto_ai_summary', false) || config('meet.ai.auto_summarize', true)) {
app(TranscriptService::class)->ensureForSession($session, $recording);
}
return $recording->fresh();
}
/** Store a browser-captured recording on Ladill storage (not LiveKit). */
public function storeUpload(Recording $recording, UploadedFile $file): Recording
{
@@ -160,10 +258,11 @@ class RecordingService
$staleAt = $recording->ended_at ?? $recording->updated_at;
if ($staleAt && $staleAt->lt(now()->subMinutes($timeoutMinutes))) {
return $this->fail(
$recording,
'Recording upload did not complete. Keep the host browser open briefly after ending the meeting so the file can upload.',
);
$reason = $this->usesServerEgress($recording)
? 'LiveKit did not finish processing the recording. Check your egress service and storage configuration.'
: 'Recording upload did not complete. Keep the host browser open briefly after ending the meeting so the file can upload.';
return $this->fail($recording, $reason);
}
return $recording;
@@ -185,10 +284,11 @@ class RecordingService
})
->orderBy('id')
->each(function (Recording $recording) use (&$failed) {
$this->fail(
$recording,
'Recording upload did not complete. Keep the host browser open briefly after ending the meeting so the file can upload.',
);
$reason = $this->usesServerEgress($recording)
? 'LiveKit did not finish processing the recording. Check your egress service and storage configuration.'
: 'Recording upload did not complete. Keep the host browser open briefly after ending the meeting so the file can upload.';
$this->fail($recording, $reason);
$failed++;
});
@@ -244,4 +344,29 @@ class RecordingService
$recording->delete();
}
protected function firstEgressFile(EgressInfo $info): ?FileInfo
{
foreach ($info->getFileResults() as $file) {
if ($file instanceof FileInfo) {
return $file;
}
}
return null;
}
protected function durationSecondsFromFile(FileInfo $file, Recording $recording): ?int
{
$duration = (int) $file->getDuration();
if ($duration <= 0) {
return $recording->duration_seconds;
}
if ($duration > 86_400) {
return (int) round($duration / 1_000_000_000);
}
return $duration;
}
}