implement basic video streaming pipeline

This commit is contained in:
buenosairesam
2025-08-25 03:58:29 -03:00
parent 05224c712b
commit c21cc32727
36 changed files with 1266 additions and 354 deletions

6
.gitignore vendored
View File

@@ -1,3 +1,7 @@
venv
node_modules
__pycache__
__pycache__
*.sublime-*
def/ignore
postgres_data
media

View File

@@ -1,6 +1,12 @@
Real-Time Video Analysis Platform
Project Overview
A scalable real-time video streaming and AI analysis platform that demonstrates modern cloud-native architecture and machine learning integration. The system ingests RTMP video streams (from sources like OBS), processes them with computer vision AI models, and provides live analysis results through a responsive web dashboard.
A scalable real-time video streaming and AI analysis platform
that demonstrates modern cloud-native architecture and machine learning integration.
The system ingests RTMP video streams (from sources like OBS),
processes them with computer vision AI models,
and provides live analysis results through a responsive web dashboard.
Core Functionality
Video Ingestion: Accept RTMP streams and convert to HLS for web playback
@@ -324,4 +330,80 @@ Slice 4: GCP Integration
Cloud Storage for segments
GKE deployment
Monitoring integration
Monitoring integration
considerations for deployment / testing
does this planning take into consideration running it on a local kubernetes cluster? I use kind and tilt for running tough a prefer not to depend on it for developing just test the orchestration?
The current planning assumes traditional development (Django dev server + Angular dev server) with K8s only for testing orchestration. This is actually perfect for your workflow! Let me clarify the development vs testing approach:
## **Development Mode (Local Servers)**
```bash
# Backend development
cd backend
python manage.py runserver 8000
# Frontend development
cd frontend
ng serve --port 4200
# Supporting services (via Docker Compose)
docker-compose up redis postgres
```
**Benefits:**
- Hot reload for both Django and Angular
- Easy debugging with IDE integration
- Fast iteration cycles
- No K8s complexity during development
## **Testing Mode (KIND + K8s)**
```bash
# Build and deploy to KIND cluster
kind create cluster --name media-analyzer
kubectl apply -k k8s/overlays/development
```
**For orchestration testing only:**
- Container builds and registry
- Service discovery and networking
- Volume mounts and persistence
- Resource limits and scaling
- Inter-service communication
## **Suggested Development Workflow**## **Key Points for Your Workflow:**
### **Development (95% of time):**
- **No K8s dependency** - just Docker Compose for supporting services
- **Fast hot reload** - Django and Angular dev servers
- **Easy debugging** - direct access to logs and debugger
- **Simple database migrations** and model changes
### **K8s Testing (when needed):**
- **Container builds** work correctly
- **Service networking** functions properly
- **Volume mounts** for media files
- **Resource limits** don't break anything
- **Horizontal scaling** works as expected
### **Perfect for KIND:**
- KIND cluster only created when testing orchestration
- No overhead during daily development
- Easy to tear down and recreate
- Matches production K8s behavior
### **Tilt Usage (Optional):**
- **If you use Tilt**: Only for K8s testing, not development
- **If you skip Tilt**: Use the simple `kubectl` commands for testing
This approach gives you:
- **Fast development** without K8s complexity
- **Realistic testing** of the actual deployment
- **No vendor lock-in** to Tilt (though it's great if you want it)
- **Easy CI/CD** since K8s manifests are tested locally
The planning already supports this perfectly - you develop fast locally and test orchestration when needed!

46
def/envsink8s Normal file
View File

@@ -0,0 +1,46 @@
You're absolutely right! In Kubernetes, environment variables are handled at the deployment level through ConfigMaps and Secrets, not
individual service .env files.
Kubernetes approach:
# k8s/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: media-analyzer-config
data:
DB_HOST: "postgres-service"
HLS_BASE_URL: "http://nginx-hls-service"
# k8s/deployment.yaml
env:
- name: DB_HOST
valueFrom:
configMapKeyRef:
name: media-analyzer-config
key: DB_HOST
Better structure:
- Development: Single .env for docker-compose
- Production: K8s ConfigMaps/Secrets per environment
- No service-specific .env files
Recommended approach:
● Write(.env.development)
 Wrote 8 lines to .env.development
# Development environment variables for docker-compose
DB_HOST=postgres
DB_NAME=media_analyzer
DB_USER=media_user
DB_PASSWORD=media_pass
RTMP_PORT=1935
HLS_BASE_URL=http://localhost:8081
DEBUG=1
● Then K8s handles it via:
- k8s/base/configmap.yaml - Non-secret config
- k8s/base/secret.yaml - Passwords, keys
- k8s/overlays/staging/ - Staging overrides
- k8s/overlays/production/ - Production overrides
This way each deployment environment controls its own config, not the services themselves.

37
def/how-to-test Normal file
View File

@@ -0,0 +1,37 @@
1. Start the stack:
# Start Docker services
docker compose --env-file .env.development up -d
# Start Django backend (in separate terminal)
cd backend && python manage.py runserver
# Start Angular frontend (in separate terminal)
cd frontend && ng serve
2. Test the API:
# Check if Django API works
curl http://localhost:8000/api/streams/
# Create a test stream
curl -X POST http://localhost:8000/api/streams/create/ \
-H "Content-Type: application/json" \
-d '{"name": "Test Stream"}'
3. Test with OBS:
1. Open OBS Studio
2. Go to Settings → Stream
3. Set:
- Service: Custom
- Server: rtmp://localhost:1935/live
- Stream Key: (Copy from API response or frontend)
4. Start streaming in OBS
4. Test video playback:
1. Open http://localhost:4200
2. Create a stream in the frontend
3. Copy the RTMP URL to OBS
4. Start the stream
5. Click "View" to watch the HLS stream
Expected flow:
OBS → RTMP (port 1935) → NGINX-RTMP → HLS segments → Angular player

38
def/whyclaudewhy Normal file
View File

@@ -0,0 +1,38 @@
media-analyzer/backend/media_analyzer/urls.py
why MEDIA_ROOT just in debug
this to store media files which is obvious not ideal to store in the db (at least on postgres)
nginx
why add cors straigth in nginx conf
> is it correct to have cors configuration in nginx?
● Yes and No - it depends on the service responsibility:
NGINX CORS is correct when:
- NGINX serves static media files (HLS videos)
- Browser needs to access video files cross-origin
- NGINX is the media server
Django CORS is correct when:
- Django serves API endpoints
- Angular makes API calls cross-origin
- Django is the application server
Your current setup needs BOTH:
- Django CORS: For Angular → Django API calls (/api/streams/)
- NGINX CORS: For Angular → NGINX media requests (/playlist.m3u8, /segment.ts)
Separation of concerns:
Angular (4200) → Django (8000) # API calls - Django CORS
Angular (4200) → NGINX (8081) # Video files - NGINX CORS
In production/K8s, you'd typically:
- Have one ingress controller handle all CORS
- Or use service mesh (Istio) for cross-origin policies
But for development, having CORS in both services is correct because they serve different content types to the browser.

8
for_seenka.MD Normal file
View File

@@ -0,0 +1,8 @@
goals of the video
show what I thoroughly know of the stack
show how how I deal with stuff I don't know
show my thought process and development workflow
show the current state of my use of AI tools
how I "code-review" it as it goes
I let it does it's thing and write down questions (def/whyclaudewhy)

View File

@@ -0,0 +1,8 @@
# Development environment variables for docker-compose
DB_HOST=postgres
DB_NAME=media_analyzer
DB_USER=media_user
DB_PASSWORD=media_pass
RTMP_PORT=1935
HLS_BASE_URL=http://localhost:8081
DEBUG=1

View File

@@ -0,0 +1,22 @@
FROM python:3.11-slim
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y \
postgresql-client \
ffmpeg \
&& rm -rf /var/lib/apt/lists/*
# Copy requirements and install Python dependencies
COPY requirements.txt .
RUN pip install -r requirements.txt
# Copy source code
COPY . .
# Expose port
EXPOSE 8000
# Start development server
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

View File

@@ -0,0 +1,10 @@
export DB_HOST=localhost
export DB_NAME=media_analyzer
export DB_USER=media_user
export DB_PASSWORD=media_pass
export RTMP_PORT=1935
export HLS_BASE_URL=http://localhost:8000
export DJANGO_SETTINGS_MODULE=media_analyzer.settings.development
export DEBUG=True
export ALLOWED_HOSTS=localhost,127.0.0.1,192.168.1.3

View File

@@ -11,6 +11,7 @@ https://docs.djangoproject.com/en/5.2/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
@@ -23,9 +24,9 @@ BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = "django-insecure-n=jmw6r)102f0mytr7m1q5qwk^v$fd8gyokqpglsd&rl$d(^0="
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
DEBUG = os.getenv('DEBUG', 'True').lower() in ('true', '1', 'yes')
ALLOWED_HOSTS = []
ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',')
# Application definition
@@ -37,8 +38,8 @@ INSTALLED_APPS = [
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"corsheaders", # For CORS
"channels", # For WebSocket
"rest_framework", # For API
"streaming",
"ai_processing",
"effects",
@@ -46,6 +47,7 @@ INSTALLED_APPS = [
]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware", # Add this first
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
@@ -78,10 +80,16 @@ WSGI_APPLICATION = "media_analyzer.wsgi.application"
# Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
import os
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
"ENGINE": "django.db.backends.postgresql",
"NAME": os.getenv("DB_NAME", "media_analyzer"),
"USER": os.getenv("DB_USER", "media_user"),
"PASSWORD": os.getenv("DB_PASSWORD", "media_pass"),
"HOST": os.getenv("DB_HOST", "localhost"),
"PORT": os.getenv("DB_PORT", "5432"),
}
}
@@ -122,6 +130,25 @@ USE_TZ = True
STATIC_URL = "static/"
# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
# Streaming settings
RTMP_PORT = int(os.getenv('RTMP_PORT', 1935))
HLS_BASE_URL = os.getenv('HLS_BASE_URL', 'http://localhost:8000')
HLS_ENDPOINT_PATH = os.getenv('HLS_ENDPOINT_PATH', '/streaming/hls/') # For Django dev mode
# When using GCS, this would be: 'https://storage.googleapis.com/bucket-name/'
# CORS settings
CORS_ALLOWED_ORIGINS = [
"http://localhost:4200", # Angular dev server
"http://127.0.0.1:4200",
]
# For development - allow all origins (comment out for production)
CORS_ALLOW_ALL_ORIGINS = True
# Default primary key field type
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field

View File

@@ -0,0 +1,4 @@
from .base import *
DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', '192.168.1.3']

View File

@@ -15,8 +15,16 @@ Including another URLconf
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('streaming.urls')),
path('streaming/', include('streaming.urls')),
]
# Serve media files in development
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

View File

@@ -0,0 +1,9 @@
Django==5.0.6
psycopg2-binary==2.9.9
channels==4.0.0
channels-redis==4.2.0
celery==5.3.4
redis==5.0.1
ffmpeg-python==0.2.0
Pillow==10.0.1
django-cors-headers==4.3.1

View File

@@ -0,0 +1,36 @@
import ffmpeg
import logging
import subprocess
from pathlib import Path
logger = logging.getLogger(__name__)
class FFmpegHandler:
"""FFmpeg operations using ffmpeg-python library"""
def rtmp_to_hls(self, rtmp_url: str, output_path: str) -> subprocess.Popen:
"""Convert RTMP stream to HLS"""
stream = ffmpeg.input(rtmp_url)
output = ffmpeg.output(
stream, output_path,
c='copy', # Copy codecs for speed
f='hls',
hls_time=4,
hls_list_size=10,
hls_flags='delete_segments'
)
return ffmpeg.run_async(output, pipe_stdout=True, pipe_stderr=True)
def file_to_hls(self, input_file: str, output_path: str) -> subprocess.Popen:
"""Convert file to HLS"""
stream = ffmpeg.input(input_file)
output = ffmpeg.output(
stream, output_path,
c='copy',
f='hls',
hls_time=4
)
return ffmpeg.run_async(output, pipe_stdout=True, pipe_stderr=True)
# Singleton
ffmpeg_handler = FFmpegHandler()

View File

@@ -0,0 +1,53 @@
# Generated by Django 5.2.5 on 2025-08-15 20:06
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='VideoStream',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
('source_type', models.CharField(choices=[('rtmp', 'RTMP Stream'), ('file', 'File Upload'), ('url', 'External URL'), ('webcam', 'Local Webcam')], default='rtmp', max_length=20)),
('source_url', models.URLField(blank=True, null=True)),
('source_file', models.FileField(blank=True, null=True, upload_to='uploads/')),
('processing_mode', models.CharField(choices=[('live', 'Live Processing'), ('batch', 'Batch Processing')], default='live', max_length=20)),
('status', models.CharField(choices=[('inactive', 'Inactive'), ('starting', 'Starting'), ('active', 'Active'), ('stopping', 'Stopping'), ('error', 'Error')], default='inactive', max_length=20)),
('stream_key', models.CharField(max_length=64, unique=True)),
('hls_playlist_url', models.URLField(blank=True, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['-created_at'],
},
),
migrations.CreateModel(
name='MediaSegment',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('sequence_number', models.PositiveIntegerField()),
('file_path', models.CharField(max_length=500)),
('duration', models.FloatField()),
('created_at', models.DateTimeField(auto_now_add=True)),
('processed', models.BooleanField(default=False)),
('stream', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='segments', to='streaming.videostream')),
],
options={
'ordering': ['stream', 'sequence_number'],
'unique_together': {('stream', 'sequence_number')},
},
),
]

View File

@@ -0,0 +1,17 @@
# Generated by Django 5.0.6 on 2025-08-18 00:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('streaming', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='videostream',
name='hls_playlist_url',
),
]

View File

@@ -1,3 +1,57 @@
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class SourceType(models.TextChoices):
RTMP = 'rtmp', 'RTMP Stream'
FILE = 'file', 'File Upload'
URL = 'url', 'External URL'
WEBCAM = 'webcam', 'Local Webcam'
class ProcessingMode(models.TextChoices):
LIVE = 'live', 'Live Processing'
BATCH = 'batch', 'Batch Processing'
class StreamStatus(models.TextChoices):
INACTIVE = 'inactive', 'Inactive'
STARTING = 'starting', 'Starting'
ACTIVE = 'active', 'Active'
STOPPING = 'stopping', 'Stopping'
ERROR = 'error', 'Error'
class VideoStream(models.Model):
name = models.CharField(max_length=200)
source_type = models.CharField(max_length=20, choices=SourceType.choices, default=SourceType.RTMP)
source_url = models.URLField(blank=True, null=True) # For RTMP/URL sources
source_file = models.FileField(upload_to='uploads/', blank=True, null=True) # For file uploads
processing_mode = models.CharField(max_length=20, choices=ProcessingMode.choices, default=ProcessingMode.LIVE)
status = models.CharField(max_length=20, choices=StreamStatus.choices, default=StreamStatus.INACTIVE)
stream_key = models.CharField(max_length=64, unique=True) # For RTMP authentication
created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return f"{self.name} ({self.get_source_type_display()})"
class MediaSegment(models.Model):
stream = models.ForeignKey(VideoStream, on_delete=models.CASCADE, related_name='segments')
sequence_number = models.PositiveIntegerField()
file_path = models.CharField(max_length=500) # Path to .ts file
duration = models.FloatField() # Segment duration in seconds
created_at = models.DateTimeField(auto_now_add=True)
processed = models.BooleanField(default=False) # AI processing status
class Meta:
ordering = ['stream', 'sequence_number']
unique_together = ['stream', 'sequence_number']
def __str__(self):
return f"{self.stream.name} - Segment {self.sequence_number}"

View File

@@ -0,0 +1,144 @@
from abc import ABC, abstractmethod
import logging
from pathlib import Path
from django.conf import settings
from .models import VideoStream, StreamStatus
from .ffmpeg_handler import ffmpeg_handler
logger = logging.getLogger(__name__)
class VideoSourceAdapter(ABC):
"""Abstract base class for video source adapters"""
def __init__(self, stream: VideoStream):
self.stream = stream
self.process = None
@abstractmethod
def start_processing(self) -> bool:
"""Start processing video from this source"""
pass
@abstractmethod
def stop_processing(self) -> bool:
"""Stop processing video from this source"""
pass
@abstractmethod
def get_hls_output_path(self) -> str:
"""Get the output path for HLS playlist"""
pass
def update_stream_status(self, status: StreamStatus):
"""Update stream status in database"""
self.stream.status = status
self.stream.save(update_fields=['status'])
class RTMPSourceAdapter(VideoSourceAdapter):
"""Adapter for RTMP streams (OBS, etc.)"""
def start_processing(self) -> bool:
try:
self.update_stream_status(StreamStatus.STARTING)
# Create HLS output directory
hls_output_dir = Path(settings.MEDIA_ROOT) / 'hls' / str(self.stream.id)
hls_output_dir.mkdir(parents=True, exist_ok=True)
# Build RTMP URL
rtmp_port = getattr(settings, 'RTMP_PORT', 1935)
rtmp_url = f"rtmp://localhost:{rtmp_port}/live/{self.stream.stream_key}"
playlist_path = str(hls_output_dir / 'playlist.m3u8')
# Start FFmpeg conversion
self.process = ffmpeg_handler.rtmp_to_hls(rtmp_url, playlist_path)
# HLS URL is now generated dynamically from settings
self.update_stream_status(StreamStatus.ACTIVE)
logger.info(f"Started RTMP processing for stream {self.stream.id}")
return True
except Exception as e:
logger.error(f"Failed to start RTMP processing: {e}")
self.update_stream_status(StreamStatus.ERROR)
return False
def stop_processing(self) -> bool:
try:
self.update_stream_status(StreamStatus.STOPPING)
if self.process and self.process.poll() is None:
self.process.terminate()
self.process.wait(timeout=10)
self.update_stream_status(StreamStatus.INACTIVE)
logger.info(f"Stopped RTMP processing for stream {self.stream.id}")
return True
except Exception as e:
logger.error(f"Failed to stop RTMP processing: {e}")
self.update_stream_status(StreamStatus.ERROR)
return False
def get_hls_output_path(self) -> str:
hls_output_dir = Path(settings.MEDIA_ROOT) / 'hls' / str(self.stream.id)
return str(hls_output_dir / 'playlist.m3u8')
class FileSourceAdapter(VideoSourceAdapter):
"""Adapter for uploaded video files"""
def start_processing(self) -> bool:
try:
self.update_stream_status(StreamStatus.STARTING)
if not self.stream.source_file:
raise ValueError("No source file provided")
# Create HLS output directory
hls_output_dir = Path(settings.MEDIA_ROOT) / 'hls' / str(self.stream.id)
hls_output_dir.mkdir(parents=True, exist_ok=True)
playlist_path = str(hls_output_dir / 'playlist.m3u8')
# Start FFmpeg conversion
self.process = ffmpeg_handler.file_to_hls(self.stream.source_file.path, playlist_path)
# HLS URL is now generated dynamically from settings
self.update_stream_status(StreamStatus.ACTIVE)
logger.info(f"Started file processing for stream {self.stream.id}")
return True
except Exception as e:
logger.error(f"Failed to start file processing: {e}")
self.update_stream_status(StreamStatus.ERROR)
return False
def stop_processing(self) -> bool:
# File processing typically completes automatically
return True
def get_hls_output_path(self) -> str:
hls_output_dir = Path(settings.MEDIA_ROOT) / 'hls' / str(self.stream.id)
return str(hls_output_dir / 'playlist.m3u8')
class SourceAdapterFactory:
"""Factory for creating video source adapters"""
@staticmethod
def create_adapter(stream: VideoStream) -> VideoSourceAdapter:
adapters = {
'rtmp': RTMPSourceAdapter,
'file': FileSourceAdapter,
}
adapter_class = adapters.get(stream.source_type)
if not adapter_class:
raise ValueError(f"Unsupported source type: {stream.source_type}")
return adapter_class(stream)

View File

@@ -0,0 +1,10 @@
from django.urls import path
from . import views
urlpatterns = [
path('streams/', views.list_streams, name='list_streams'),
path('streams/create/', views.create_stream, name='create_stream'),
path('streams/<int:stream_id>/start/', views.start_stream, name='start_stream'),
path('streams/<int:stream_id>/stop/', views.stop_stream, name='stop_stream'),
path('hls/<str:filename>', views.serve_hls_file, name='serve_hls_file'),
]

View File

@@ -1,3 +1,127 @@
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.shortcuts import get_object_or_404
from django.conf import settings
from .models import VideoStream, StreamStatus
from .source_adapters import SourceAdapterFactory
import json
import uuid
import logging
import os
# Create your views here.
logger = logging.getLogger(__name__)
@csrf_exempt
@require_http_methods(["POST"])
def create_stream(request):
"""Create new stream"""
try:
data = json.loads(request.body)
stream = VideoStream.objects.create(
name=data['name'],
source_type=data.get('source_type', 'rtmp'),
processing_mode=data.get('processing_mode', 'live'),
stream_key=str(uuid.uuid4())
)
return JsonResponse({
'id': stream.id,
'name': stream.name,
'source_type': stream.source_type,
'processing_mode': stream.processing_mode,
'stream_key': stream.stream_key,
'status': stream.status,
'hls_playlist_url': f"{settings.HLS_BASE_URL}{settings.HLS_ENDPOINT_PATH}{stream.stream_key}.m3u8" if stream.status == 'active' else None,
'rtmp_ingest_url': f"rtmp://{request.get_host().split(':')[0]}:{settings.RTMP_PORT}/live/{stream.stream_key}",
'created_at': stream.created_at.isoformat()
})
except Exception as e:
return JsonResponse({'error': str(e)}, status=500)
def list_streams(request):
"""List all streams"""
streams = VideoStream.objects.all()
return JsonResponse({
'streams': [{
'id': s.id,
'name': s.name,
'source_type': s.source_type,
'processing_mode': s.processing_mode,
'status': s.status,
'hls_playlist_url': f"{settings.HLS_BASE_URL}{settings.HLS_ENDPOINT_PATH}{s.stream_key}.m3u8" if s.status == 'active' else None,
'rtmp_ingest_url': f"rtmp://{request.get_host().split(':')[0]}:{settings.RTMP_PORT}/live/{s.stream_key}",
'created_at': s.created_at.isoformat()
} for s in streams]
})
@csrf_exempt
@require_http_methods(["POST"])
def start_stream(request, stream_id):
"""Start stream processing"""
stream = get_object_or_404(VideoStream, id=stream_id)
try:
adapter = SourceAdapterFactory.create_adapter(stream)
success = adapter.start_processing()
if success:
return JsonResponse({
'message': 'Stream started successfully',
'hls_playlist_url': f"{settings.HLS_BASE_URL}{settings.HLS_ENDPOINT_PATH}{stream.stream_key}.m3u8"
})
else:
return JsonResponse({'error': 'Failed to start stream'}, status=500)
except Exception as e:
logger.error(f"Error starting stream {stream_id}: {e}")
return JsonResponse({'error': str(e)}, status=500)
@csrf_exempt
@require_http_methods(["POST"])
def stop_stream(request, stream_id):
"""Stop stream processing"""
stream = get_object_or_404(VideoStream, id=stream_id)
try:
adapter = SourceAdapterFactory.create_adapter(stream)
success = adapter.stop_processing()
if success:
return JsonResponse({'message': 'Stream stopped successfully'})
else:
return JsonResponse({'error': 'Failed to stop stream'}, status=500)
except Exception as e:
logger.error(f"Error stopping stream {stream_id}: {e}")
return JsonResponse({'error': str(e)}, status=500)
def serve_hls_file(request, filename):
"""Serve HLS files with proper headers"""
# Files are stored in project media directory
media_dir = os.path.join(settings.BASE_DIR.parent.parent, 'media')
file_path = os.path.join(media_dir, filename)
# Check if file exists
if not os.path.exists(file_path):
raise Http404("HLS file not found")
# Determine content type
if filename.endswith('.m3u8'):
content_type = 'application/vnd.apple.mpegurl'
elif filename.endswith('.ts'):
content_type = 'video/mp2t'
else:
content_type = 'application/octet-stream'
# Read and serve file
with open(file_path, 'rb') as f:
response = HttpResponse(f.read(), content_type=content_type)
response['Cache-Control'] = 'no-cache'
return response

View File

@@ -0,0 +1,91 @@
version: '3.8'
services:
# Django Backend
backend:
build: ./backend
ports:
- "8000:8000"
volumes:
- ./backend:/app
- ./media:/app/media
environment:
- DEBUG=1
- DB_HOST=postgres
- DB_NAME=media_analyzer
- DB_USER=media_user
- DB_PASSWORD=media_pass
depends_on:
postgres:
condition: service_healthy
command: python manage.py runserver 0.0.0.0:8000
# Django Migrations (run manually)
migrate:
build: ./backend
volumes:
- ./backend:/app
environment:
- DEBUG=1
- DB_HOST=postgres
- DB_NAME=media_analyzer
- DB_USER=media_user
- DB_PASSWORD=media_pass
depends_on:
postgres:
condition: service_healthy
command: python manage.py migrate
profiles: ["tools"] # Only runs when explicitly called
# # Angular Frontend
# frontend:
# build: ./frontend
# ports:
# - "4200:4200"
# volumes:
# - ./frontend:/app
# - /app/node_modules # Anonymous volume for node_modules
# environment:
# - CHOKIDAR_USEPOLLING=true # Enable polling for hot reload
# depends_on:
# - backend
# PostgreSQL Database
postgres:
image: postgres:15
environment:
POSTGRES_DB: media_analyzer
POSTGRES_USER: media_user
POSTGRES_PASSWORD: media_pass
ports:
- "5432:5432"
volumes:
- ./postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U media_user -d media_analyzer"]
interval: 5s
timeout: 5s
retries: 5
# Redis for Celery
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
- redis_data:/data
# NGINX with RTMP module for stream ingestion
nginx-rtmp:
image: tiangolo/nginx-rtmp
ports:
- "0.0.0.0:1935:1935" # RTMP port - bind to all interfaces
- "0.0.0.0:8081:80" # HTTP port for HLS - bind to all interfaces
volumes:
- ./media:/var/www/html
- ./docker/nginx.conf:/etc/nginx/nginx.conf
depends_on:
- postgres
volumes:
postgres_data:
redis_data:

View File

@@ -0,0 +1,75 @@
events {
worker_connections 1024;
}
# RTMP configuration
rtmp {
server {
listen 1935; # Listen on standard RTMP port
chunk_size 4000;
application live {
live on;
# Turn on HLS
hls on;
hls_path /var/www/html;
hls_fragment 3;
hls_playlist_length 60;
# Disable consuming the stream from nginx as rtmp
deny play all;
}
}
}
# HTTP configuration
http {
sendfile off;
tcp_nopush on;
# aio on; # Disabled - not supported on all platforms
# directio 512;
default_type application/octet-stream;
server {
listen 80;
location / {
# Disable cache
add_header 'Cache-Control' 'no-cache';
# CORS setup
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
add_header 'Access-Control-Allow-Headers' 'Range';
# allow CORS preflight requests
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
# HLS playlist files
location ~* \.m3u8$ {
add_header Content-Type application/vnd.apple.mpegurl;
add_header Cache-Control no-cache;
root /var/www/html/;
}
# HLS segment files
location ~* \.ts$ {
add_header Content-Type video/mp2t;
add_header Cache-Control no-cache;
root /var/www/html/;
}
# Default location
location / {
root /var/www/html/;
}
}
}
}

View File

@@ -0,0 +1,18 @@
FROM node:18-alpine
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm ci
# Copy source code
COPY . .
# Expose port
EXPOSE 4200
# Start development server with hot reload
CMD ["npm", "run", "start", "--", "--host", "0.0.0.0", "--poll", "2000"]

View File

@@ -16,6 +16,7 @@
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"hls.js": "^1.6.10",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
@@ -6951,6 +6952,12 @@
"node": ">= 0.4"
}
},
"node_modules/hls.js": {
"version": "1.6.10",
"resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.6.10.tgz",
"integrity": "sha512-16XHorwFNh+hYazYxDNXBLEm5aRoU+oxMX6qVnkbGH3hJil4xLav3/M6NH92VkD1qSOGKXeSm+5unuawPXK6OQ==",
"license": "Apache-2.0"
},
"node_modules/hosted-git-info": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-7.0.2.tgz",

View File

@@ -18,6 +18,7 @@
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"hls.js": "^1.6.10",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"

View File

@@ -1,336 +1,19 @@
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * * * The content below * * * * * * * * * * * -->
<!-- * * * * * * * * * * is only a placeholder * * * * * * * * * * -->
<!-- * * * * * * * * * * and can be replaced. * * * * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * Delete the template below * * * * * * * * * -->
<!-- * * * * * * * to get started with your project! * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<style>
:host {
--bright-blue: oklch(51.01% 0.274 263.83);
--electric-violet: oklch(53.18% 0.28 296.97);
--french-violet: oklch(47.66% 0.246 305.88);
--vivid-pink: oklch(69.02% 0.277 332.77);
--hot-red: oklch(61.42% 0.238 15.34);
--orange-red: oklch(63.32% 0.24 31.68);
--gray-900: oklch(19.37% 0.006 300.98);
--gray-700: oklch(36.98% 0.014 302.71);
--gray-400: oklch(70.9% 0.015 304.04);
--red-to-pink-to-purple-vertical-gradient: linear-gradient(
180deg,
var(--orange-red) 0%,
var(--vivid-pink) 50%,
var(--electric-violet) 100%
);
--red-to-pink-to-purple-horizontal-gradient: linear-gradient(
90deg,
var(--orange-red) 0%,
var(--vivid-pink) 50%,
var(--electric-violet) 100%
);
--pill-accent: var(--bright-blue);
font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji",
"Segoe UI Symbol";
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
h1 {
font-size: 3.125rem;
color: var(--gray-900);
font-weight: 500;
line-height: 100%;
letter-spacing: -0.125rem;
margin: 0;
font-family: "Inter Tight", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji",
"Segoe UI Symbol";
}
p {
margin: 0;
color: var(--gray-700);
}
main {
width: 100%;
min-height: 100%;
display: flex;
justify-content: center;
align-items: center;
padding: 1rem;
box-sizing: inherit;
position: relative;
}
.angular-logo {
max-width: 9.2rem;
}
.content {
display: flex;
justify-content: space-around;
width: 100%;
max-width: 700px;
margin-bottom: 3rem;
}
.content h1 {
margin-top: 1.75rem;
}
.content p {
margin-top: 1.5rem;
}
.divider {
width: 1px;
background: var(--red-to-pink-to-purple-vertical-gradient);
margin-inline: 0.5rem;
}
.pill-group {
display: flex;
flex-direction: column;
align-items: start;
flex-wrap: wrap;
gap: 1.25rem;
}
.pill {
display: flex;
align-items: center;
--pill-accent: var(--bright-blue);
background: color-mix(in srgb, var(--pill-accent) 5%, transparent);
color: var(--pill-accent);
padding-inline: 0.75rem;
padding-block: 0.375rem;
border-radius: 2.75rem;
border: 0;
transition: background 0.3s ease;
font-family: var(--inter-font);
font-size: 0.875rem;
font-style: normal;
font-weight: 500;
line-height: 1.4rem;
letter-spacing: -0.00875rem;
text-decoration: none;
}
.pill:hover {
background: color-mix(in srgb, var(--pill-accent) 15%, transparent);
}
.pill-group .pill:nth-child(6n + 1) {
--pill-accent: var(--bright-blue);
}
.pill-group .pill:nth-child(6n + 2) {
--pill-accent: var(--french-violet);
}
.pill-group .pill:nth-child(6n + 3),
.pill-group .pill:nth-child(6n + 4),
.pill-group .pill:nth-child(6n + 5) {
--pill-accent: var(--hot-red);
}
.pill-group svg {
margin-inline-start: 0.25rem;
}
.social-links {
display: flex;
align-items: center;
gap: 0.73rem;
margin-top: 1.5rem;
}
.social-links path {
transition: fill 0.3s ease;
fill: var(--gray-400);
}
.social-links a:hover svg path {
fill: var(--gray-900);
}
@media screen and (max-width: 650px) {
.content {
flex-direction: column;
width: max-content;
}
.divider {
height: 1px;
width: 100%;
background: var(--red-to-pink-to-purple-horizontal-gradient);
margin-block: 1.5rem;
}
}
</style>
<main class="main">
<div class="content">
<div class="left-side">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 982 239"
fill="none"
class="angular-logo"
>
<g clip-path="url(#a)">
<path
fill="url(#b)"
d="M388.676 191.625h30.849L363.31 31.828h-35.758l-56.215 159.797h30.848l13.174-39.356h60.061l13.256 39.356Zm-65.461-62.675 21.602-64.311h1.227l21.602 64.311h-44.431Zm126.831-7.527v70.202h-28.23V71.839h27.002v20.374h1.392c2.782-6.71 7.2-12.028 13.255-15.956 6.056-3.927 13.584-5.89 22.503-5.89 8.264 0 15.465 1.8 21.684 5.318 6.137 3.518 10.964 8.673 14.319 15.382 3.437 6.71 5.074 14.81 4.992 24.383v76.175h-28.23v-71.92c0-8.019-2.046-14.237-6.219-18.819-4.173-4.5-9.819-6.791-17.102-6.791-4.91 0-9.328 1.063-13.174 3.272-3.846 2.128-6.792 5.237-9.001 9.328-2.046 4.009-3.191 8.918-3.191 14.728ZM589.233 239c-10.147 0-18.82-1.391-26.103-4.091-7.282-2.7-13.092-6.382-17.511-10.964-4.418-4.582-7.528-9.655-9.164-15.219l25.448-6.136c1.145 2.372 2.782 4.663 4.991 6.954 2.209 2.291 5.155 4.255 8.837 5.81 3.683 1.554 8.428 2.291 14.074 2.291 8.019 0 14.647-1.964 19.884-5.81 5.237-3.845 7.856-10.227 7.856-19.064v-22.665h-1.391c-1.473 2.946-3.601 5.892-6.383 9.001-2.782 3.109-6.464 5.645-10.965 7.691-4.582 2.046-10.228 3.109-17.101 3.109-9.165 0-17.511-2.209-25.039-6.545-7.446-4.337-13.42-10.883-17.757-19.474-4.418-8.673-6.628-19.473-6.628-32.565 0-13.091 2.21-24.301 6.628-33.383 4.419-9.082 10.311-15.955 17.839-20.7 7.528-4.746 15.874-7.037 25.039-7.037 7.037 0 12.846 1.145 17.347 3.518 4.582 2.373 8.182 5.236 10.883 8.51 2.7 3.272 4.746 6.382 6.137 9.327h1.554v-19.8h27.821v121.749c0 10.228-2.454 18.737-7.364 25.447-4.91 6.709-11.538 11.7-20.048 15.055-8.509 3.355-18.165 4.991-28.884 4.991Zm.245-71.266c5.974 0 11.047-1.473 15.302-4.337 4.173-2.945 7.446-7.118 9.573-12.519 2.21-5.482 3.274-12.027 3.274-19.637 0-7.609-1.064-14.155-3.274-19.8-2.127-5.646-5.318-10.064-9.491-13.255-4.174-3.11-9.329-4.746-15.384-4.746s-11.537 1.636-15.792 4.91c-4.173 3.272-7.365 7.772-9.492 13.418-2.128 5.727-3.191 12.191-3.191 19.392 0 7.2 1.063 13.745 3.273 19.228 2.127 5.482 5.318 9.736 9.573 12.764 4.174 3.027 9.41 4.582 15.629 4.582Zm141.56-26.51V71.839h28.23v119.786h-27.412v-21.273h-1.227c-2.7 6.709-7.119 12.191-13.338 16.446-6.137 4.255-13.747 6.382-22.748 6.382-7.855 0-14.81-1.718-20.783-5.237-5.974-3.518-10.72-8.591-14.075-15.382-3.355-6.709-5.073-14.891-5.073-24.464V71.839h28.312v71.921c0 7.609 2.046 13.664 6.219 18.083 4.173 4.5 9.655 6.709 16.365 6.709 4.173 0 8.183-.982 12.111-3.028 3.927-2.045 7.118-5.072 9.655-9.082 2.537-4.091 3.764-9.164 3.764-15.218Zm65.707-109.395v159.796h-28.23V31.828h28.23Zm44.841 162.169c-7.61 0-14.402-1.391-20.457-4.091-6.055-2.7-10.883-6.791-14.32-12.109-3.518-5.319-5.237-11.946-5.237-19.801 0-6.791 1.228-12.355 3.765-16.773 2.536-4.419 5.891-7.937 10.228-10.637 4.337-2.618 9.164-4.664 14.647-6.055 5.4-1.391 11.046-2.373 16.856-3.027 7.037-.737 12.683-1.391 17.102-1.964 4.337-.573 7.528-1.555 9.574-2.782 1.963-1.309 3.027-3.273 3.027-5.973v-.491c0-5.891-1.718-10.391-5.237-13.664-3.518-3.191-8.51-4.828-15.056-4.828-6.955 0-12.356 1.473-16.447 4.5-4.009 3.028-6.71 6.546-8.183 10.719l-26.348-3.764c2.046-7.282 5.483-13.336 10.31-18.328 4.746-4.909 10.638-8.59 17.511-11.045 6.955-2.455 14.565-3.682 22.912-3.682 5.809 0 11.537.654 17.265 2.045s10.965 3.6 15.711 6.71c4.746 3.109 8.51 7.282 11.455 12.6 2.864 5.318 4.337 11.946 4.337 19.883v80.184h-27.166v-16.446h-.9c-1.719 3.355-4.092 6.464-7.201 9.328-3.109 2.864-6.955 5.237-11.619 6.955-4.828 1.718-10.229 2.536-16.529 2.536Zm7.364-20.701c5.646 0 10.556-1.145 14.729-3.354 4.173-2.291 7.364-5.237 9.655-9.001 2.292-3.763 3.355-7.854 3.355-12.273v-14.155c-.9.737-2.373 1.391-4.5 2.046-2.128.654-4.419 1.145-7.037 1.636-2.619.491-5.155.9-7.692 1.227-2.537.328-4.746.655-6.628.901-4.173.572-8.019 1.472-11.292 2.781-3.355 1.31-5.973 3.11-7.855 5.401-1.964 2.291-2.864 5.318-2.864 8.918 0 5.237 1.882 9.164 5.728 11.782 3.682 2.782 8.51 4.091 14.401 4.091Zm64.643 18.328V71.839h27.412v19.965h1.227c2.21-6.955 5.974-12.274 11.292-16.038 5.319-3.763 11.456-5.645 18.329-5.645 1.555 0 3.355.082 5.237.163 1.964.164 3.601.328 4.91.573v25.938c-1.227-.41-3.109-.819-5.646-1.146a58.814 58.814 0 0 0-7.446-.49c-5.155 0-9.738 1.145-13.829 3.354-4.091 2.209-7.282 5.236-9.655 9.164-2.373 3.927-3.519 8.427-3.519 13.5v70.448h-28.312ZM222.077 39.192l-8.019 125.923L137.387 0l84.69 39.192Zm-53.105 162.825-57.933 33.056-57.934-33.056 11.783-28.556h92.301l11.783 28.556ZM111.039 62.675l30.357 73.803H80.681l30.358-73.803ZM7.937 165.115 0 39.192 84.69 0 7.937 165.115Z"
/>
<path
fill="url(#c)"
d="M388.676 191.625h30.849L363.31 31.828h-35.758l-56.215 159.797h30.848l13.174-39.356h60.061l13.256 39.356Zm-65.461-62.675 21.602-64.311h1.227l21.602 64.311h-44.431Zm126.831-7.527v70.202h-28.23V71.839h27.002v20.374h1.392c2.782-6.71 7.2-12.028 13.255-15.956 6.056-3.927 13.584-5.89 22.503-5.89 8.264 0 15.465 1.8 21.684 5.318 6.137 3.518 10.964 8.673 14.319 15.382 3.437 6.71 5.074 14.81 4.992 24.383v76.175h-28.23v-71.92c0-8.019-2.046-14.237-6.219-18.819-4.173-4.5-9.819-6.791-17.102-6.791-4.91 0-9.328 1.063-13.174 3.272-3.846 2.128-6.792 5.237-9.001 9.328-2.046 4.009-3.191 8.918-3.191 14.728ZM589.233 239c-10.147 0-18.82-1.391-26.103-4.091-7.282-2.7-13.092-6.382-17.511-10.964-4.418-4.582-7.528-9.655-9.164-15.219l25.448-6.136c1.145 2.372 2.782 4.663 4.991 6.954 2.209 2.291 5.155 4.255 8.837 5.81 3.683 1.554 8.428 2.291 14.074 2.291 8.019 0 14.647-1.964 19.884-5.81 5.237-3.845 7.856-10.227 7.856-19.064v-22.665h-1.391c-1.473 2.946-3.601 5.892-6.383 9.001-2.782 3.109-6.464 5.645-10.965 7.691-4.582 2.046-10.228 3.109-17.101 3.109-9.165 0-17.511-2.209-25.039-6.545-7.446-4.337-13.42-10.883-17.757-19.474-4.418-8.673-6.628-19.473-6.628-32.565 0-13.091 2.21-24.301 6.628-33.383 4.419-9.082 10.311-15.955 17.839-20.7 7.528-4.746 15.874-7.037 25.039-7.037 7.037 0 12.846 1.145 17.347 3.518 4.582 2.373 8.182 5.236 10.883 8.51 2.7 3.272 4.746 6.382 6.137 9.327h1.554v-19.8h27.821v121.749c0 10.228-2.454 18.737-7.364 25.447-4.91 6.709-11.538 11.7-20.048 15.055-8.509 3.355-18.165 4.991-28.884 4.991Zm.245-71.266c5.974 0 11.047-1.473 15.302-4.337 4.173-2.945 7.446-7.118 9.573-12.519 2.21-5.482 3.274-12.027 3.274-19.637 0-7.609-1.064-14.155-3.274-19.8-2.127-5.646-5.318-10.064-9.491-13.255-4.174-3.11-9.329-4.746-15.384-4.746s-11.537 1.636-15.792 4.91c-4.173 3.272-7.365 7.772-9.492 13.418-2.128 5.727-3.191 12.191-3.191 19.392 0 7.2 1.063 13.745 3.273 19.228 2.127 5.482 5.318 9.736 9.573 12.764 4.174 3.027 9.41 4.582 15.629 4.582Zm141.56-26.51V71.839h28.23v119.786h-27.412v-21.273h-1.227c-2.7 6.709-7.119 12.191-13.338 16.446-6.137 4.255-13.747 6.382-22.748 6.382-7.855 0-14.81-1.718-20.783-5.237-5.974-3.518-10.72-8.591-14.075-15.382-3.355-6.709-5.073-14.891-5.073-24.464V71.839h28.312v71.921c0 7.609 2.046 13.664 6.219 18.083 4.173 4.5 9.655 6.709 16.365 6.709 4.173 0 8.183-.982 12.111-3.028 3.927-2.045 7.118-5.072 9.655-9.082 2.537-4.091 3.764-9.164 3.764-15.218Zm65.707-109.395v159.796h-28.23V31.828h28.23Zm44.841 162.169c-7.61 0-14.402-1.391-20.457-4.091-6.055-2.7-10.883-6.791-14.32-12.109-3.518-5.319-5.237-11.946-5.237-19.801 0-6.791 1.228-12.355 3.765-16.773 2.536-4.419 5.891-7.937 10.228-10.637 4.337-2.618 9.164-4.664 14.647-6.055 5.4-1.391 11.046-2.373 16.856-3.027 7.037-.737 12.683-1.391 17.102-1.964 4.337-.573 7.528-1.555 9.574-2.782 1.963-1.309 3.027-3.273 3.027-5.973v-.491c0-5.891-1.718-10.391-5.237-13.664-3.518-3.191-8.51-4.828-15.056-4.828-6.955 0-12.356 1.473-16.447 4.5-4.009 3.028-6.71 6.546-8.183 10.719l-26.348-3.764c2.046-7.282 5.483-13.336 10.31-18.328 4.746-4.909 10.638-8.59 17.511-11.045 6.955-2.455 14.565-3.682 22.912-3.682 5.809 0 11.537.654 17.265 2.045s10.965 3.6 15.711 6.71c4.746 3.109 8.51 7.282 11.455 12.6 2.864 5.318 4.337 11.946 4.337 19.883v80.184h-27.166v-16.446h-.9c-1.719 3.355-4.092 6.464-7.201 9.328-3.109 2.864-6.955 5.237-11.619 6.955-4.828 1.718-10.229 2.536-16.529 2.536Zm7.364-20.701c5.646 0 10.556-1.145 14.729-3.354 4.173-2.291 7.364-5.237 9.655-9.001 2.292-3.763 3.355-7.854 3.355-12.273v-14.155c-.9.737-2.373 1.391-4.5 2.046-2.128.654-4.419 1.145-7.037 1.636-2.619.491-5.155.9-7.692 1.227-2.537.328-4.746.655-6.628.901-4.173.572-8.019 1.472-11.292 2.781-3.355 1.31-5.973 3.11-7.855 5.401-1.964 2.291-2.864 5.318-2.864 8.918 0 5.237 1.882 9.164 5.728 11.782 3.682 2.782 8.51 4.091 14.401 4.091Zm64.643 18.328V71.839h27.412v19.965h1.227c2.21-6.955 5.974-12.274 11.292-16.038 5.319-3.763 11.456-5.645 18.329-5.645 1.555 0 3.355.082 5.237.163 1.964.164 3.601.328 4.91.573v25.938c-1.227-.41-3.109-.819-5.646-1.146a58.814 58.814 0 0 0-7.446-.49c-5.155 0-9.738 1.145-13.829 3.354-4.091 2.209-7.282 5.236-9.655 9.164-2.373 3.927-3.519 8.427-3.519 13.5v70.448h-28.312ZM222.077 39.192l-8.019 125.923L137.387 0l84.69 39.192Zm-53.105 162.825-57.933 33.056-57.934-33.056 11.783-28.556h92.301l11.783 28.556ZM111.039 62.675l30.357 73.803H80.681l30.358-73.803ZM7.937 165.115 0 39.192 84.69 0 7.937 165.115Z"
/>
</g>
<defs>
<radialGradient
id="c"
cx="0"
cy="0"
r="1"
gradientTransform="rotate(118.122 171.182 60.81) scale(205.794)"
gradientUnits="userSpaceOnUse"
>
<stop stop-color="#FF41F8" />
<stop offset=".707" stop-color="#FF41F8" stop-opacity=".5" />
<stop offset="1" stop-color="#FF41F8" stop-opacity="0" />
</radialGradient>
<linearGradient
id="b"
x1="0"
x2="982"
y1="192"
y2="192"
gradientUnits="userSpaceOnUse"
>
<stop stop-color="#F0060B" />
<stop offset="0" stop-color="#F0070C" />
<stop offset=".526" stop-color="#CC26D5" />
<stop offset="1" stop-color="#7702FF" />
</linearGradient>
<clipPath id="a"><path fill="#fff" d="M0 0h982v239H0z" /></clipPath>
</defs>
</svg>
<h1>Hello, {{ title }}</h1>
<p>Congratulations! Your app is running. 🎉</p>
<div class="app">
<header>
<h1>{{ title }}</h1>
</header>
<main class="main-content">
<div class="controls-section">
<app-stream-control
(streamSelected)="onStreamSelected($event)">
</app-stream-control>
</div>
<div class="divider" role="separator" aria-label="Divider"></div>
<div class="right-side">
<div class="pill-group">
@for (item of [
{ title: 'Explore the Docs', link: 'https://angular.dev' },
{ title: 'Learn with Tutorials', link: 'https://angular.dev/tutorials' },
{ title: 'CLI Docs', link: 'https://angular.dev/tools/cli' },
{ title: 'Angular Language Service', link: 'https://angular.dev/tools/language-service' },
{ title: 'Angular DevTools', link: 'https://angular.dev/tools/devtools' },
]; track item.title) {
<a
class="pill"
[href]="item.link"
target="_blank"
rel="noopener"
>
<span>{{ item.title }}</span>
<svg
xmlns="http://www.w3.org/2000/svg"
height="14"
viewBox="0 -960 960 960"
width="14"
fill="currentColor"
>
<path
d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h280v80H200v560h560v-280h80v280q0 33-23.5 56.5T760-120H200Zm188-212-56-56 372-372H560v-80h280v280h-80v-144L388-332Z"
/>
</svg>
</a>
}
</div>
<div class="social-links">
<a
href="https://github.com/angular/angular"
aria-label="Github"
target="_blank"
rel="noopener"
>
<svg
width="25"
height="24"
viewBox="0 0 25 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
alt="Github"
>
<path
d="M12.3047 0C5.50634 0 0 5.50942 0 12.3047C0 17.7423 3.52529 22.3535 8.41332 23.9787C9.02856 24.0946 9.25414 23.7142 9.25414 23.3871C9.25414 23.0949 9.24389 22.3207 9.23876 21.2953C5.81601 22.0377 5.09414 19.6444 5.09414 19.6444C4.53427 18.2243 3.72524 17.8449 3.72524 17.8449C2.61064 17.082 3.81137 17.0973 3.81137 17.0973C5.04697 17.1835 5.69604 18.3647 5.69604 18.3647C6.79321 20.2463 8.57636 19.7029 9.27978 19.3881C9.39052 18.5924 9.70736 18.0499 10.0591 17.7423C7.32641 17.4347 4.45429 16.3765 4.45429 11.6618C4.45429 10.3185 4.9311 9.22133 5.72065 8.36C5.58222 8.04931 5.16694 6.79833 5.82831 5.10337C5.82831 5.10337 6.85883 4.77319 9.2121 6.36459C10.1965 6.09082 11.2424 5.95546 12.2883 5.94931C13.3342 5.95546 14.3801 6.09082 15.3644 6.36459C17.7023 4.77319 18.7328 5.10337 18.7328 5.10337C19.3942 6.79833 18.9789 8.04931 18.8559 8.36C19.6403 9.22133 20.1171 10.3185 20.1171 11.6618C20.1171 16.3888 17.2409 17.4296 14.5031 17.7321C14.9338 18.1012 15.3337 18.8559 15.3337 20.0084C15.3337 21.6552 15.3183 22.978 15.3183 23.3779C15.3183 23.7009 15.5336 24.0854 16.1642 23.9623C21.0871 22.3484 24.6094 17.7341 24.6094 12.3047C24.6094 5.50942 19.0999 0 12.3047 0Z"
/>
</svg>
</a>
<a
href="https://twitter.com/angular"
aria-label="Twitter"
target="_blank"
rel="noopener"
>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
alt="Twitter"
>
<path
d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"
/>
</svg>
</a>
<a
href="https://www.youtube.com/channel/UCbn1OgGei-DV7aSRo_HaAiw"
aria-label="Youtube"
target="_blank"
rel="noopener"
>
<svg
width="29"
height="20"
viewBox="0 0 29 20"
fill="none"
xmlns="http://www.w3.org/2000/svg"
alt="Youtube"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M27.4896 1.52422C27.9301 1.96749 28.2463 2.51866 28.4068 3.12258C29.0004 5.35161 29.0004 10 29.0004 10C29.0004 10 29.0004 14.6484 28.4068 16.8774C28.2463 17.4813 27.9301 18.0325 27.4896 18.4758C27.0492 18.9191 26.5 19.2389 25.8972 19.4032C23.6778 20 14.8068 20 14.8068 20C14.8068 20 5.93586 20 3.71651 19.4032C3.11363 19.2389 2.56449 18.9191 2.12405 18.4758C1.68361 18.0325 1.36732 17.4813 1.20683 16.8774C0.613281 14.6484 0.613281 10 0.613281 10C0.613281 10 0.613281 5.35161 1.20683 3.12258C1.36732 2.51866 1.68361 1.96749 2.12405 1.52422C2.56449 1.08095 3.11363 0.76113 3.71651 0.596774C5.93586 0 14.8068 0 14.8068 0C14.8068 0 23.6778 0 25.8972 0.596774C26.5 0.76113 27.0492 1.08095 27.4896 1.52422ZM19.3229 10L11.9036 5.77905V14.221L19.3229 10Z"
/>
</svg>
</a>
</div>
<div class="viewer-section">
<app-stream-viewer
[streamUrl]="selectedStreamUrl">
</app-stream-viewer>
</div>
</div>
</main>
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * * * The content above * * * * * * * * * * * * -->
<!-- * * * * * * * * * * is only a placeholder * * * * * * * * * * * -->
<!-- * * * * * * * * * * and can be replaced. * * * * * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * * End of Placeholder * * * * * * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<router-outlet />
</main>
</div>

View File

@@ -0,0 +1,39 @@
.app {
min-height: 100vh;
padding: 1rem;
header {
text-align: center;
margin-bottom: 2rem;
h1 {
color: #333;
font-size: 2rem;
}
}
.main-content {
display: grid;
grid-template-columns: 1fr 2fr;
gap: 2rem;
max-width: 1400px;
margin: 0 auto;
@media (max-width: 768px) {
grid-template-columns: 1fr;
gap: 1rem;
}
}
.controls-section {
background: #f8f9fa;
padding: 1.5rem;
border-radius: 8px;
}
.viewer-section {
background: #000;
padding: 1rem;
border-radius: 8px;
}
}

View File

@@ -1,13 +1,22 @@
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { StreamControlComponent } from './components/stream-control/stream-control.component';
import { StreamViewerComponent } from './components/stream-viewer/stream-viewer.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
imports: [RouterOutlet, HttpClientModule, StreamControlComponent, StreamViewerComponent],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
export class AppComponent {
title = 'frontend';
title = 'Media Analyzer';
selectedStreamUrl: string = '';
onStreamSelected(streamUrl: string) {
console.log('App received stream URL:', streamUrl);
this.selectedStreamUrl = streamUrl;
}
}

View File

@@ -1 +1,39 @@
<p>stream-control works!</p>
<div class="stream-control">
<h2>Stream Control</h2>
<!-- Create New Stream -->
<div class="create-stream">
<h3>Create Stream</h3>
<input
type="text"
[(ngModel)]="newStreamName"
placeholder="Stream name"
class="input">
<button (click)="createStream()" class="btn btn-primary">Create Stream</button>
</div>
<!-- Stream List -->
<div class="streams-list">
<h3>Streams</h3>
<div class="stream-item" *ngFor="let stream of streams">
<div class="stream-info">
<h4>{{ stream.name }}</h4>
<p class="status">Status: <span [class]="'status-' + stream.status">{{ stream.status }}</span></p>
<p class="rtmp-url">RTMP URL: <code>{{ stream.rtmp_ingest_url }}</code></p>
<p class="stream-key">Stream Key: <code>{{ stream.stream_key }}</code></p>
</div>
<div class="stream-actions">
<button (click)="startStream(stream)"
[disabled]="stream.status === 'active'"
class="btn btn-success">Start</button>
<button (click)="stopStream(stream)"
[disabled]="stream.status === 'inactive'"
class="btn btn-danger">Stop</button>
<button (click)="selectStream(stream)"
*ngIf="stream.hls_playlist_url"
class="btn btn-info">Load</button>
</div>
</div>
</div>
</div>

View File

@@ -1,12 +1,87 @@
import { Component } from '@angular/core';
import { Component, EventEmitter, Output } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { environment } from '../../../environments/environment';
interface Stream {
id: number;
name: string;
source_type: string;
processing_mode: string;
status: string;
stream_key: string;
hls_playlist_url: string | null;
rtmp_ingest_url: string;
created_at: string;
}
@Component({
selector: 'app-stream-control',
standalone: true,
imports: [],
imports: [CommonModule, FormsModule],
templateUrl: './stream-control.component.html',
styleUrl: './stream-control.component.scss'
})
export class StreamControlComponent {
@Output() streamSelected = new EventEmitter<string>();
streams: Stream[] = [];
newStreamName = '';
selectedStream: Stream | null = null;
constructor(private http: HttpClient) {
this.loadStreams();
}
loadStreams() {
this.http.get<{streams: Stream[]}>(`${environment.apiUrl}/streams/`).subscribe({
next: (response) => {
this.streams = response.streams;
},
error: (error) => console.error('Error loading streams:', error)
});
}
createStream() {
if (!this.newStreamName) return;
this.http.post<Stream>(`${environment.apiUrl}/streams/create/`, {
name: this.newStreamName,
source_type: 'rtmp',
processing_mode: 'live'
}).subscribe({
next: (stream) => {
this.streams.push(stream);
this.newStreamName = '';
},
error: (error) => console.error('Error creating stream:', error)
});
}
startStream(stream: Stream) {
this.http.post(`${environment.apiUrl}/streams/${stream.id}/start/`, {}).subscribe({
next: () => {
this.loadStreams();
},
error: (error) => console.error('Error starting stream:', error)
});
}
stopStream(stream: Stream) {
this.http.post(`${environment.apiUrl}/streams/${stream.id}/stop/`, {}).subscribe({
next: () => {
this.loadStreams();
},
error: (error) => console.error('Error stopping stream:', error)
});
}
selectStream(stream: Stream) {
this.selectedStream = stream;
if (stream.hls_playlist_url) {
// Use the HLS URL provided by backend - no hardcoding!
this.streamSelected.emit(stream.hls_playlist_url);
}
}
}

View File

@@ -1 +1,10 @@
<p>stream-viewer works!</p>
<div class="stream-viewer">
<video #video controls muted class="video-player">
Your browser does not support video playback.
</video>
<div class="controls">
<button (click)="play()" class="btn">Play</button>
<button (click)="pause()" class="btn">Pause</button>
</div>
</div>

View File

@@ -0,0 +1,32 @@
.stream-viewer {
width: 100%;
max-width: 800px;
margin: 0 auto;
.video-player {
width: 100%;
height: auto;
background: #000;
border-radius: 8px;
}
.controls {
margin-top: 1rem;
display: flex;
gap: 1rem;
justify-content: center;
.btn {
padding: 0.5rem 1rem;
background: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
&:hover {
background: #0056b3;
}
}
}
}

View File

@@ -1,4 +1,5 @@
import { Component } from '@angular/core';
import { Component, ElementRef, Input, ViewChild, AfterViewInit, OnDestroy, OnChanges } from '@angular/core';
import Hls from 'hls.js';
@Component({
selector: 'app-stream-viewer',
@@ -7,6 +8,89 @@ import { Component } from '@angular/core';
templateUrl: './stream-viewer.component.html',
styleUrl: './stream-viewer.component.scss'
})
export class StreamViewerComponent {
export class StreamViewerComponent implements AfterViewInit, OnDestroy, OnChanges {
@ViewChild('video', { static: true }) videoElement!: ElementRef<HTMLVideoElement>;
@Input() streamUrl: string = '';
private hls?: Hls;
ngAfterViewInit() {
console.log('StreamViewer initialized with URL:', this.streamUrl);
if (this.streamUrl) {
this.loadStream(this.streamUrl);
}
}
ngOnChanges() {
console.log('StreamViewer URL changed to:', this.streamUrl);
if (this.streamUrl && this.videoElement) {
this.loadStream(this.streamUrl);
}
}
ngOnDestroy() {
if (this.hls) {
this.hls.destroy();
}
}
loadStream(url: string) {
const video = this.videoElement.nativeElement;
console.log('Loading HLS stream:', url);
if (this.hls) {
this.hls.destroy();
}
if (Hls.isSupported()) {
this.hls = new Hls({
debug: true, // Enable debug logging
enableWorker: false
});
this.hls.on(Hls.Events.MEDIA_ATTACHED, () => {
console.log('HLS media attached');
});
this.hls.on(Hls.Events.MANIFEST_LOADED, () => {
console.log('HLS manifest loaded');
});
this.hls.on(Hls.Events.ERROR, (event, data) => {
console.error('HLS error:', data);
});
this.hls.loadSource(url);
this.hls.attachMedia(video);
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
// Native HLS support (Safari)
video.src = url;
} else {
console.error('HLS not supported');
}
}
async play() {
try {
const video = this.videoElement.nativeElement;
if (video.readyState >= 2) { // HAVE_CURRENT_DATA
await video.play();
} else {
console.warn('Video not ready to play');
}
} catch (error) {
console.error('Play error:', error);
}
}
pause() {
try {
const video = this.videoElement.nativeElement;
if (!video.paused) {
video.pause();
}
} catch (error) {
console.error('Pause error:', error);
}
}
}

View File

@@ -0,0 +1,5 @@
export const environment = {
production: true,
apiUrl: '/api', // In production, same origin
backendUrl: '', // In production, same origin
};

View File

@@ -0,0 +1,5 @@
export const environment = {
production: false,
apiUrl: 'http://localhost:8000/api',
backendUrl: 'http://localhost:8000',
};