hls.main()   A
last analyzed

Complexity

Conditions 4

Size

Total Lines 31
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 17
nop 0
dl 0
loc 31
rs 9.55
c 0
b 0
f 0
1
"""
2
examples.hls
3
~~~~~~~~~~~~
4
5
Create HlS streams
6
7
8
:copyright: (c) 2020 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 datetime
16
import sys
17
import logging
18
19
import ffmpeg_streaming
20
from ffmpeg_streaming import Formats
21
22
logging.basicConfig(filename='streaming.log', level=logging.NOTSET, format='[%(asctime)s] %(levelname)s: %(message)s')
23
24
25
def monitor(ffmpeg, duration, time_, time_left, process):
26
    """
27
       Handling proccess.
28
29
       Examples:
30
       1. Logging or printing ffmpeg command
31
       logging.info(ffmpeg) or print(ffmpeg)
32
33
       2. Handling Process object
34
       if "something happened":
35
           process.terminate()
36
37
       3. Email someone to inform about the time of finishing process
38
       if time_left > 3600 and not already_send:  # if it takes more than one hour and you have not emailed them already
39
           ready_time = time_left + time.time()
40
           Email.send(
41
               email='[email protected]',
42
               subject='Your video will be ready by %s' % datetime.timedelta(seconds=ready_time),
43
               message='Your video takes more than %s hour(s) ...' % round(time_left / 3600)
44
           )
45
          already_send = True
46
47
       4. Create a socket connection and show a progress bar(or other parameters) to your users
48
       Socket.broadcast(
49
           address=127.0.0.1
50
           port=5050
51
           data={
52
               percentage = per,
53
               time_left = datetime.timedelta(seconds=int(time_left))
54
           }
55
       )
56
57
       :param ffmpeg: ffmpeg command line
58
       :param duration: duration of the video
59
       :param time_: current time of transcoded video
60
       :param time_left: seconds left to finish the video process
61
       :param process: subprocess object
62
       :return: None
63
       """
64
    per = round(time_ / duration * 100)
65
    sys.stdout.write(
66
        "\rTranscoding...(%s%%) %s left [%s%s]" %
67
        (per, datetime.timedelta(seconds=int(time_left)), '#' * per, '-' * (100 - per))
68
    )
69
    sys.stdout.flush()
70
71
72
def main():
73
    parser = argparse.ArgumentParser()
74
    parser.add_argument('-i', '--input', required=True, help='The path to the video file (required).')
75
    parser.add_argument('-o', '--output', default=None, help='The output to write files.')
76
77
    parser.add_argument('-fmp4', '--fragmented', default=False, help='Fragmented mp4 output')
78
79
    parser.add_argument('-k', '--key', default=None, help='The full pathname of the file where a random key will be '
80
                                                          'created (required). Note: The path of the key should be '
81
                                                          'accessible from your website(e.g. '
82
                                                          '"/var/www/public_html/keys/enc.key")')
83
    parser.add_argument('-u', '--url', default=None, help='A URL (or a path) to access the key on your website ('
84
                                                          'required)')
85
    parser.add_argument('-krp', '--key_rotation_period', default=0, help='Use a different key for each set of '
86
                                                                         'segments, rotating to a new key after this '
87
                                                                         'many segments.')
88
89
    args = parser.parse_args()
90
91
    video = ffmpeg_streaming.input(args.input)
92
93
    hls = video.hls(Formats.h264())
94
    hls.auto_generate_representations()
95
96
    if args.fragmented:
97
        hls.fragmented_mp4()
98
99
    if args.key is not None and args.url is not None:
100
        hls.encryption(args.key, args.url, args.key_rotation_period)
101
102
    hls.output(args.output, monitor=monitor)
103
104
105
if __name__ == "__main__":
106
    sys.exit(main())
107