Skip to main content

trim_video_proxy_server 0.1.0 copy "trim_video_proxy_server: ^0.1.0" to clipboard
trim_video_proxy_server: ^0.1.0 copied to clipboard

A lightweight HTTP proxy server for Dart applications. Automatically adds authentication headers to video requests (m3u8 playlists and TS segments). Ideal for video playback scenarios requiring authentication.

TrimVideo Proxy Server #

Pub Version License: MIT Dart Null Safety

A lightweight HTTP proxy server for Dart applications that automatically adds authentication headers to video requests. Perfect for scenarios requiring authenticated video streaming (m3u8 playlists and TS segments).

Features #

  • ✅ Automatic Port Selection - If the default port is occupied, automatically tries the next available port
  • ✅ Authentication Header Injection - Dynamically adds cookies/headers to all proxied requests
  • ✅ Zero-Copy Streaming - Streams video data directly without loading entire segments into memory
  • ✅ HTTP Configuration API - Provides /proxy/info endpoint for dynamic proxy configuration
  • ✅ Comprehensive Error Handling - Detailed error messages and graceful failure recovery
  • ✅ Custom Logger Support - Optional logger callback for integration with your logging system
  • ✅ Zero Dependencies - Uses only Dart SDK (dart:io, dart:convert)
  • ✅ Cross-Platform - Tested on Linux, Windows, Android; should work on any platform supporting dart:io

Installation #

From pub.dev #

Add this to your package's pubspec.yaml file:

dependencies:
  trim_video_proxy_server: ^0.1.0

Then run:

dart pub get
# or for Flutter
flutter pub get

From GitHub #

dependencies:
  trim_video_proxy_server:
    git:
      url: https://github.com/dongfengweixiao/trim_video_proxy_server.git

Quick Start #

Basic Example #

import 'package:trim_video_proxy_server/trim_video_proxy_server.dart';

void main() async {
  // Create proxy server instance
  final proxy = TrimVideoProxyServer();

  // Start the server on port 3999
  final port = await proxy.start(port: 3999);
  print('Proxy server started on port $port');

  // Set proxy target URL and authentication cookie
  proxy.setProxyInfo(
    'https://video.example.com',
    'session=abc123; auth_token=xyz789',
  );

  // Use proxy URL in your video player
  // Original: https://video.example.com/video.m3u8
  // Proxied:  http://localhost:3999/video.m3u8

  // ... later when app closes
  await proxy.stop();
}

With Custom Logger #

import 'package:trim_video_proxy_server/trim_video_proxy_server.dart';

void main() async {
  final proxy = TrimVideoProxyServer();

  // Inject custom logger
  proxy.logger = (message) {
    // Use your app's logging system
    print('[CustomLogger] $message');
    // Or integrate with logging packages like 'logging'
  };

  await proxy.start(port: 3999);
}

Dynamic Configuration via HTTP #

You can update proxy configuration at runtime by sending a POST request to /proxy/info:

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<void> updateProxyConfig(String proxyUrl) async {
  final response = await http.post(
    Uri.parse('$proxyUrl/proxy/info'),
    headers: {'Content-Type': 'application/json'},
    body: jsonEncode({
      'url': 'https://new-target.com',
      'cookie': 'new-cookie-value',
    }),
  );

  if (response.statusCode == 200) {
    print('Proxy configuration updated successfully');
  }
}

How It Works #

The proxy server acts as a middleman between your video player and the video server:

Video Player ──► [Proxy Server :3999] ──► Video Server
                    ↓
                  Add Auth Headers
  1. Video player requests video through proxy (e.g., http://localhost:3999/video/123.m3u8)
  2. Proxy forwards request to target URL with authentication headers
  3. Video server returns response
  4. Proxy streams response back to video player
  5. Zero-copy approach minimizes memory usage

Usage Examples #

Flutter Video Player Integration #

import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import 'package:trim_video_proxy_server/trim_video_proxy_server.dart';

class VideoPlayerPage extends StatefulWidget {
  const VideoPlayerPage({super.key});

  @override
  State<VideoPlayerPage> createState() => _VideoPlayerPageState();
}

class _VideoPlayerPageState extends State<VideoPlayerPage> {
  late TrimVideoProxyServer _proxy;
  late Player _player;
  String? _proxyUrl;

  @override
  void initState() {
    super.initState();
    _initProxy();
    _initPlayer();
  }

  Future<void> _initProxy() async {
    _proxy = TrimVideoProxyServer();

    // Inject custom logger
    _proxy.logger = (message) {
      debugPrint(message);
    };

    // Start proxy
    final port = await _proxy.start(port: 3999);
    _proxyUrl = 'http://localhost:$port';

    // Set authentication
    _proxy.setProxyInfo(
      'https://video.example.com',
      'your-auth-cookie=value',
    );

    setState(() {});
  }

  void _initPlayer() {
    _player = Player();
  }

  @override
  void dispose() {
    _proxy.stop();
    _player.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return VideoPlayer(
      controller: VideoController(_player),
    );
  }
}

Console/Server Application #

import 'package:trim_video_proxy_server/trim_video_proxy_server.dart';

void main() async {
  final proxy = TrimVideoProxyServer();

  // Configure with structured logging
  proxy.logger = (message) {
    final timestamp = DateTime.now().toIso8601String();
    print('[$timestamp] $message');
  };

  final port = await proxy.start(port: 8080);
  print('🚀 Proxy server running on http://localhost:$port');

  // Set proxy configuration
  proxy.setProxyInfo(
    'https://api.example.com',
    'api_key=secret123',
  );

  // Keep server running...
  print('Press Ctrl+C to stop');

  // Graceful shutdown
  // await proxy.stop();
}

API Reference #

TrimVideoProxyServer #

Constructors

TrimVideoProxyServer()

Creates a new proxy server instance.

Methods

Future<int> start({int port = 3999, int maxRetries = 100})

Starts the proxy server.

Parameters:

  • port - Preferred port number (default: 3999)
  • maxRetries - Maximum number of port attempts if port is occupied (default: 100)

Returns: The actual port number the server is listening on

Throws: Exception if all retry attempts fail

Example:

final port = await proxy.start(port: 3999);
print('Server listening on $port');
Future<void> stop()

Stops the proxy server and releases the port.

Example:

await proxy.stop();

Sets the target URL and authentication cookie.

Parameters:

  • url - The base URL of the target server (e.g., https://video.example.com)
  • cookie - Authentication cookie to add to all proxied requests

Example:

proxy.setProxyInfo(
  'https://video.example.com',
  'session=abc123; auth_token=xyz789',
);

Properties

void Function(String)? logger

Optional callback function for custom logging.

Example:

proxy.logger = (String message) {
  print('[CustomLogger] $message');
};

HTTP Endpoint #

POST /proxy/info #

Update proxy configuration dynamically.

Request:

POST /proxy/info HTTP/1.1
Content-Type: application/json

{
  "url": "https://video.example.com",
  "cookie": "session=abc123"
}

Success Response (200):

{
  "code": 0,
  "status": "success",
  "message": "Proxy info updated",
  "data": true
}

Error Response (400/405):

{
  "code": 400,
  "status": "error",
  "message": "url parameter cannot be empty",
  "data": false
}

Error Handling #

The proxy server handles various error scenarios:

Scenario Behavior
Port occupied Automatically tries next port (3999 → 4000 → 4001...)
Invalid target URL Returns 400 error
Proxy info not set Returns 400 error with message
Proxy request fails Returns 500 error with details
Target server down Returns 500 error with connection details

Performance Considerations #

  • Memory Efficient: Uses zero-copy streaming to avoid loading large video segments into memory
  • Low Latency: Minimal overhead as it only adds headers and forwards requests
  • Concurrent Support: Handles multiple simultaneous video requests
  • Connection Pooling: Reuses connections when possible

Platform Support #

Platform Status
Linux ✅ Fully Tested
Windows ✅ Fully Tested
Android ✅ Fully Tested
macOS ⚠️ Supported (not tested, should work)
iOS ⚠️ Supported (not tested, should work)
Web ❌ Not Applicable (cookies handled natively by browsers)

Testing #

import 'package:test/test.dart';
import 'package:trim_video_proxy_server/trim_video_proxy_server.dart';

void main() {
  group('TrimVideoProxyServer', () {
    late TrimVideoProxyServer proxy;

    setUp(() {
      proxy = TrimVideoProxyServer();
    });

    tearDown(() async {
      await proxy.stop();
    });

    test('should start on available port', () async {
      final port = await proxy.start(port: 3999);
      expect(port, greaterThanOrEqualTo(3999));
    });

    test('should set proxy info', () {
      proxy.setProxyInfo('https://example.com', 'cookie=value');
      // Verify proxy info is set
      expect(() => proxy.setProxyInfo('https://example.com', 'cookie=value'),
          returnsNormally);
    });
  });
}

Contributing #

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development #

# Clone the repository
git clone https://github.com/dongfengweixiao/trim_video_proxy_server.git

# Install dependencies
cd trim_video_proxy_server
dart pub get

# Run tests
dart test

# Run example
dart example/main.dart

Changelog #

See CHANGELOG.md for a list of changes in each version.

License #

This project is licensed under the MIT License - see the LICENSE file for details.

Author #

dongfengweixiao - GitHub

Show Your Support #

Give a ⭐️ if this project helped you!

0
likes
150
points
13
downloads

Documentation

Documentation
API reference

Publisher

unverified uploader

Weekly Downloads

A lightweight HTTP proxy server for Dart applications. Automatically adds authentication headers to video requests (m3u8 playlists and TS segments). Ideal for video playback scenarios requiring authentication.

Repository (GitHub)
View/report issues
Contributing

Topics

#http #proxy #video #streaming #authentication

License

MIT (license)

More

Packages that depend on trim_video_proxy_server