Passed
Push — master ( db420a...23049e )
by Amin
04:01
created

hls.time_left()   A

Complexity

Conditions 2

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nop 2
dl 0
loc 9
rs 10
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
    You can monitor ffmpeg command line and handle the process. For example, you can update a field in your database
28
    or log it to a file.
29
30
    Examples:
31
    1. Logging or printing ffmpeg command
32
    logging.info(ffmpeg) or print(ffmpeg)
33
34
    2. Handling Process object
35
    if "something happened":
36
        process.terminate()
37
38
    3. Email someone to notice the time of finishing process
39
    if time_left > 3600 and not already_send:  # if it takes more than one hour and you did not email them already
40
        Email.send(
41
            email='[email protected]',
42
            subject='Your video will be ready at %s seconds' % time_left,
43
            message='Your video takes more than an hour ...'
44
        )
45
       already_send = True
46
47
    4. Create a socket connection and show a progress bar(and other parameters) to 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