• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

EsupPortail / Esup-Pod / 8112176461

01 Mar 2024 01:32PM UTC coverage: 70.221%. First build
8112176461

Pull #1056

github

web-flow
Merge 639a7f93f into 043f63f32
Pull Request #1056: [DONE] Fix remote encoding and other stuff

46 of 158 new or added lines in 9 files covered. (29.11%)

9871 of 14057 relevant lines covered (70.22%)

0.7 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

70.28
/pod/video_encode_transcript/Encoding_video.py
1
"""Esup-Pod video encoding."""
2

3
import json
1✔
4
import os
1✔
5
import time
1✔
6
from webvtt import WebVTT, Caption
1✔
7
import argparse
1✔
8
import unicodedata
1✔
9

10
if __name__ == "__main__":
1✔
11
    from encoding_utils import (
×
12
        get_dressing_position_value,
13
        get_info_from_video,
14
        get_list_rendition,
15
        launch_cmd,
16
        check_file,
17
    )
18
    from encoding_settings import (
×
19
        FFMPEG_CMD,
20
        FFPROBE_CMD,
21
        FFPROBE_GET_INFO,
22
        FFMPEG_CRF,
23
        FFMPEG_PRESET,
24
        FFMPEG_PROFILE,
25
        FFMPEG_LEVEL,
26
        FFMPEG_HLS_TIME,
27
        FFMPEG_INPUT,
28
        FFMPEG_LIBX,
29
        FFMPEG_MP4_ENCODE,
30
        FFMPEG_HLS_COMMON_PARAMS,
31
        FFMPEG_HLS_ENCODE_PARAMS,
32
        FFMPEG_MP3_ENCODE,
33
        FFMPEG_M4A_ENCODE,
34
        FFMPEG_NB_THREADS,
35
        FFMPEG_AUDIO_BITRATE,
36
        FFMPEG_EXTRACT_THUMBNAIL,
37
        FFMPEG_NB_THUMBNAIL,
38
        FFMPEG_CREATE_THUMBNAIL,
39
        FFMPEG_EXTRACT_SUBTITLE,
40
        FFMPEG_DRESSING_INPUT,
41
        FFMPEG_DRESSING_OUTPUT,
42
        FFMPEG_DRESSING_WATERMARK,
43
        FFMPEG_DRESSING_FILTER_COMPLEX,
44
        FFMPEG_DRESSING_SCALE,
45
        FFMPEG_DRESSING_CONCAT,
46
    )
47
else:
48
    from .encoding_utils import (
1✔
49
        get_dressing_position_value,
50
        get_info_from_video,
51
        get_list_rendition,
52
        launch_cmd,
53
        check_file,
54
    )
55
    from .encoding_settings import (
1✔
56
        FFMPEG_CMD,
57
        FFPROBE_CMD,
58
        FFPROBE_GET_INFO,
59
        FFMPEG_CRF,
60
        FFMPEG_PRESET,
61
        FFMPEG_PROFILE,
62
        FFMPEG_LEVEL,
63
        FFMPEG_HLS_TIME,
64
        FFMPEG_INPUT,
65
        FFMPEG_LIBX,
66
        FFMPEG_MP4_ENCODE,
67
        FFMPEG_HLS_COMMON_PARAMS,
68
        FFMPEG_HLS_ENCODE_PARAMS,
69
        FFMPEG_MP3_ENCODE,
70
        FFMPEG_M4A_ENCODE,
71
        FFMPEG_NB_THREADS,
72
        FFMPEG_AUDIO_BITRATE,
73
        FFMPEG_EXTRACT_THUMBNAIL,
74
        FFMPEG_NB_THUMBNAIL,
75
        FFMPEG_CREATE_THUMBNAIL,
76
        FFMPEG_EXTRACT_SUBTITLE,
77
        FFMPEG_DRESSING_INPUT,
78
        FFMPEG_DRESSING_OUTPUT,
79
        FFMPEG_DRESSING_WATERMARK,
80
        FFMPEG_DRESSING_FILTER_COMPLEX,
81
        FFMPEG_DRESSING_SCALE,
82
        FFMPEG_DRESSING_CONCAT,
83
    )
84

85

86
__author__ = "Nicolas CAN <nicolas.can@univ-lille.fr>"
1✔
87
__license__ = "LGPL v3"
1✔
88

89
image_codec = ["jpeg", "gif", "png", "bmp", "jpg"]
1✔
90

91
"""
92
 - Get video source
93
 - get alls track from video source
94
 - encode tracks in HLS and mp4
95
 - save it
96
"""
97

98
try:
1✔
99
    from django.conf import settings
1✔
100

101
    FFMPEG_CMD = getattr(settings, "FFMPEG_CMD", FFMPEG_CMD)
1✔
102
    FFPROBE_CMD = getattr(settings, "FFPROBE_CMD", FFPROBE_CMD)
1✔
103
    FFPROBE_GET_INFO = getattr(settings, "FFPROBE_GET_INFO", FFPROBE_GET_INFO)
1✔
104
    FFMPEG_CRF = getattr(settings, "FFMPEG_CRF", FFMPEG_CRF)
1✔
105
    FFMPEG_PRESET = getattr(settings, "FFMPEG_PRESET", FFMPEG_PRESET)
1✔
106
    FFMPEG_PROFILE = getattr(settings, "FFMPEG_PROFILE", FFMPEG_PROFILE)
1✔
107
    FFMPEG_LEVEL = getattr(settings, "FFMPEG_LEVEL", FFMPEG_LEVEL)
1✔
108
    FFMPEG_HLS_TIME = getattr(settings, "FFMPEG_HLS_TIME", FFMPEG_HLS_TIME)
1✔
109
    FFMPEG_INPUT = getattr(settings, "FFMPEG_INPUT", FFMPEG_INPUT)
1✔
110
    FFMPEG_LIBX = getattr(settings, "FFMPEG_LIBX", FFMPEG_LIBX)
1✔
111
    FFMPEG_MP4_ENCODE = getattr(settings, "FFMPEG_MP4_ENCODE", FFMPEG_MP4_ENCODE)
1✔
112
    FFMPEG_HLS_COMMON_PARAMS = getattr(
1✔
113
        settings, "FFMPEG_HLS_COMMON_PARAMS", FFMPEG_HLS_COMMON_PARAMS
114
    )
115
    FFMPEG_HLS_ENCODE_PARAMS = getattr(
1✔
116
        settings, "FFMPEG_HLS_ENCODE_PARAMS", FFMPEG_HLS_ENCODE_PARAMS
117
    )
118
    FFMPEG_MP3_ENCODE = getattr(settings, "FFMPEG_MP3_ENCODE", FFMPEG_MP3_ENCODE)
1✔
119
    FFMPEG_M4A_ENCODE = getattr(settings, "FFMPEG_M4A_ENCODE", FFMPEG_M4A_ENCODE)
1✔
120
    FFMPEG_NB_THREADS = getattr(settings, "FFMPEG_NB_THREADS", FFMPEG_NB_THREADS)
1✔
121
    FFMPEG_AUDIO_BITRATE = getattr(settings, "FFMPEG_AUDIO_BITRATE", FFMPEG_AUDIO_BITRATE)
1✔
122
    FFMPEG_EXTRACT_THUMBNAIL = getattr(
1✔
123
        settings, "FFMPEG_EXTRACT_THUMBNAIL", FFMPEG_EXTRACT_THUMBNAIL
124
    )
125
    FFMPEG_NB_THUMBNAIL = getattr(settings, "FFMPEG_NB_THUMBNAIL", FFMPEG_NB_THUMBNAIL)
1✔
126
    FFMPEG_CREATE_THUMBNAIL = getattr(
1✔
127
        settings, "FFMPEG_CREATE_THUMBNAIL", FFMPEG_CREATE_THUMBNAIL
128
    )
129
    FFMPEG_EXTRACT_SUBTITLE = getattr(
1✔
130
        settings, "FFMPEG_EXTRACT_SUBTITLE", FFMPEG_EXTRACT_SUBTITLE
131
    )
132
    FFMPEG_DRESSING_INPUT = getattr(
1✔
133
        settings, "FFMPEG_DRESSING_INPUT", FFMPEG_DRESSING_INPUT
134
    )
135
    FFMPEG_DRESSING_OUTPUT = getattr(
1✔
136
        settings, "FFMPEG_DRESSING_OUTPUT", FFMPEG_DRESSING_OUTPUT
137
    )
138
    FFMPEG_DRESSING_WATERMARK = getattr(
1✔
139
        settings, "FFMPEG_DRESSING_WATERMARK", FFMPEG_DRESSING_WATERMARK
140
    )
141
    FFMPEG_DRESSING_FILTER_COMPLEX = getattr(
1✔
142
        settings, "FFMPEG_DRESSING_FILTER_COMPLEX", FFMPEG_DRESSING_FILTER_COMPLEX
143
    )
144
    FFMPEG_DRESSING_SCALE = getattr(
1✔
145
        settings, "FFMPEG_DRESSING_SCALE", FFMPEG_DRESSING_SCALE
146
    )
147
    FFMPEG_DRESSING_CONCAT = getattr(
1✔
148
        settings, "FFMPEG_DRESSING_CONCAT", FFMPEG_DRESSING_CONCAT
149
    )
150
except ImportError:  # pragma: no cover
151
    pass
152

153

154
class Encoding_video:
1✔
155
    """Encoding video object."""
156

157
    id = 0
1✔
158
    video_file = ""
1✔
159
    duration = 0
1✔
160
    list_video_track = {}
1✔
161
    list_audio_track = {}
1✔
162
    list_subtitle_track = {}
1✔
163
    list_image_track = {}
1✔
164
    list_mp4_files = {}
1✔
165
    list_hls_files = {}
1✔
166
    list_mp3_files = {}
1✔
167
    list_m4a_files = {}
1✔
168
    list_thumbnail_files = {}
1✔
169
    list_overview_files = {}
1✔
170
    list_subtitle_files = {}
1✔
171
    encoding_log = {}
1✔
172
    output_dir = ""
1✔
173
    start = 0
1✔
174
    stop = 0
1✔
175
    error_encoding = False
1✔
176
    cutting_start = 0
1✔
177
    cutting_stop = 0
1✔
178
    json_dressing = None
1✔
179
    dressing_input = ""
1✔
180

181
    def __init__(self, id=0, video_file="", start=0, stop=0, json_dressing=None, dressing_input=""):
1✔
182
        """Initialize a new Encoding_video object."""
183
        self.id = id
1✔
184
        self.video_file = video_file
1✔
185
        self.duration = 0
1✔
186
        self.list_video_track = {}
1✔
187
        self.list_audio_track = {}
1✔
188
        self.list_subtitle_track = {}
1✔
189
        self.list_image_track = {}
1✔
190
        self.list_mp4_files = {}
1✔
191
        self.list_hls_files = {}
1✔
192
        self.list_mp3_files = {}
1✔
193
        self.list_m4a_files = {}
1✔
194
        self.list_thumbnail_files = {}
1✔
195
        self.list_overview_files = {}
1✔
196
        self.encoding_log = {}
1✔
197
        self.list_subtitle_files = {}
1✔
198
        self.output_dir = ""
1✔
199
        self.start = 0
1✔
200
        self.stop = 0
1✔
201
        self.error_encoding = False
1✔
202
        self.cutting_start = start or 0
1✔
203
        self.cutting_stop = stop or 0
1✔
204
        self.json_dressing = json_dressing
1✔
205
        self.dressing_input = dressing_input
1✔
206

207
    def is_video(self) -> bool:
1✔
208
        """Check if current encoding correspond to a video."""
209
        return len(self.list_video_track) > 0
1✔
210

211
    def get_subtime(self, clip_begin, clip_end):
1✔
212
        subtime = ""
1✔
213
        if clip_begin != 0 or clip_end != 0:
1✔
214
            subtime += "-ss %s " % str(clip_begin) + "-to %s " % str(clip_end)
×
215
        return subtime
1✔
216

217
    def get_video_data(self):
1✔
218
        """Get alls tracks from video source and put it in object passed in parameter."""
219
        msg = "--> get_info_video\n"
1✔
220
        probe_cmd = FFPROBE_GET_INFO % {
1✔
221
            "ffprobe": FFPROBE_CMD,
222
            "select_streams": "",
223
            "source": '"' + self.video_file + '" ',
224
        }
225
        msg += probe_cmd + "\n"
1✔
226
        duration = 0
1✔
227
        info, return_msg = get_info_from_video(probe_cmd)
1✔
228
        msg += json.dumps(info, indent=2)
1✔
229
        msg += " \n"
1✔
230
        msg += return_msg + "\n"
1✔
231
        self.add_encoding_log("probe_cmd", probe_cmd, True, msg)
1✔
232
        try:
1✔
233
            duration = int(float("%s" % info["format"]["duration"]))
1✔
234
        except (RuntimeError, KeyError, AttributeError, ValueError, TypeError) as err:
×
235
            msg = "\nUnexpected error: {0}".format(err)
×
236
            self.add_encoding_log("duration", "", True, msg)
×
237
        if self.cutting_start != 0 or self.cutting_stop != 0:
1✔
238
            duration = self.cutting_stop - self.cutting_start
×
239
        self.duration = duration
1✔
240
        streams = info.get("streams", [])
1✔
241
        for stream in streams:
1✔
242
            self.add_stream(stream)
1✔
243

244
    def fix_duration(self, input_file):
1✔
245
        msg = "--> get_info_video\n"
×
246
        probe_cmd = 'ffprobe -v quiet -show_entries format=duration -hide_banner  \
×
247
                    -of default=noprint_wrappers=1:nokey=1 -print_format json -i \
248
                    "{}"'.format(
249
            input_file
250
        )
251
        info, return_msg = get_info_from_video(probe_cmd)
×
252
        msg += json.dumps(info, indent=2)
×
253
        msg += " \n"
×
254
        msg += return_msg + "\n"
×
255
        duration = 0
×
256
        try:
×
257
            duration = int(float("%s" % info["format"]["duration"]))
×
258
        except (RuntimeError, KeyError, AttributeError, ValueError, TypeError) as err:
×
259
            msg += "\nUnexpected error: {0}".format(err)
×
260
        self.add_encoding_log("fix_duration", "", True, msg)
×
261
        if self.cutting_start != 0 or self.cutting_stop != 0:
×
262
            duration = self.cutting_stop - self.cutting_start
×
263
        self.duration = duration
×
264

265
    def add_stream(self, stream):
1✔
266
        codec_type = stream.get("codec_type", "unknown")
1✔
267
        # https://ffmpeg.org/doxygen/3.2/group__lavu__misc.html#ga9a84bba4713dfced21a1a56163be1f48
268
        if codec_type == "audio":
1✔
269
            codec = stream.get("codec_name", "unknown")
1✔
270
            self.list_audio_track["%s" % stream.get("index")] = {
1✔
271
                "sample_rate": stream.get("sample_rate", 0),
272
                "channels": stream.get("channels", 0),
273
            }
274
        if codec_type == "video":
1✔
275
            codec = stream.get("codec_name", "unknown")
1✔
276
            if any(ext in codec.lower() for ext in image_codec):
1✔
277
                self.list_image_track["%s" % stream.get("index")] = {
×
278
                    "width": stream.get("width", 0),
279
                    "height": stream.get("height", 0),
280
                }
281
            else:
282
                self.list_video_track["%s" % stream.get("index")] = {
1✔
283
                    "width": stream.get("width", 0),
284
                    "height": stream.get("height", 0),
285
                }
286
        if codec_type == "subtitle":
1✔
287
            codec = stream.get("codec_name", "unknown")
×
288
            language = ""
×
289
            if stream.get("tags"):
×
290
                language = stream.get("tags").get("language", "")
×
291
            self.list_subtitle_track["%s" % stream.get("index")] = {"language": language}
×
292

293
    def get_output_dir(self) -> str:
1✔
294
        dirname = os.path.dirname(self.video_file)
1✔
295
        return os.path.join(dirname, "%04d" % int(self.id))
1✔
296

297
    def create_output_dir(self):
1✔
298
        output_dir = self.get_output_dir()
1✔
299
        if not os.path.exists(output_dir):
1✔
300
            os.makedirs(output_dir)
1✔
301
        self.output_dir = output_dir
1✔
302

303
    def get_mp4_command(self) -> str:
1✔
304
        mp4_command = "%s " % FFMPEG_CMD
1✔
305
        list_rendition = get_list_rendition()
1✔
306
        # remove rendition if encode_mp4 == False
307
        for rend in list_rendition.copy():
1✔
308
            if list_rendition[rend]["encode_mp4"] is False:
1✔
309
                list_rendition.pop(rend)
1✔
310
        if len(list_rendition) == 0:
1✔
311
            return ""
×
312
        first_item = list_rendition.popitem(last=False)
1✔
313
        mp4_command += FFMPEG_INPUT % {
1✔
314
            "input": self.video_file,
315
            "nb_threads": FFMPEG_NB_THREADS,
316
        }
317
        output_file = os.path.join(self.output_dir, "%sp.mp4" % first_item[0])
1✔
318
        mp4_command += FFMPEG_MP4_ENCODE % {
1✔
319
            "cut": self.get_subtime(self.cutting_start, self.cutting_stop),
320
            "map_audio": "-map 0:a:0" if len(self.list_audio_track) > 0 else "",
321
            "libx": FFMPEG_LIBX,
322
            "height": first_item[0],
323
            "preset": FFMPEG_PRESET,
324
            "profile": FFMPEG_PROFILE,
325
            "level": FFMPEG_LEVEL,
326
            "crf": FFMPEG_CRF,
327
            "maxrate": first_item[1]["maxrate"],
328
            "bufsize": first_item[1]["maxrate"],
329
            "ba": first_item[1]["audio_bitrate"],
330
            "output": output_file,
331
        }
332
        self.list_mp4_files[first_item[0]] = output_file
1✔
333
        """
334
        il est possible de faire ainsi :
335
        mp4_command += FFMPEG_MP4_ENCODE.format(
336
            height=first_item[0],
337
            [...]
338
        )
339
        """
340
        in_height = list(self.list_video_track.items())[0][1]["height"]
1✔
341
        for rend in list_rendition:
1✔
342
            resolution_threshold = rend - rend * (
1✔
343
                list_rendition[rend]["encoding_resolution_threshold"] / 100
344
            )
345
            if in_height >= resolution_threshold:
1✔
346
                output_file = os.path.join(self.output_dir, "%sp.mp4" % rend)
×
347
                mp4_command += FFMPEG_MP4_ENCODE % {
×
348
                    "cut": self.get_subtime(self.cutting_start, self.cutting_stop),
349
                    "map_audio": "-map 0:a:0" if len(self.list_audio_track) > 0 else "",
350
                    "libx": FFMPEG_LIBX,
351
                    "height": min(rend, in_height),
352
                    "preset": FFMPEG_PRESET,
353
                    "profile": FFMPEG_PROFILE,
354
                    "level": FFMPEG_LEVEL,
355
                    "crf": FFMPEG_CRF,
356
                    "maxrate": list_rendition[rend]["maxrate"],
357
                    "bufsize": list_rendition[rend]["maxrate"],
358
                    "ba": list_rendition[rend]["audio_bitrate"],
359
                    "output": output_file,
360
                }
361
                self.list_mp4_files[rend] = output_file
×
362
        return mp4_command
1✔
363

364
    def get_hls_command(self) -> str:
1✔
365
        hls_command = "%s " % FFMPEG_CMD
1✔
366
        list_rendition = get_list_rendition()
1✔
367
        hls_command += FFMPEG_INPUT % {
1✔
368
            "input": self.video_file,
369
            "nb_threads": FFMPEG_NB_THREADS,
370
        }
371
        hls_common_params = FFMPEG_HLS_COMMON_PARAMS % {
1✔
372
            "cut": self.get_subtime(self.cutting_start, self.cutting_stop),
373
            "libx": FFMPEG_LIBX,
374
            "preset": FFMPEG_PRESET,
375
            "profile": FFMPEG_PROFILE,
376
            "level": FFMPEG_LEVEL,
377
            "crf": FFMPEG_CRF,
378
        }
379
        hls_command += hls_common_params
1✔
380
        in_height = list(self.list_video_track.items())[0][1]["height"]
1✔
381
        for index, rend in enumerate(list_rendition):
1✔
382
            resolution_threshold = rend - rend * (
1✔
383
                list_rendition[rend]["encoding_resolution_threshold"] / 100
384
            )
385
            if in_height >= resolution_threshold or index == 0:
1✔
386
                output_file = os.path.join(self.output_dir, "%sp.m3u8" % rend)
1✔
387
                hls_command += hls_common_params
1✔
388
                hls_command += FFMPEG_HLS_ENCODE_PARAMS % {
1✔
389
                    "height": min(rend, in_height),
390
                    "maxrate": list_rendition[rend]["maxrate"],
391
                    "bufsize": list_rendition[rend]["maxrate"],
392
                    "ba": list_rendition[rend]["audio_bitrate"],
393
                    "hls_time": FFMPEG_HLS_TIME,
394
                    "output": output_file,
395
                }
396
                self.list_hls_files[rend] = output_file
1✔
397
        return hls_command
1✔
398

399
    def get_dressing_file(self) -> str:
1✔
400
        """Create or replace the dressed video file."""
401
        dirname = os.path.dirname(self.video_file)
×
402
        filename, ext = os.path.splitext(os.path.basename(self.video_file))
×
403
        output_file = os.path.join(dirname, filename + "_dressing" + ext)
×
404
        return output_file
×
405

406
    def get_dressing_command(self) -> str:
1✔
407
        """Get the command based on the dressing object parameters."""
408
        height = str(list(self.list_video_track.items())[0][1]["height"])
×
409
        order_opening_credits = 0
×
410
        dressing_command_params = "[vid][0:a]"
×
411
        number_concat = 1
×
412
        dressing_command = "%s " % FFMPEG_CMD
×
413
        dressing_command += FFMPEG_INPUT % {
×
414
            "input": self.video_file,
415
            "nb_threads": FFMPEG_NB_THREADS,
416
        }
417

NEW
418
        dressing_command += self.dressing_input
×
419
        dressing_command_filter = []
×
420
        dressing_command_filter.append(
×
421
            FFMPEG_DRESSING_SCALE
422
            % {
423
                "number": "0",
424
                "height": height,
425
                "name": "vid",
426
            }
427
        )
NEW
428
        if self.json_dressing["watermark"]:
×
429
            dressing_command_params = "[video][0:a]"
×
430
            order_opening_credits = order_opening_credits + 1
×
431
            name_out = ""
×
NEW
432
            if self.json_dressing["opening_credits"] or self.json_dressing["ending_credits"]:
×
433
                name_out = "[video]"
×
434
            dressing_command_filter.append(
×
435
                FFMPEG_DRESSING_WATERMARK
436
                % {
437
                    "opacity": self.json_dressing.opacity / 100.0,
438
                    "position": get_dressing_position_value(self.json_dressing["position"], height),
439
                    "name_out": name_out,
440
                }
441
            )
NEW
442
        if self.json_dressing["opening_credits"]:
×
443
            order_opening_credits = order_opening_credits + 1
×
444
            number_concat = number_concat + 1
×
445
            dressing_command_params = (
×
446
                "[debut][" + str(order_opening_credits) + ":a]" + dressing_command_params
447
            )
448
            dressing_command_filter.append(
×
449
                FFMPEG_DRESSING_SCALE
450
                % {
451
                    "number": str(order_opening_credits),
452
                    "height": height,
453
                    "name": "debut",
454
                }
455
            )
NEW
456
        if self.json_dressing["ending_credits"]:
×
457
            number_concat = number_concat + 1
×
458
            dressing_command_params = (
×
459
                dressing_command_params
460
                + "[fin]["
461
                + str(order_opening_credits + 1)
462
                + ":a]"
463
            )
464
            dressing_command_filter.append(
×
465
                FFMPEG_DRESSING_SCALE
466
                % {
467
                    "number": str(order_opening_credits + 1),
468
                    "height": str(list(self.list_video_track.items())[0][1]["height"]),
469
                    "name": "fin",
470
                }
471
            )
NEW
472
        if self.json_dressing["opening_credits"] or self.json_dressing["ending_credits"]:
×
473
            dressing_command_filter.append(
×
474
                FFMPEG_DRESSING_CONCAT
475
                % {
476
                    "params": dressing_command_params,
477
                    "number": number_concat,
478
                }
479
            )
480

481
        dressing_command += FFMPEG_DRESSING_FILTER_COMPLEX % {
×
482
            "filter": ";".join(dressing_command_filter),
483
        }
484

NEW
485
        if self.json_dressing["opening_credits"] or self.json_dressing["ending_credits"]:
×
486
            dressing_command += " -map '[v]' -map '[a]' "
×
487

488
        output_file = self.get_dressing_file()
×
489
        dressing_command += FFMPEG_DRESSING_OUTPUT % {
×
490
            "output": output_file,
491
        }
492
        return dressing_command
×
493

494
    def encode_video_dressing(self):
1✔
495
        """Encode the dressed video."""
496
        dressing_command = self.get_dressing_command()
×
497
        return_value, return_msg = launch_cmd(dressing_command)
×
498
        self.add_encoding_log(
×
499
            "dressing_command", dressing_command, return_value, return_msg
500
        )
501
        self.video_file = self.get_dressing_file()
×
502

503
    def encode_video_part(self):
1✔
504
        """Encode the video part of a file."""
505
        mp4_command = self.get_mp4_command()
1✔
506
        return_value, return_msg = launch_cmd(mp4_command)
1✔
507
        self.add_encoding_log("mp4_command", mp4_command, return_value, return_msg)
1✔
508
        if not return_value:
1✔
509
            self.error_encoding = True
×
510
        if self.duration == 0:
1✔
511
            list_rendition = get_list_rendition()
×
512
            first_item = list_rendition.popitem(last=False)
×
513
            self.fix_duration(self.list_mp4_files[first_item[0]])
×
514
        hls_command = self.get_hls_command()
1✔
515
        return_value, return_msg = launch_cmd(hls_command)
1✔
516
        if return_value:
1✔
517
            self.create_main_livestream()
1✔
518
        self.add_encoding_log("hls_command", hls_command, return_value, return_msg)
1✔
519

520
    def create_main_livestream(self):
1✔
521
        list_rendition = get_list_rendition()
1✔
522
        livestream_content = ""
1✔
523
        for index, rend in enumerate(list_rendition):
1✔
524
            rend_livestream = os.path.join(
1✔
525
                self.get_output_dir(), "livestream%s.m3u8" % rend
526
            )
527
            if os.path.exists(rend_livestream):
1✔
528
                with open(rend_livestream, "r") as file:
1✔
529
                    data = file.read()
1✔
530
                if index == 0:
1✔
531
                    livestream_content += data
1✔
532
                else:
533
                    livestream_content += "\n".join(data.split("\n")[2:])
×
534
                os.remove(rend_livestream)
1✔
535
        livestream_file = open(
1✔
536
            os.path.join(self.get_output_dir(), "livestream.m3u8"), "w"
537
        )
538
        livestream_file.write(livestream_content.replace("\n\n", "\n"))
1✔
539
        livestream_file.close()
1✔
540

541
    def get_mp3_command(self) -> str:
1✔
542
        mp3_command = "%s " % FFMPEG_CMD
1✔
543
        mp3_command += FFMPEG_INPUT % {
1✔
544
            "input": self.video_file,
545
            "nb_threads": FFMPEG_NB_THREADS,
546
        }
547
        output_file = os.path.join(self.output_dir, "audio_%s.mp3" % FFMPEG_AUDIO_BITRATE)
1✔
548
        mp3_command += FFMPEG_MP3_ENCODE % {
1✔
549
            # "audio_bitrate": AUDIO_BITRATE,
550
            "cut": self.get_subtime(self.cutting_start, self.cutting_stop),
551
            "output": output_file,
552
        }
553
        self.list_mp3_files[FFMPEG_AUDIO_BITRATE] = output_file
1✔
554
        return mp3_command
1✔
555

556
    def get_m4a_command(self) -> str:
1✔
557
        m4a_command = "%s " % FFMPEG_CMD
1✔
558
        m4a_command += FFMPEG_INPUT % {
1✔
559
            "input": self.video_file,
560
            "nb_threads": FFMPEG_NB_THREADS,
561
        }
562
        output_file = os.path.join(self.output_dir, "audio_%s.m4a" % FFMPEG_AUDIO_BITRATE)
1✔
563
        m4a_command += FFMPEG_M4A_ENCODE % {
1✔
564
            "cut": self.get_subtime(self.cutting_start, self.cutting_stop),
565
            "audio_bitrate": FFMPEG_AUDIO_BITRATE,
566
            "output": output_file,
567
        }
568
        self.list_m4a_files[FFMPEG_AUDIO_BITRATE] = output_file
1✔
569
        return m4a_command
1✔
570

571
    def encode_audio_part(self):
1✔
572
        """Encode the audio part of a video."""
573
        mp3_command = self.get_mp3_command()
1✔
574
        return_value, return_msg = launch_cmd(mp3_command)
1✔
575
        self.add_encoding_log("mp3_command", mp3_command, return_value, return_msg)
1✔
576
        if self.duration == 0:
1✔
577
            new_k = list(self.list_mp3_files)[0]
×
578
            self.fix_duration(self.list_mp3_files[new_k])
×
579
        if not self.is_video():
1✔
580
            m4a_command = self.get_m4a_command()
1✔
581
            return_value, return_msg = launch_cmd(m4a_command)
1✔
582
            self.add_encoding_log("m4a_command", m4a_command, return_value, return_msg)
1✔
583

584
    def get_extract_thumbnail_command(self) -> str:
1✔
585
        thumbnail_command = "%s " % FFMPEG_CMD
×
586
        thumbnail_command += FFMPEG_INPUT % {
×
587
            "input": self.video_file,
588
            "nb_threads": FFMPEG_NB_THREADS,
589
        }
590
        for img in self.list_image_track:
×
591
            output_file = os.path.join(self.output_dir, "thumbnail_%s.png" % img)
×
592
            thumbnail_command += FFMPEG_EXTRACT_THUMBNAIL % {
×
593
                "index": img,
594
                "output": output_file,
595
            }
596
            self.list_thumbnail_files[img] = output_file
×
597
        return thumbnail_command
×
598

599
    def get_create_thumbnail_command(self) -> str:
1✔
600
        thumbnail_command = "%s " % FFMPEG_CMD
1✔
601
        first_item = self.get_first_item()
1✔
602
        input_file = self.list_mp4_files[first_item[0]]
1✔
603
        thumbnail_command += FFMPEG_INPUT % {
1✔
604
            "input": input_file,
605
            "nb_threads": FFMPEG_NB_THREADS,
606
        }
607
        output_file = os.path.join(self.output_dir, "thumbnail")
1✔
608
        thumbnail_command += FFMPEG_CREATE_THUMBNAIL % {
1✔
609
            "duration": self.duration,
610
            "nb_thumbnail": FFMPEG_NB_THUMBNAIL,
611
            "output": output_file,
612
        }
613
        for nb in range(0, FFMPEG_NB_THUMBNAIL):
1✔
614
            num_thumb = str(nb + 1)
1✔
615
            self.list_thumbnail_files[num_thumb] = "%s_000%s.png" % (
1✔
616
                output_file,
617
                num_thumb,
618
            )
619
        return thumbnail_command
1✔
620

621
    def get_first_item(self):
1✔
622
        """Get the first mp4 render from setting."""
623
        list_rendition = get_list_rendition()
1✔
624
        for rend in list_rendition.copy():
1✔
625
            if list_rendition[rend]["encode_mp4"] is False:
1✔
626
                list_rendition.pop(rend)
1✔
627
        if len(list_rendition) == 0:
1✔
628
            return None
×
629
        else:
630
            return list_rendition.popitem(last=False)
1✔
631

632
    def create_overview(self):
1✔
633
        first_item = self.get_first_item()
1✔
634
        # overview combine for 160x90
635
        in_height = list(self.list_video_track.items())[0][1]["height"]
1✔
636
        in_width = list(self.list_video_track.items())[0][1]["width"]
1✔
637
        image_height = 75  # decrease to 75 px instead of 90 due to montage overflow
1✔
638
        coef = in_height / image_height
1✔
639
        image_width = int(in_width / coef)
1✔
640
        input_file = self.list_mp4_files[first_item[0]]
1✔
641
        nb_img = 100
1✔
642
        step = 1
1✔
643
        if self.duration < 100:
1✔
644
            # nb_img = int(self.duration * 10 / 100)
645
            step = 10  # on ne fait que 10 images si la video dure moins de 100 sec.
1✔
646
        overviewimagefilename = os.path.join(self.output_dir, "overview.png")
1✔
647
        image_url = os.path.basename(overviewimagefilename)
1✔
648
        overviewfilename = os.path.join(self.output_dir, "overview.vtt")
1✔
649
        webvtt = WebVTT()
1✔
650
        for i in range(0, nb_img, step):
1✔
651
            # create overviewimagefilename for first pass
652
            output_file = (
1✔
653
                os.path.join(self.output_dir, "thumbnail_%s.png" % i)
654
                if i > 0
655
                else overviewimagefilename
656
            )
657
            cmd_ffmpegthumbnailer = (
1✔
658
                'ffmpegthumbnailer -t "%(stamp)s" '
659
                + '-s "%(image_width)s" -i %(source)s -c png '
660
                + "-o %(output_file)s "
661
            ) % {
662
                "stamp": str(i) + "%",
663
                "source": input_file,
664
                "output_file": output_file,
665
                "image_width": image_width,
666
            }
667
            return_value, return_msg = launch_cmd(cmd_ffmpegthumbnailer)
1✔
668
            # self.add_encoding_log(
669
            # "ffmpegthumbnailer_%s" % i, cmd_ffmpegthumbnailer, return_value, return_msg)
670
            if return_value and check_file(output_file) and i > 0:
1✔
671
                # print("MONTAGE")
672
                cmd_montage = (
1✔
673
                    "montage -geometry +0+0 %(overviewimagefilename)s \
674
                    %(output_file)s  %(overviewimagefilename)s"
675
                    % {
676
                        "overviewimagefilename": overviewimagefilename,
677
                        "output_file": output_file,
678
                    }
679
                )
680
                return_value, return_msg = launch_cmd(cmd_montage)
1✔
681
                if not return_value:
1✔
682
                    print("cmd_montage_%s" % i, cmd_montage, return_value, return_msg)
×
683
                # self.add_encoding_log
684
                # ("cmd_montage_%s" % i, cmd_montage, return_value, return_msg)
685
                os.remove(output_file)
1✔
686
            start = format(float(self.duration * i / 100), ".3f")
1✔
687
            end = format(float(self.duration * (i + step) / 100), ".3f")
1✔
688
            start_time = time.strftime(
1✔
689
                "%H:%M:%S", time.gmtime(int(str(start).split(".")[0]))
690
            )
691
            start_time += ".%s" % (str(start).split(".")[1])
1✔
692
            end_time = time.strftime(
1✔
693
                "%H:%M:%S", time.gmtime(int(str(end).split(".")[0]))
694
            ) + ".%s" % (str(end).split(".")[1])
695
            caption = Caption(
1✔
696
                "%s" % start_time,
697
                "%s" % end_time,
698
                "%s#xywh=%d,%d,%d,%d"
699
                % (image_url, image_width * (i / step), 0, image_width, image_height),
700
            )
701
            webvtt.captions.append(caption)
1✔
702
        webvtt.save(overviewfilename)
1✔
703
        if check_file(overviewfilename) and check_file(overviewimagefilename):
1✔
704
            self.list_overview_files["0"] = overviewimagefilename
1✔
705
            self.list_overview_files["1"] = overviewfilename
1✔
706
            # self.encoding_log += "\n- overviewfilename:\n%s" % overviewfilename
707
        else:
708
            self.add_encoding_log("create_overview", "", False, "")
×
709

710
    def encode_image_part(self):
1✔
711
        if len(self.list_image_track) > 0:
1✔
712
            thumbnail_command = self.get_extract_thumbnail_command()
×
713
            return_value, return_msg = launch_cmd(thumbnail_command)
×
714
            self.add_encoding_log(
×
715
                "extract_thumbnail_command", thumbnail_command, return_value, return_msg
716
            )
717
        elif self.is_video():
1✔
718
            thumbnail_command = self.get_create_thumbnail_command()
1✔
719
            return_value, return_msg = launch_cmd(thumbnail_command)
1✔
720
            self.add_encoding_log(
1✔
721
                "create_thumbnail_command", thumbnail_command, return_value, return_msg
722
            )
723
        # on ne fait pas d'overview pour les videos de moins de 10 secondes
724
        # (laisser les 10sec inclus pour laisser les tests passer) --> OK
725
        if self.is_video() and self.duration >= 10:
1✔
726
            self.create_overview()
1✔
727

728
    def get_extract_subtitle_command(self) -> str:
1✔
729
        subtitle_command = "%s " % FFMPEG_CMD
×
730
        subtitle_command += FFMPEG_INPUT % {
×
731
            "input": self.video_file,
732
            "nb_threads": FFMPEG_NB_THREADS,
733
        }
734
        for sub in self.list_subtitle_track:
×
735
            lang = self.list_subtitle_track[sub]["language"]
×
736
            output_file = os.path.join(self.output_dir, "subtitle_%s.vtt" % lang)
×
737
            subtitle_command += FFMPEG_EXTRACT_SUBTITLE % {
×
738
                "index": sub,
739
                "output": output_file,
740
            }
741
            self.list_subtitle_files[sub] = [lang, output_file]
×
742
        return subtitle_command
×
743

744
    def get_subtitle_part(self):
1✔
745
        if len(self.list_subtitle_track) > 0:
×
746
            subtitle_command = self.get_extract_subtitle_command()
×
747
            return_value, return_msg = launch_cmd(subtitle_command)
×
748
            self.add_encoding_log(
×
749
                "subtitle_command", subtitle_command, return_value, return_msg
750
            )
751

752
    def export_to_json(self):
1✔
753
        data_to_dump = {}
1✔
754
        for attribute, value in self.__dict__.items():
1✔
755
            data_to_dump[attribute] = value
1✔
756
        with open(self.output_dir + "/info_video.json", "w") as outfile:
1✔
757
            json.dump(data_to_dump, outfile, indent=2)
1✔
758

759
    def add_encoding_log(self, title, command, result, msg):
1✔
760
        """Add Encoding step to the encoding_log dict."""
761
        self.encoding_log[title] = {"command": command, "result": result, "msg": msg}
1✔
762
        if result is False and self.error_encoding is False:
1✔
763
            self.error_encoding = True
1✔
764

765
    def start_encode(self):
1✔
766
        self.start = time.ctime()
1✔
767
        self.create_output_dir()
1✔
768
        self.get_video_data()
1✔
769
        if self.json_dressing is not None:
1✔
770
            self.encode_video_dressing()
×
771
        print(self.id, self.video_file, self.duration)
1✔
772
        if self.is_video():
1✔
773
            self.encode_video_part()
1✔
774
        if len(self.list_audio_track) > 0:
1✔
775
            self.encode_audio_part()
1✔
776
        self.encode_image_part()
1✔
777
        if len(self.list_subtitle_track) > 0:
1✔
778
            self.get_subtitle_part()
×
779
        self.stop = time.ctime()
1✔
780
        self.export_to_json()
1✔
781

782

783
def fix_input(input) -> str:
1✔
784
    filename = ""
×
785
    if args.input.startswith("/"):
×
786
        path_file = args.input
×
787
    else:
788
        path_file = os.path.join(os.getcwd(), args.input)
×
789
    if os.access(path_file, os.F_OK) and os.stat(path_file).st_size > 0:
×
790
        # remove accent and space
791
        filename = "".join(
×
792
            (
793
                c
794
                for c in unicodedata.normalize("NFD", path_file)
795
                if unicodedata.category(c) != "Mn"
796
            )
797
        )
798
        filename = filename.replace(" ", "_")
×
799
        os.rename(
×
800
            path_file,
801
            filename,
802
        )
803
        print("Encoding file {} \n".format(filename))
×
804
    return filename
×
805

806

807
"""
808
  remote encode ???
809
"""
810
if __name__ == "__main__":
1✔
811
    start = "Start at: %s" % time.ctime()
×
812
    parser = argparse.ArgumentParser(description="Running encoding video.")
×
813
    parser.add_argument("--id", required=True, help="the ID of the video")
×
814
    parser.add_argument("--start", required=False, help="Start cut")
×
815
    parser.add_argument("--stop", required=False, help="Stop cut")
×
816
    parser.add_argument("--input", required=True, help="name of input file to encode")
×
817
    parser.add_argument("--dressing", required=False, help="Dressing for the video")
×
818

819
    args = parser.parse_args()
×
820
    print(args.start)
×
821
    filename = fix_input(args.input)
×
822
    encoding_video = Encoding_video(
×
823
        args.id, filename, args.start, args.stop, args.dressing
824
    )
825
    # error if uncommented
826
    # encoding_video.encoding_log += start
827
    # AttributeError: 'NoneType' object has no attribute 'get'
828
    encoding_video.start_encode()
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc