Passed
Push — master ( 3e986c...751e0b )
by Amin
01:07
created

hls_encryption_key_rotation   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 34
dl 0
loc 68
rs 10
c 0
b 0
f 0
wmc 4

3 Functions

Rating   Name   Duplication   Size   Complexity  
A progress() 0 5 2
A main() 0 8 1
A k_format() 0 2 1
1
"""
2
examples.hls.hls_encryption
3
~~~~~~~~~~~~
4
5
Create encrypted HlS streams and manifests
6
7
8
:copyright: (c) 2019 by Amin Yazdanpanah.
9
:website: https://www.aminyazdanpanah.com
10
:email: [email protected]
11
:license: MIT, see LICENSE for more details.
12
"""
13
14
import argparse
15
import sys
16
import logging
17
import tempfile
18
from os.path import join
19
from random import randrange
20
21
import ffmpeg_streaming
22
from ffmpeg_streaming.key_info_file import generate_key_info_file
23
24
logging.basicConfig(filename='streaming.log', level=logging.NOTSET, format='[%(asctime)s] %(levelname)s: %(message)s')
25
26
parser = argparse.ArgumentParser()
27
parser.add_argument('-i', '--input', required=True, help='The path to the video file (required).')
28
parser.add_argument('-key', '--key', required=True, help='The full pathname of the file where a random key will '
29
                                                         'be created (required). Note: The path of the key should '
30
                                                         'be accessible from your website(e.g. '
31
                                                         '"/var/www/public_html/keys/enc.key")')
32
parser.add_argument('-url', '--url', required=True, help='A URL (or a path) to access the key on your website ('
33
                                                         'required). It is highly recommended to protect the key '
34
                                                         'on your website(e.g using a token or check a '
35
                                                         'session/cookie)')
36
parser.add_argument('-o', '--output', default=None, help='The output to write files.')
37
args = parser.parse_args()
38
39
40
key_info_file_path = join(tempfile.gettempdir(), str(randrange(1000, 100000)) + '_py_ff_vi_st.tmp')
41
k_num = 1
42
43
44
def k_format(name, num):
45
    return str(name) + "_" + str(num)
46
47
48
def progress(per, ffmpeg):
49
    global k_num
50
    if ".ts' for writing" in ffmpeg:
51
        generate_key_info_file(k_format(args.url, k_num), k_format(args.key, k_num), key_info_path=key_info_file_path)
52
        k_num += 1
53
54
55
def main():
56
    (
57
        ffmpeg_streaming
58
            .hls(args.input, hls_flags="periodic_rekey")
59
            .encryption(args.url, args.key, key_info_path=key_info_file_path)
60
            .format('libx264')
61
            .auto_rep()
62
            .package(args.output, progress=progress)
63
    )
64
65
66
if __name__ == "__main__":
67
    sys.exit(main())
68