Скрипт предназначен для потоковой передачи мультимедиа с использованием утилиты ffmpeg и протокола HLS


#!/usr/bin/perl

=head1 NAME

hls-streaming.pl, version 1.0

=head1 DESCRIPTION

the script streams media files using HLS protocol

=head1 SYNOPSIS

hls-streaming.pl [option-1] ... [option-N]

=head1 OPTIONS

=over 8

=item --source

a path to files for streaming

=item --destination

a path to a folder for storing a playlist and segments

=item --name

a name of a playlist and segments

=item --url

a URL prefix for a playlist and segments (resulting URLs would look like <prefix>/<name>.m3u8 and <prefix>/<name><segment-number>.ts respectively)

=item --time

a segment duration (default - "10")

=item --count

a number of segments (default - "30")

=back

=head1 COPYRIGHT

(c) 2020 Alexander Galkov, [email protected]

=head1 LINK

www.galkov.pro/en/perl-script-for-hls-streaming-en

=cut

use strict;
use File::Find;
use Getopt::Long;
use Pod::Usage;

my $help;
my $source;
my $destination;
my $name;
my $url;
my $time = "10";
my $count = "30";

GetOptions ('help' => \$help,
    'source=s' => \$source,
    'destination=s' => \$destination,
    'name=s' => \$name,
    'url=s' => \$url,
    'time:s' => \$time,
    'count:s' => \$count);

if ($help)
{
    pod2usage( { -verbose => 2 } );
}
else
{
    my $address = "127.0.0.1";
    my $port = 49152+int(rand(16384));
    my $format = "%".length($count)."d";
    my $pid = fork;
    if ($pid==0)
    {
        while (1)
        {
            my @files;
            find(sub { return unless -f; push(@files,$File::Find::name); }, $source);
            my $cmd_1="ffmpeg -re -i \"@files[int(rand(scalar(@files)))]\" -vcodec copy -acodec copy -f mpegts udp://$address:$port > /dev/null 2>&amp;1";
            `$cmd_1`;
        }
    }
    my $cmd_2="ffmpeg -i udp://$address:$port?buffer_size=10000000?fifo_size=100000 -vcodec copy -acodec copy -f ssegment -segment_list_flags +live -segment_time $time -segment_list_entry_prefix $url/ -segment_list_size $count -segment_wrap $count -segment_list \"$destination/$name.m3u8\" \"$destination/$name$format.ts\" > /dev/null 2>&amp;1";
    `$cmd_2`;
}

Скрипт также можно скачать отсюда


Для запуска скрипта в фоновом режиме создаем службу

создаем unit-файл /usr/lib/systemd/system/hls-streaming.service

[Unit]
Description=HLS Streaming
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/sbin/hls-streaming.pl --source /hls --destination /var/www/html --name stream --url http://hls.domain.lan

[Install]
WantedBy=multi-user.target

обновляем конфигурацию systemd

systemctl daemon-reload

запускаем службу

systemctl start hls-streaming


Для снижения нагрузки на дисковую подсистему монтируем к конечной папке с сегментами RAM-диск

mount -t tmpfs -o size=1G,rootcontext=system_u:object_r:httpd_sys_content_t:s0 tmpfs /var/www/html

Добавить комментарий