Hướng dẫn php video streaming library

HTTP Live Streaming (HLS) là một trong những giao thức phát trực tuyến video được sử dụng rộng rãi nhất . Mặc dù nó được gọi là HTTP "live" streaming, nhưng nó được sử dụng cho cả phát trực tuyến theo yêu cầu và phát trực tiếp. HLS chia nhỏ các tệp video thành các tệp HTTP nhỏ hơn có thể tải xuống và phân phối chúng bằng giao thức HTTP. Các thiết bị khách tải các tệp HTTP này và sau đó phát lại chúng dưới dạng video.

Một ưu điểm của HLS là tất cả các thiết bị kết nối Internet đều hỗ trợ HTTP nên việc triển khai đơn giản hơn so với các giao thức truyền trực tuyến yêu cầu sử dụng các máy chủ chuyên dụng. Một ưu điểm khác là luồng HLS có thể tăng hoặc giảm chất lượng video tùy thuộc vào điều kiện mạng mà không làm gián đoạn quá trình phát lại. Đây là lý do tại sao chất lượng video có thể tốt hơn hoặc kém hơn ở giữa video khi người dùng đang xem video đó. Tính năng này được gọi là "adaptive bitrate video delivery" hoặc " adaptive bitrate streaming" và nếu không có nó, điều kiện mạng chậm có thể ngăn video phát hoàn toàn.

HLS được Apple phát triển để sử dụng trên các sản phẩm của Apple, nhưng hiện nó đã được sử dụng trên nhiều loại thiết bị.

Cài đặt HTTP Live Streaming trong Laravel

Cài đặt thư viện pbmedia/laravel-ffmpeg

Trước khi bắt đầu, bạn cần đảm bảo môi trường linux của bạn đã cài package FFmpeg.

Đầu tiên, chúng ta sẽ cài thư viện pbmedia/laravel-ffmpeg để hỗ trợ chúng ta thiết lập HLS trong Laravel, bạn hãy chạy lệnh command sau đây:

composer require pbmedia/laravel-ffmpeg

Tiếp theo, chúng ta sẽ thêm Service Provider và Facade vào file config/app.php

'providers' => [
    ...
    ProtoneMedia\LaravelFFMpeg\Support\ServiceProvider::class,
    ...
];

'aliases' => [
    ...
    'FFMpeg' => ProtoneMedia\LaravelFFMpeg\Support\FFMpeg::class
    ...
];

Tiếp theo, chúng ta sẽ tạo file config bằng lệnh command sau đây:

php artisan vendor:publish --provider="ProtoneMedia\LaravelFFMpeg\Support\ServiceProvider"

Bạn hãy thêm FFMPEG_BINARIES và FFPROBE_BINARIES vào file .env như sau:

FFMPEG_BINARIES=/usr/bin/ffmpeg
FFPROBE_BINARIES=/usr/bin/ffprobe

Setting filesystems

Chúng ta sẽ config các thông tin disk cần thiết, mở file filesystems.php nằm trong thư mục config và thêm các thông tin như sau:

 [
        ...
        'uploads' => [
            'driver' => 'local',
            'root' => storage_path('app/upload'),
        ],

        'streamable_videos' => [
            'driver' => 'local',
            'root' => storage_path('app/streamable_videos'),
            'url' => env('APP_URL').'/streamable_videos',
            'visibility' => 'public',
        ],

        'streamable_keys' => [
            'driver' => 'local',
            'root' => storage_path('app/streamable_keys'),
        ],
        ...
    ],
    ...
    'links' => [
        ...
        public_path('streamable_videos') => storage_path('app/streamable_videos'),
    ],

];

Hãy chạy lệnh command bên dưới, sau khi chỉnh sửa filesystems.php ở phía trên:

php artisan storage:link

Xây dựng chức năng Upload, Convert và Phát video HLS

Trước tiên, hãy tạo model có tên là Video, và cũng chắc chắn rằng chúng ta sẽ controller và migrate cơ sở dữ liệu:

php artisan make:model Video --migration --controller

Vì đây là một ví dụ nên chúng ta sẽ tạo một migrate cơ sở dữ liệu đơn giản như sau:

increments('id');
            $table->string('original_name');
            $table->string('disk');
            $table->string('path');
            $table->datetime('converted_for_streaming_at')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('videos');
    }
}

Tiếp theo, chúng ta chỉnh sửa model Video như sau:


     */
    protected $fillable = [
        'original_name',
        'disk',
        'path',
        'converted_for_streaming_at',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $dates = [
        'converted_for_streaming_at',
    ];

}

Do phần xử lý convert video là rất nặng, nên chúng ta sẽ sử dụng Laravel Queue, đầu tiên chúng ta sẽ tạo một Job bằng lệnh command sau:

php artisan make:job ConvertVideoForStreaming

Các bạn có thể tìm hiểu thêm Laravel Queue ở các bài viết sau:

https://manhdandev.com/laravel-queues-and-jobs.html

https://manhdandev.com/laravel-jobs-batching.html

Tiếp theo, hãy mở file ConvertVideoForStreaming.php nằm trong thư mục app/Jobs và chỉnh sửa như sau:

video = $video;
    }

    public function handle()
    {
        // create some video formats...
        $lowBitrateFormat  = (new X264)->setKiloBitrate(500);
        $midBitrateFormat  = (new X264)->setKiloBitrate(1500);
        $highBitrateFormat = (new X264)->setKiloBitrate(3000);

        // open the uploaded video from the right disk...
        FFMpeg::fromDisk($this->video->disk)
            ->open($this->video->path)

        // call the 'exportForHLS' method and specify the disk to which we want to export...
            ->exportForHLS()
            ->withRotatingEncryptionKey(function ($filename, $contents) {
                Storage::disk('streamable_keys')->put($filename, $contents);
            })
        // we'll add different formats so the stream will play smoothly
        // with all kinds of internet connections...
            ->addFormat($lowBitrateFormat)
            ->addFormat($midBitrateFormat)
            ->addFormat($highBitrateFormat)

        // call the 'save' method with a filename...
            ->toDisk('streamable_videos')
            ->save($this->video->id . '.m3u8');

        // update the database so we know the convertion is done!
        $this->video->update([
            'converted_for_streaming_at' => Carbon::now(),
        ]);
    }
}

Cuối cùng, hãy tạo một controller có các chức năng cơ bản như upload file video, convert video và xem video, hãy mở VideoController.php trong thư mục app/Http/Controllers và chỉnh sửa như bên dưới:

 'uploads',
            'original_name' => $request->file->getClientOriginalName(),
            'path'          => $request->file->store('videos', 'uploads'),
        ]);

        $this->dispatch(new ConvertVideoForStreaming($video));

        return response()->json([
            'id' => $video->id,
        ], 201);
    }

    public function show($id)
    {
        $video = Video::where('id', $id)->first();
        return view('play-hls', compact('video'));
    }

    public function playlist($playlist)
    {
        return FFMpeg::dynamicHLSPlaylist()
            ->fromDisk('streamable_videos')
            ->open($playlist)
            ->setKeyUrlResolver(function ($key) {
                return route('videos.key', ['key' => $key]);
            })
            ->setMediaUrlResolver(function ($mediaFilename) {
                return Storage::disk('streamable_videos')->url($mediaFilename);
            })
            ->setPlaylistUrlResolver(function ($playlistFilename) {
                return route('videos.playlist', ['playlist' => $playlistFilename]);
            });
    }

    public function key($key)
    {
        return Storage::disk('streamable_keys')->download($key);
    }
}

Setting Routes

Hãy mở route.php nằm trong thư mục routes và chỉnh sửa như sau:

 'videos', 'as' => 'videos.'], function () {
   Route::get('key/{key}', [VideoController::class, 'key'])->name('key');
   Route::get('playlist/{playlist}', [VideoController::class, 'playlist'])->name('playlist');
});

Tạo mới Blade File

Đầu tiên, chúng ta hãy xây dựng giao diện upload file đơn giản, hãy mở welcome.php nằm trong thư mục resources/views và chỉnh sửa như sau:




    Encrypted HLS with Laravel FFMpeg: Protect your videos with AES-128 Encryption
    
    
    


Encrypted HLS with Laravel FFMpeg: Protect your videos with AES-128 Encryption

@csrf

Tiếp theo, xây dựng giao diện để xem video HLS, hãy tạo file play-hls.blade.php nằm trong thư mục resources/views và có nội dung như sau



    
        
        
        Encrypted HLS with Laravel FFMpeg: Protect your videos with AES-128 Encryption
        
        
        
    
    
        

Encrypted HLS with Laravel FFMpeg: Protect your videos with AES-128 Encryption

Trải nghiệm HTTP Live Streaming trong Laravel

Bạn truy cập vào http://127.0.0.1:8000/ để thực hiện upload video

Hướng dẫn php video streaming library

Bạn vào DB kiểm tra xem record có id mới nhất có giá trị converted_for_streaming_at, nếu đã có giá trị các bạn truy cập http://127.0.0.1:8000/videos/{video}

Trong đó: video là id tự động tăng của model Video.

Hướng dẫn php video streaming library

Như vậy, chúng ta đã thực hiện xong một ví dụ đơn giản về HTTP Live Streaming trong Laravel rồi, tôi hy vọng hướng dẫn này của tôi sẽ giúp ích cho việc học tập cũng như công việc của bạn. Nếu bạn có bất kỳ câu hỏi nào hãy liên hệ với chúng tôi qua trang contact. Cảm ơn bạn.

Tài liệu tham khảo:

https://github.com/protonemedia/laravel-ffmpeg

https://www.youtube.com/watch?v=WlbzWoAcez4

https://phpnews.io/feeditem/how-to-use-ffmpeg-in-your-laravel-projects