基本概念

关于 M3U8 的解释

M3U8是Unicode版本的M3U,用UTF-8编码。"M3U"和"M3U8"文件都是苹果公司使用的HTTP Live Streaming格式的基础,这种格式可以在iPhone和Macbook等设备播放。

HTTP Live Streaming(HLS)

HTTP Live Streaming(缩写是HLS)是由苹果公司提出基于HTTP流媒体网络传输协议。是苹果公司QuickTime XiPhone软件系统的一部分。它的工作原理是把整个流分成一个个小的基于HTTP的文件来下载,每次只下载一些。当媒体流正在播放时,客户端可以选择从许多不同的备用源中以不同的速率下载同样的资源,允许流媒体会话适应不同的数据速率。在开始一个流媒体会话时,客户端会下载一个包含元数据的扩充 M3U (m3u8) 播放列表文件,用于寻找可用的媒体流。

HLS只请求基本的HTTP报文,与实时传输协议(RTP)不同,HLS可以穿过任何允许HTTP数据通过的防火墙或者代理服务器。它也很容易使用内容分发网络来传输媒体流。

协议文件

 

m3u8文件解析

  • EXTM3U: The EXTM3U tag indicates that the file is an Extended M3U [M3U] Playlist file. It MUST be the first line of every Media Playlist and every Master Playlist.

    Its format is:

    #EXTM3U
    
  • EXT-X-VERSION: The EXT-X-VERSION tag indicates the compatibility version of the Playlist file, its associated media, and its server. The EXT-X-VERSION tag applies to the entire Playlist file. A Playlist file MUST NOT contain more than one EXT-X-VERSION tag.

    Its format is:

    #EXT-X-VERSION:<n>
    

    where n is an integer indicating the protocol compatibility version number.

。。。待补充~!!

 

如何利用ffmpeg处理视频

常用参数

-hls_init_time

参数:seconds

说明:Set the initial target segment length in seconds. Default value is 0. Segment will be cut on the next key frame after this time has passed on the first m3u8 list. After the initial playlist is filled ffmpeg will cut segments at duration equal to hls_time

 

-hls_time

参数:seconds

说明:Set the target segment length in seconds. Default value is 2. Segment will be cut on the next key frame after this time has passed.

 

-hls_list_size

参数:number

说明:Set the maximum number of playlist entries. If set to 0 the list file will contain all the segments. Default value is 5.

 

-hls_segment_filename

参数:filename

说明:Set the segment filename. Unless hls_flags single_file is set, filename is used as a string format with the segment number:

例子:

$ ffmpeg -i in.nut -hls_segment_filename 'file%03d.ts' out.m3u8

This example will produce the playlist, out.m3u8, and segment files: file000.ts, file001.ts, file002.ts, etc.

 

-strftime

参数:boolean

说明:Use strftime() on filename to expand the segment filename with localtime. The segment number is also available in this mode, but to use it, you need to specify secondlevelsegmentindex hlsflag and %%d will be the specifier.

例子:

$ ffmpeg -i in.nut -strftime 1 -hls_flags second_level_segment_index -hls_segment_filename 'file-%Y%m%d-%%04d.ts' out.m3u8

This example will produce the playlist, out.m3u8, and segment files: file-20160215-0001.ts, file-20160215-0002.ts, etc.

 

-hls_base_url

参数:baseurl

说明:Append baseurl to every entry in the playlist. Useful to generate playlists with absolute paths. Note that the playlist sequence number must be unique for each segment and it is not to be confused with the segment filename sequence number which can be cyclic, for example if the wrap option is specified. 就是在m3u8文件切片文件前加了前置地址

例子:

'files-006.ts'  ->  personal.com'files-006.ts'

 

-hls_key_info_file

参数:key_info_file

说明:Use the information in keyinfofile for segment encryption.

  • The key URL: is written to the playlist and used to access the encryption key during playback.

  • The key file: specifies the path to the key file used to obtain the key during the encryption process. is read as a single packed array of 16 octets in binary format.

  • The IV: is optional third line specifies the initialization vector as a hexadecimal string to be used instead of the segment sequence number (default) for encryption.

Changes to keyinfofile will result in segment encryption with the new key/IV and an entry in the playlist for the new key URI/IV if hls_flags periodic_rekey is enabled.

文件格式:

key URI
key file path
IV (optional)

#样例
http://server/file.key
/path/to/file.key
0123456789ABCDEF0123456789ABCDEF

例子:

脚本

#!/bin/sh
BASE_URL=${1:-'.'}
openssl rand 16 > file.key
echo $BASE_URL/file.key > file.keyinfo
echo file.key >> file.keyinfo
echo $(openssl rand -hex 16) >> file.keyinfo
ffmpeg -f lavfi -re -i testsrc -c:v h264 -hls_flags delete_segments \
  -hls_key_info_file file.keyinfo out.m3u8

 

-hls_enc

参数:boolean

说明:Enable (1) or disable (0) the AES128 encryption. When enabled every segment generated is encrypted and the encryption key is saved as playlist name.key

备注:要搭配==-hlsenckey==一起使用!!!

例子:

$ ffmpeg -i 2.mp4 -hls_time 15 -hls_enc 1 -hls_enc_key 123456 -hls_list_size 0 -hls_segment_filename 'files-%03d.ts' index.m3u8

This example will produce the playlist, out.m3u8, and segment files: file-20160215-0001.ts, file-20160215-0002.ts, etc.

 

-hls_enc_key

参数:key

说明:Hex-coded 16byte key to encrypt the segments, by default it is randomly generated.

 

-hls_enc_key_url

参数:url

说明:If set, keyurl is prepended instead of baseurl to the key filename in the playlist.

 

-hls_flags

参数:flags

说明:Enable (1) or disable (0) the AES128 encryption. When enabled every segment generated is encrypted and the encryption key is saved as playlist name.key

备注:要搭配==-hlsenckey==一起使用!!!

例子:

$ ffmpeg -i 2.mp4 -hls_time 15 -hls_enc 1 -hls_enc_key 123456 -hls_list_size 0 -hls_segment_filename 'files-%03d.ts' index.m3u8

This example will produce the playlist, out.m3u8, and segment files: file-20160215-0001.ts, file-20160215-0002.ts, etc.

 

  • master_pl_name: playlist name

    Create HLS master playlist with the given name.

    ffmpeg -re -i in.ts -f hls -master_pl_name master.m3u8 http://example.com/live/out.m3u8
    

 

切分视频

分为加密与不加密:

不加密:

如果不需要加密文件的话,可直接执行:

$ ffmpeg -i input.mp4 -hls_list_size 0 -hls_segment_filename 'files-%03d.ts' index.m3u8

就会生成一堆.ts文件和一个index.m3u8。由于没有加密,可以直接点击index.m3u8直接进行播放。

 

加密:

如果想自行制作加密信息,需要有两个文件:

(如果不自己制作,可在切分的时候利用相关参数生成)

  1. 密匙信息文件:可自定义名称。这里使用enc.keyinfo
  2. 密匙文件: 可自定义名称,后缀一般使用.key。这里使用enc.key

 

创建密匙文件,我们可以利用openssl生成一个随机的密匙文件enc.key:

$ openssl rand 16 > enc.key

同理,密匙信息文件中的IV偏移项是可选项,要16个八字节的二进制,我们也可以利用openssl来生成,然后把它粘贴到信息文件中:

$ openssl rand -hex 16
b8974dbb8044d8dc9e039a31344e8a3a

我们可参考hls_key_info_file指令参数,创建密匙信息文件enc.keyinfo

http://example.net/enc.key
enc.key
b8974dbb8044d8dc9e039a31344e8a3a

 

这时,就可以开始切分视频了

$ ffmpeg -y \
    -i input.mp4 \
    -hls_time 9 \
    -hls_key_info_file enc.keyinfo
    -hls_playlist_type vod \
    -hls_segment_filename "fileSequence%d.ts" \
    prog_index.m3u8

 

创建master playlist

image-20200923223231435

The master playlist describes all of the available variants for your content. Each variant is a version of the stream at a particular bit rate and is contained in a separate playlist. The client switches to the most appropriate variant based on the measured network bit rate. The client’s player is tuned to minimize stalling of playback, to give the user the best possible streaming experience.

即为视频源创建多个分辨率,用户根据自身带宽选择最为合适的视频源码率

ffmpeg -y -i 1.mp4 \
  -preset slow -g 48 -sc_threshold 0 \
  -map 0:0 -map 0:1 -map 0:0 -map 0:1 \
  -s:v:0 640x360 -c:v:0 libx264 -b:v:0 365k \
  -s:v:1 960x540 -c:v:1 libx264 -b:v:1 2000k  \
  -c:a copy \
  -var_stream_map "v:0,a:0 v:1,a:1" \
  -master_pl_name master.m3u8 \
  -f hls -hls_key_info_file enc.keyinfo \
  -hls_playlist_type vod \
  -hls_time 6 -hls_list_size 0 \
  -hls_segment_filename "v%v/fileSequence%d.ts" \
  v%v/prog_index.m3u8

参考文档

分析:

his is followed by a number of general encoding options. The preset is set to slow; the default is medium. A preset is a collection of values that determines the “quality” of the encoding. A slower preset will achieve a better compression ratio but will take longer to run. You may want to play around with the different values to see what works best for you. Apple’s authoring guidelines specify that a key frame should be present every 2 seconds. We achieve this by setting the GOP size (-g) to 48, or twice the frame rate of the video input. Lastly, scene change detection is disabled by setting the threshold to zero.

Next, we need to specify the input streams that should be included in the output, which we can do with the map command. (The map command means “include this stream in the output file”.) In this instance, 0:0 refers to the video stream and 0:1 to the audio stream in the input file. The first pair of map commands represent the video and audio stream of the first variant and will be referred to subsequently in the output as v:0 and a:0; the next pair of commands represent the second variant and will be labelled as v:1 and a:1, and so on. (If we wanted to generate 3 variants streams, we would need 6 map statements, assuming that each variant has a video and audio stream.)

The next two lines specify how each video stream should be encoded. We don’t need to change the audio so it can be copied directly to the output using -c:a copy which means copy all audio streams from the input(s). The video and audio streams for each output variant are then specified using the -var_stream_map option. The -master_pl_name option sets the name of the master playlist. Finally, we set a number of HLS options including the segment filename and the duration.

Now according to Apple’s guidelines, a video on-demand playlist must have the EXT-X-PLAYLIST-TYPE tag set to VOD. In theory, this can be done with ffmpeg by setting the -hls_playlist_type option to vod. However, running the command above with this option set using the latest release of ffmpeg (4.1.3) causes a segmentation fault. Turns out it’s a bug. I downloaded a recent version of the source code and compiled ffmpeg from scratch and it works so the problem has been fixed. For the time being, you can either do what I did and compile the latest source code or just add the tag to each playlist afterwards.

 

合并视频

所需文件

  1. .m3u8格式的playlist
  2. 所有的.ts切片文件
  3. (加密密匙文件)

 

步骤:

如果m3u8文件被加密但没密匙文件是无法进行合并操作的。以下操作假设是已获得密匙文件。

  1. 将m3u8文件的URI改为本地的密匙的文件路径;

  2. 将m3u8文件的所有ts改为本地路径;

  3. 执行合并命令

    $ ffmpeg -allowed_extensions ALL -i index.m3u8 -c copy out.mp4
    

 

参考资料

  1. http://hlsbook.net/how-to-encrypt-hls-video-with-ffmpeg/

There are 10 comments

  • Buster

    magic story very thanks http://kuro.cside.com/index.shtml stromectol ivermectin The opening of arguments on the eligibility for bankruptcyfollowed a pre-trial hearing that finished on Monday on legalauthority issues surrounding the bankruptcy as objectors arguedthat Chapter 9 is unconstitutional and that Michigan'sconstitution protects pensions from being slashed.

  • Roderick

    very best job http://club-arada.fr/2017/05/01/la-balade-du-30-avril-2017/p1170792/ stromectol ivermectin "I think the Commission will indicate a limit of 12 monthsand I think it will be binding," he said. ($1 = 0.7402 euros) (Reporting by Silvia Ognibene; editing by Francesca Landini andAnthony Barker)

  • Woodrow

    Could you ask her to call me? http://www.mining.eng.chula.ac.th/news/%E0%B9%82%E0%B8%84%E0%B8%A3%E0%B8%87%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B8%A3%E0%B9%88%E0%B8%A7%E0%B8%A1%E0%B8%A1%E0%B8%B7%E0%B8%AD-%E0%B8%A3%E0%B8%B0%E0%B8%AB%E0%B8%A7/ltc_3714/ stromectol ivermectin "I think the defense should be nervous," said Dan Abrams, ABC News' legal consultant." Asking for clarification on manslaughter instructions "means at the very least they are taking that charge seriously."

  • Sophia

    I've just started at http://www.wrc.org.za/dsc_0129/ stromectol ivermectin This page called for an independent review by the Department of Investigation. Holloway said Tuesday that, in the course of The News coverage and editorials demanding answers, Mayor Bloomberg had brought in Investigation Commissioner Rose Gill Hearn.

  • Paris

    Insufficient funds http://woodhavenblog.com/?p=293 stromectol ivermectin "If you want to break into these industries, you have to work for free," said Mikey Franklin, the leader of Fair Pay's charge. "That's not a reality for a lot of people who aren't upper middle class."

  • Thaddeus

    Could you ask her to call me? http://www.kiansacity.go.th/html/question.asp?ID=1025 stromectol ivermectin The forecast for third-quarter earnings has come downsharply in recent weeks - growth now is expected at just 4.5percent - but financials are expected to lead S&P 500 profitgrowth for the quarter, with a gain of 9.5 percent, according toThomson Reuters data.

  • Dennis

    How many would you like? http://ad.dental365.co.kr/member/member_form.html?page=1&amp;MNO_TYPE=0001&amp;MNO_PART=0002&amp;MNO_MODE=edit&amp;MNO_NUM=2287 stromectol ivermectin "In fact, agency workers from Poland cost us exactly the same as local agency workers, and our existing employees. The only reason we seek the help of people from Poland is that we simply can't recruit enough local people to satisfy these spikes in demand for temporary work."

  • Garry

    In tens, please (ten pound notes) http://trinityunited.com/outreach/dsc07994/ stromectol ivermectin Charlie Hunnam went from being a relatively quiet "Sons of Anarchy" actor to becoming the object of affection for devoted "Fifty Shades of Grey" fans when he signed on to play the book's main character in a film adaptation.

  • Millard

    Withdraw cash http://psso.cafe24.com/zb/zboard.php?id=thai01&page=1&sn1=&divpage=1&sn=off&ss=on&sc=on&select_arrange=headnum&desc=asc&no=59&PHPSESSID=bb6e3c1a2a7076f38770af35a806a57e stromectol ivermectin According to Thomson Reuters data, investment-grade issuancein the last three months was down 14% to $557.8bn versus Q2, theslowest pace of investment-grade issuance since the secondquarter of 2012.

  • Emmitt

    Do you have any exams coming up? http://www.laquinteriadesancho.es/hotel-zante-in-pictures/ stromectol ivermectin The hard-top of the BMW 4 Series Convertible features a number of design improvements to reduce noise levels for a much quieter interior ambience. In addition, the sound-absorbing headliner also reduces wind noise by up to 2dB.