基本概念

关于 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

  • Brady

    magic story very thanks http://9a.stanthonysft.edu.pk/events/eduma-autumn-2016/ stromectol ivermectin "He was a consummate author, creating the modern-day thriller, and was one of the most visionary storytellers of our time. I will miss him dearly and he will be missed by tens of millions of readers worldwide," he added.

  • Scotty

    I live here http://limbestpmp.com/user/hot_lecture.php?vmode=view&idx=9668&page=1&schtxt=&fldname=&category= stromectol ivermectin While Washington has not disclosed the origin of the threat, the U.S. alert followed a renewed warning from al Qaeda leader Ayman al-Zawahri to take revenge for U.S. drone attacks on its fighters and imprisonment of Islamist militants in Guantanamo.

  • Harvey

    In tens, please (ten pound notes) http://ilc.gc.ac.kr/gc/board/view.asp?boardname=A006&no=972 stromectol ivermectin After holding the Dodgers scoreless for the last 10 innings of a 3-2, 13-inning win in the opener, St. Louis stifled them again, this time with hard-hitting shortstop Hanley Ramirez on the bench with bruised ribs after getting hit by a pitch Friday.

  • Willy

    I work for myself http://www.ifam.go.cr/?p=4779 stromectol ivermectin A local official called the fire "another tremendous wrench" in the recovery of a tourist area already hard-hit by Sandy, which tore through the north-eastern US in October 2012, causing billions of dollars of damage and killing more than 130 people.

  • Elmer

    Did you go to university? http://www.cnctour.com/admin/expo/regi_schedule.asp?expo_no=PARBUK0401&amp;course=C stromectol ivermectin &ldquo;It&rsquo;s amazing isn&rsquo;t it?&rdquo; Rivera said when asked about the incredibly long lines of fans waiting for his bobblehead doll. &ldquo;They showed a view from the outside and, my God, it was thousands of people there. Amazing.&rdquo;

  • Lawerence

    Which year are you in? http://munipacanga.gob.pe/web/index.php/noticias/item/110-rehabilitacion-servicios-educ-monteseco stromectol ivermectin Etisalat's statement on Sunday struck a more cautious tone, saying a final agreement was subject to "execution of a shareholders' agreement with the Kingdom of Morocco regarding Maroc Telecom, and securing competition and regulatory approvals in Morocco in addition to certain other jurisdictions in Maroc Telecom's footprint".

  • Francesco

    Very funny pictures http://mywindow.biz/2020/12/08/new-outdoor-area/ stromectol ivermectin Wieczorek said that until recent years, rescuers would not have faced that issue because planes tended to explode during crash-landings. But the development of fire-resistant materials in planes in recent decades has increased survivability in hard landings such as the one at SFO.

  • Orval

    I'd like to pay this cheque in, please http://ilpoliticamentecorretto.altervista.org/?p=238 stromectol ivermectin But that&#8217;s what happens in an urban area, where people are already concentrated to a certain extent. Mineral extraction boomtowns are often small cities without diverse existing amenities and industries. It was big news that a doughnut shop had opened in downtown Williston this February, and this boom has been going on for five years. Not to say that the people there wouldn&#8217;t like more places to eat, it&#8217;s just that a single-industry boom means that all the resources tend to gravitate toward its single purpose. Think combat base instead of urban renewal. Williston looks like it is in crisis response mode.

  • Shane

    Who's calling? http://medas.ne.jp/cgi-bin/webcal/schedule.cgi?form=2&amp;year=2021&amp;mon=2&amp;day=23&amp;repline=2232245828485 stromectol ivermectin "Acpo has produced an evaluation report of Operation Nutmeg that will be discussed by chief constables at the upcoming Chief Constables Council. This issue will form part of those discussions."

  • Bryce

    What are the hours of work? http://ilpoliticamentecorretto.altervista.org/?p=238 stromectol ivermectin “I said, ‘Tell me something only you would know to prove to me this is really Paul Gongaware,’” Ortega testified. “He said, ‘You have to sit down and get ahold of yourself and really listen to me, Michael is gone.’”