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

EsupPortail / Esup-Pod / 13951476187

19 Mar 2025 04:17PM UTC coverage: 70.106%. First build
13951476187

Pull #1280

github

web-flow
Merge ae6a8ec19 into 749de494a
Pull Request #1280: Replace credit_videofile by credit_video_dir

83 of 105 new or added lines in 12 files covered. (79.05%)

11984 of 17094 relevant lines covered (70.11%)

0.7 hits per line

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

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

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

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

92
__author__ = "Nicolas CAN <nicolas.can@univ-lille.fr>"
1✔
93
__license__ = "LGPL v3"
1✔
94

95
image_codec = ["jpeg", "gif", "png", "bmp", "jpg"]
1✔
96

97
"""
98
 - Get video source
99
 - get alls track from video source
100
 - encode tracks in HLS and mp4
101
 - save it
102
"""
103

104
try:
1✔
105
    from django.conf import settings
1✔
106

107
    FFMPEG_CMD = getattr(settings, "FFMPEG_CMD", FFMPEG_CMD)
1✔
108
    FFPROBE_CMD = getattr(settings, "FFPROBE_CMD", FFPROBE_CMD)
1✔
109
    FFPROBE_GET_INFO = getattr(settings, "FFPROBE_GET_INFO", FFPROBE_GET_INFO)
1✔
110
    FFMPEG_CRF = getattr(settings, "FFMPEG_CRF", FFMPEG_CRF)
1✔
111
    FFMPEG_PRESET = getattr(settings, "FFMPEG_PRESET", FFMPEG_PRESET)
1✔
112
    FFMPEG_PROFILE = getattr(settings, "FFMPEG_PROFILE", FFMPEG_PROFILE)
1✔
113
    FFMPEG_LEVEL = getattr(settings, "FFMPEG_LEVEL", FFMPEG_LEVEL)
1✔
114
    FFMPEG_HLS_TIME = getattr(settings, "FFMPEG_HLS_TIME", FFMPEG_HLS_TIME)
1✔
115
    FFMPEG_INPUT = getattr(settings, "FFMPEG_INPUT", FFMPEG_INPUT)
1✔
116
    FFMPEG_LIBX = getattr(settings, "FFMPEG_LIBX", FFMPEG_LIBX)
1✔
117
    FFMPEG_MP4_ENCODE = getattr(settings, "FFMPEG_MP4_ENCODE", FFMPEG_MP4_ENCODE)
1✔
118
    FFMPEG_HLS_COMMON_PARAMS = getattr(
1✔
119
        settings, "FFMPEG_HLS_COMMON_PARAMS", FFMPEG_HLS_COMMON_PARAMS
120
    )
121
    FFMPEG_HLS_ENCODE_PARAMS = getattr(
1✔
122
        settings, "FFMPEG_HLS_ENCODE_PARAMS", FFMPEG_HLS_ENCODE_PARAMS
123
    )
124
    FFMPEG_MP3_ENCODE = getattr(settings, "FFMPEG_MP3_ENCODE", FFMPEG_MP3_ENCODE)
1✔
125
    FFMPEG_M4A_ENCODE = getattr(settings, "FFMPEG_M4A_ENCODE", FFMPEG_M4A_ENCODE)
1✔
126
    FFMPEG_NB_THREADS = getattr(settings, "FFMPEG_NB_THREADS", FFMPEG_NB_THREADS)
1✔
127
    FFMPEG_AUDIO_BITRATE = getattr(settings, "FFMPEG_AUDIO_BITRATE", FFMPEG_AUDIO_BITRATE)
1✔
128
    FFMPEG_EXTRACT_THUMBNAIL = getattr(
1✔
129
        settings, "FFMPEG_EXTRACT_THUMBNAIL", FFMPEG_EXTRACT_THUMBNAIL
130
    )
131
    FFMPEG_NB_THUMBNAIL = getattr(settings, "FFMPEG_NB_THUMBNAIL", FFMPEG_NB_THUMBNAIL)
1✔
132
    FFMPEG_CREATE_THUMBNAIL = getattr(
1✔
133
        settings, "FFMPEG_CREATE_THUMBNAIL", FFMPEG_CREATE_THUMBNAIL
134
    )
135
    FFMPEG_EXTRACT_SUBTITLE = getattr(
1✔
136
        settings, "FFMPEG_EXTRACT_SUBTITLE", FFMPEG_EXTRACT_SUBTITLE
137
    )
138
    FFMPEG_DRESSING_INPUT = getattr(
1✔
139
        settings, "FFMPEG_DRESSING_INPUT", FFMPEG_DRESSING_INPUT
140
    )
141
    FFMPEG_DRESSING_OUTPUT = getattr(
1✔
142
        settings, "FFMPEG_DRESSING_OUTPUT", FFMPEG_DRESSING_OUTPUT
143
    )
144
    FFMPEG_DRESSING_WATERMARK = getattr(
1✔
145
        settings, "FFMPEG_DRESSING_WATERMARK", FFMPEG_DRESSING_WATERMARK
146
    )
147
    FFMPEG_DRESSING_FILTER_COMPLEX = getattr(
1✔
148
        settings, "FFMPEG_DRESSING_FILTER_COMPLEX", FFMPEG_DRESSING_FILTER_COMPLEX
149
    )
150
    FFMPEG_DRESSING_SCALE = getattr(
1✔
151
        settings, "FFMPEG_DRESSING_SCALE", FFMPEG_DRESSING_SCALE
152
    )
153
    FFMPEG_DRESSING_CONCAT = getattr(
1✔
154
        settings, "FFMPEG_DRESSING_CONCAT", FFMPEG_DRESSING_CONCAT
155
    )
156
    FFMPEG_DRESSING_SILENT = getattr(
1✔
157
        settings, "FFMPEG_DRESSING_SILENT", FFMPEG_DRESSING_SILENT
158
    )
159
    FFMPEG_DRESSING_AUDIO = getattr(
1✔
160
        settings, "FFMPEG_DRESSING_AUDIO", FFMPEG_DRESSING_AUDIO
161
    )
162
    DEBUG = getattr(settings, "DEBUG", True)
1✔
163
except ImportError:  # pragma: no cover
164
    DEBUG = True
165
    pass
166

167
logger = logging.getLogger(__name__)
1✔
168
if DEBUG:
1✔
169
    logger.setLevel(logging.DEBUG)
1✔
170

171

172
class Encoding_video:
1✔
173
    """Encoding video object."""
174

175
    id = 0
1✔
176
    video_file = ""
1✔
177
    duration = 0
1✔
178
    list_video_track = {}
1✔
179
    list_audio_track = {}
1✔
180
    list_subtitle_track = {}
1✔
181
    list_image_track = {}
1✔
182
    list_mp4_files = {}
1✔
183
    list_hls_files = {}
1✔
184
    list_mp3_files = {}
1✔
185
    list_m4a_files = {}
1✔
186
    list_thumbnail_files = {}
1✔
187
    list_overview_files = {}
1✔
188
    list_subtitle_files = {}
1✔
189
    encoding_log = {}
1✔
190
    output_dir = ""
1✔
191
    start = 0
1✔
192
    stop = 0
1✔
193
    error_encoding = False
1✔
194
    cutting_start = 0
1✔
195
    cutting_stop = 0
1✔
196
    json_dressing = None
1✔
197
    dressing_input = ""
1✔
198

199
    def __init__(
1✔
200
        self, id=0, video_file="", start=0, stop=0, json_dressing=None, dressing_input=""
201
    ) -> None:
202
        """Initialize a new Encoding_video object."""
203
        self.id = id
1✔
204
        self.video_file = video_file
1✔
205
        self.duration = 0
1✔
206
        self.list_video_track = {}
1✔
207
        self.list_audio_track = {}
1✔
208
        self.list_subtitle_track = {}
1✔
209
        self.list_image_track = {}
1✔
210
        self.list_mp4_files = {}
1✔
211
        self.list_hls_files = {}
1✔
212
        self.list_mp3_files = {}
1✔
213
        self.list_m4a_files = {}
1✔
214
        self.list_thumbnail_files = {}
1✔
215
        self.list_overview_files = {}
1✔
216
        self.encoding_log = {}
1✔
217
        self.list_subtitle_files = {}
1✔
218
        self.output_dir = ""
1✔
219
        self.start = 0
1✔
220
        self.stop = 0
1✔
221
        self.error_encoding = False
1✔
222
        self.cutting_start = start or 0
1✔
223
        self.cutting_stop = stop or 0
1✔
224
        self.json_dressing = json_dressing
1✔
225
        self.dressing_input = dressing_input
1✔
226

227
    def is_video(self) -> bool:
1✔
228
        """Check if current encoding correspond to a video."""
229
        return len(self.list_video_track) > 0
1✔
230

231
    def get_subtime(self, clip_begin, clip_end) -> str:
1✔
232
        subtime = ""
1✔
233
        if clip_begin != 0 or clip_end != 0:
1✔
234
            subtime += "-ss %s " % str(clip_begin) + "-to %s " % str(clip_end)
×
235
        return subtime
1✔
236

237
    def get_video_data(self) -> None:
1✔
238
        """Get alls tracks from video source and put it in object passed in parameter."""
239
        msg = "--> get_info_video\n"
1✔
240
        probe_cmd = FFPROBE_GET_INFO % {
1✔
241
            "ffprobe": FFPROBE_CMD,
242
            "select_streams": "",
243
            "source": '"' + self.video_file + '" ',
244
        }
245
        msg += probe_cmd + "\n"
1✔
246
        duration = 0
1✔
247
        info, return_msg = get_info_from_video(probe_cmd)
1✔
248
        msg += json.dumps(info, indent=2)
1✔
249
        msg += " \n"
1✔
250
        msg += return_msg + "\n"
1✔
251
        self.add_encoding_log("probe_cmd", probe_cmd, True, msg)
1✔
252
        try:
1✔
253
            duration = int(float("%s" % info["format"]["duration"]))
1✔
254
        except (RuntimeError, KeyError, AttributeError, ValueError, TypeError) as err:
×
255
            msg = "\nUnexpected error: {0}".format(err)
×
256
            self.add_encoding_log("duration", "", True, msg)
×
257
        if self.cutting_start != 0 or self.cutting_stop != 0:
1✔
258
            duration = self.cutting_stop - self.cutting_start
×
259
        self.duration = duration
1✔
260
        streams = info.get("streams", [])
1✔
261
        for stream in streams:
1✔
262
            self.add_stream(stream)
1✔
263

264
    def fix_duration(self, input_file) -> None:
1✔
265
        msg = "--> get_info_video\n"
×
266
        probe_cmd = 'ffprobe -v quiet -show_entries format=duration -hide_banner  \
×
267
                    -of default=noprint_wrappers=1:nokey=1 -print_format json -i \
268
                    "{}"'.format(
269
            input_file
270
        )
271
        info, return_msg = get_info_from_video(probe_cmd)
×
272
        msg += json.dumps(info, indent=2)
×
273
        msg += " \n"
×
274
        msg += return_msg + "\n"
×
275
        duration = 0
×
276
        try:
×
277
            duration = int(float("%s" % info["format"]["duration"]))
×
278
        except (RuntimeError, KeyError, AttributeError, ValueError, TypeError) as err:
×
279
            msg += "\nUnexpected error: {0}".format(err)
×
280
        self.add_encoding_log("fix_duration", "", True, msg)
×
281
        if self.cutting_start != 0 or self.cutting_stop != 0:
×
282
            duration = self.cutting_stop - self.cutting_start
×
283
        self.duration = duration
×
284

285
    def add_stream(self, stream):
1✔
286
        codec_type = stream.get("codec_type", "unknown")
1✔
287
        # https://ffmpeg.org/doxygen/3.2/group__lavu__misc.html#ga9a84bba4713dfced21a1a56163be1f48
288
        if codec_type == "audio":
1✔
289
            codec = stream.get("codec_name", "unknown")
1✔
290
            self.list_audio_track["%s" % stream.get("index")] = {
1✔
291
                "sample_rate": stream.get("sample_rate", 0),
292
                "channels": stream.get("channels", 0),
293
            }
294
        if codec_type == "video":
1✔
295
            codec = stream.get("codec_name", "unknown")
1✔
296
            if any(ext in codec.lower() for ext in image_codec):
1✔
297
                self.list_image_track["%s" % stream.get("index")] = {
×
298
                    "width": stream.get("width", 0),
299
                    "height": stream.get("height", 0),
300
                }
301
            else:
302
                self.list_video_track["%s" % stream.get("index")] = {
1✔
303
                    "width": stream.get("width", 0),
304
                    "height": stream.get("height", 0),
305
                }
306
        if codec_type == "subtitle":
1✔
307
            codec = stream.get("codec_name", "unknown")
×
308
            language = ""
×
309
            if stream.get("tags"):
×
310
                language = stream.get("tags").get("language", "")
×
311
            self.list_subtitle_track["%s" % stream.get("index")] = {"language": language}
×
312

313
    def get_output_dir(self) -> str:
1✔
314
        dirname = os.path.dirname(self.video_file)
1✔
315
        return os.path.join(dirname, "%04d" % int(self.id))
1✔
316

317
    def create_output_dir(self) -> None:
1✔
318
        output_dir = self.get_output_dir()
1✔
319
        if not os.path.exists(output_dir):
1✔
320
            os.makedirs(output_dir)
1✔
321
        self.output_dir = output_dir
1✔
322

323
    def get_mp4_command(self) -> str:
1✔
324
        mp4_command = "%s " % FFMPEG_CMD
1✔
325
        list_rendition = get_list_rendition()
1✔
326
        # remove rendition if encode_mp4 == False
327
        for rend in list_rendition.copy():
1✔
328
            if list_rendition[rend]["encode_mp4"] is False:
1✔
329
                list_rendition.pop(rend)
1✔
330
        if len(list_rendition) == 0:
1✔
331
            return ""
×
332
        first_item = list_rendition.popitem(last=False)
1✔
333
        mp4_command += FFMPEG_INPUT % {
1✔
334
            "input": self.video_file,
335
            "nb_threads": FFMPEG_NB_THREADS,
336
        }
337
        output_file = os.path.join(self.output_dir, "%sp.mp4" % first_item[0])
1✔
338
        mp4_command += FFMPEG_MP4_ENCODE % {
1✔
339
            "cut": self.get_subtime(self.cutting_start, self.cutting_stop),
340
            "map_audio": "-map 0:a:0" if len(self.list_audio_track) > 0 else "",
341
            "libx": FFMPEG_LIBX,
342
            "height": first_item[0],
343
            "preset": FFMPEG_PRESET,
344
            "profile": FFMPEG_PROFILE,
345
            "level": FFMPEG_LEVEL,
346
            "crf": FFMPEG_CRF,
347
            "maxrate": first_item[1]["maxrate"],
348
            "bufsize": first_item[1]["maxrate"],
349
            "ba": first_item[1]["audio_bitrate"],
350
            "output": output_file,
351
        }
352
        self.list_mp4_files[first_item[0]] = output_file
1✔
353
        """
354
        il est possible de faire ainsi :
355
        mp4_command += FFMPEG_MP4_ENCODE.format(
356
            height=first_item[0],
357
            [...]
358
        )
359
        """
360
        in_height = list(self.list_video_track.items())[0][1]["height"]
1✔
361
        for rend in list_rendition:
1✔
362
            resolution_threshold = rend - rend * (
1✔
363
                list_rendition[rend]["encoding_resolution_threshold"] / 100
364
            )
365
            if in_height >= resolution_threshold:
1✔
366
                output_file = os.path.join(self.output_dir, "%sp.mp4" % rend)
×
367
                mp4_command += FFMPEG_MP4_ENCODE % {
×
368
                    "cut": self.get_subtime(self.cutting_start, self.cutting_stop),
369
                    "map_audio": "-map 0:a:0" if len(self.list_audio_track) > 0 else "",
370
                    "libx": FFMPEG_LIBX,
371
                    "height": min(rend, in_height),
372
                    "preset": FFMPEG_PRESET,
373
                    "profile": FFMPEG_PROFILE,
374
                    "level": FFMPEG_LEVEL,
375
                    "crf": FFMPEG_CRF,
376
                    "maxrate": list_rendition[rend]["maxrate"],
377
                    "bufsize": list_rendition[rend]["maxrate"],
378
                    "ba": list_rendition[rend]["audio_bitrate"],
379
                    "output": output_file,
380
                }
381
                self.list_mp4_files[rend] = output_file
×
382
        return mp4_command
1✔
383

384
    def get_hls_command(self) -> str:
1✔
385
        hls_command = "%s " % FFMPEG_CMD
1✔
386
        list_rendition = get_list_rendition()
1✔
387
        hls_command += FFMPEG_INPUT % {
1✔
388
            "input": self.video_file,
389
            "nb_threads": FFMPEG_NB_THREADS,
390
        }
391
        hls_common_params = FFMPEG_HLS_COMMON_PARAMS % {
1✔
392
            "cut": self.get_subtime(self.cutting_start, self.cutting_stop),
393
            "libx": FFMPEG_LIBX,
394
            "preset": FFMPEG_PRESET,
395
            "profile": FFMPEG_PROFILE,
396
            "level": FFMPEG_LEVEL,
397
            "crf": FFMPEG_CRF,
398
        }
399
        hls_command += hls_common_params
1✔
400
        in_height = list(self.list_video_track.items())[0][1]["height"]
1✔
401
        for index, rend in enumerate(list_rendition):
1✔
402
            resolution_threshold = rend - rend * (
1✔
403
                list_rendition[rend]["encoding_resolution_threshold"] / 100
404
            )
405
            if in_height >= resolution_threshold or index == 0:
1✔
406
                output_file = os.path.join(self.output_dir, "%sp.m3u8" % rend)
1✔
407
                hls_command += hls_common_params
1✔
408
                hls_command += FFMPEG_HLS_ENCODE_PARAMS % {
1✔
409
                    "height": min(rend, in_height),
410
                    "maxrate": list_rendition[rend]["maxrate"],
411
                    "bufsize": list_rendition[rend]["maxrate"],
412
                    "ba": list_rendition[rend]["audio_bitrate"],
413
                    "hls_time": FFMPEG_HLS_TIME,
414
                    "output": output_file,
415
                }
416
                self.list_hls_files[rend] = output_file
1✔
417
        return hls_command
1✔
418

419
    def get_dressing_file(self) -> str:
1✔
420
        """Create or replace the dressed video file."""
421
        dirname = os.path.dirname(self.video_file)
×
422
        filename, ext = os.path.splitext(os.path.basename(self.video_file))
×
423
        output_file = os.path.join(dirname, filename + "_dressing" + ext)
×
424
        return output_file
×
425

426
    def get_dressing_command(self) -> str:
1✔
427
        """
428
        Generate the FFMPEG command based on the dressing object parameters.
429

430
        Returns:
431
            A string representing the complete FFMPEG command.
432
        """
433
        height = str(list(self.list_video_track.items())[0][1]["height"])
×
434
        dressing_command = f"{FFMPEG_CMD} "
×
435
        dressing_command += FFMPEG_INPUT % {
×
436
            "input": self.video_file,
437
            "nb_threads": FFMPEG_NB_THREADS,
438
        }
439

440
        dressing_command += self.dressing_input
×
441

442
        # Handle opening and ending credits
443
        dressing_command += self.handle_dressing_credits()
×
444

445
        # Apply filters
446
        dressing_command_filter, dressing_command_params = self.build_dressing_filters(
×
447
            height
448
        )
449

450
        dressing_command += FFMPEG_DRESSING_FILTER_COMPLEX % {
×
451
            "filter": ";".join(dressing_command_filter),
452
        }
453

454
        if self.json_dressing.get("opening_credits") or self.json_dressing.get(
×
455
            "ending_credits"
456
        ):
457
            dressing_command += " -map '[v]' -map '[a]' "
×
458

459
        output_file = self.get_dressing_file()
×
460
        dressing_command += FFMPEG_DRESSING_OUTPUT % {"output": output_file}
×
461

462
        return dressing_command
×
463

464
    def handle_dressing_credits(self) -> str:
1✔
465
        """
466
        Handle the addition of opening and ending credits to the command.
467

468
        Returns:
469
            A string with the FFMPEG commands for silent credits if required.
470
        """
471
        command = ""
×
472
        for credit_type in ["opening_credits", "ending_credits"]:
×
473
            if self.json_dressing.get(credit_type):
×
474
                has_audio_key = f"{credit_type}_video_hasaudio"
×
475
                duration_key = f"{credit_type}_video_duration"
×
476

477
                if not self.json_dressing.get(has_audio_key):
×
478
                    command += FFMPEG_DRESSING_SILENT % {
×
479
                        "duration": self.json_dressing[duration_key],
480
                    }
481
        return command
×
482

483
    def build_dressing_filters(self, height: str):
1✔
484
        """
485
        Build the filters for video processing.
486

487
        Args:
488
            height: The height of the video for scaling purposes.
489

490
        Returns:
491
            A tuple containing the list of filters and the filter parameters.
492
        """
493
        filters = []
×
494
        params = ""
×
495
        order = 0
×
496
        interval_silent = 0
×
497
        concat_number = 1
×
498

499
        # Base video track
500
        filters.append(
×
501
            FFMPEG_DRESSING_SCALE % {"number": "0", "height": height, "name": "vid"}
502
        )
503
        params = "[vid][0:a]"
×
504
        order = order + 1
×
505

506
        # Watermark if present
507
        if self.json_dressing.get("watermark"):
×
508
            filters.append(self.apply_dressing_watermark(height))
×
509
            params = "[video][0:a]"
×
510
            order = order + 1
×
511

512
        interval_silent = order
×
513
        # Opening credits
514
        if self.json_dressing.get("opening_credits"):
×
515
            if self.json_dressing.get("ending_credits"):
×
516
                interval_silent = interval_silent + 1
×
517
            filters, params, interval_silent = self.add_dressing_credits(
×
518
                filters,
519
                params,
520
                height,
521
                "opening_credits",
522
                "debut",
523
                order,
524
                interval_silent,
525
            )
526
            order = order + 1
×
527
            concat_number = concat_number + 1
×
528

529
        # Ending credits
530
        if self.json_dressing.get("ending_credits"):
×
531
            filters, params, interval_silent = self.add_dressing_credits(
×
532
                filters, params, height, "ending_credits", "fin", order, interval_silent
533
            )
534
            concat_number = concat_number + 1
×
535

536
        # Concatenate if needed
537
        if self.json_dressing.get("opening_credits") or self.json_dressing.get(
×
538
            "ending_credits"
539
        ):
540
            filters.append(
×
541
                FFMPEG_DRESSING_CONCAT % {"params": params, "number": concat_number}
542
            )
543

544
        return filters, params
×
545

546
    def apply_dressing_watermark(self, height: str) -> str:
1✔
547
        """
548
        Apply the watermark to the video.
549

550
        Args:
551
            height: The height of the video to position the watermark correctly.
552

553
        Returns:
554
            A string representing the FFMPEG command for applying the watermark.
555
        """
556
        opacity = self.json_dressing["opacity"] / 100.0
×
557
        position = get_dressing_position_value(
×
558
            self.json_dressing["position_orig"], height
559
        )
560
        name_out = (
×
561
            "[video]"
562
            if self.json_dressing.get("opening_credits")
563
            or self.json_dressing.get("ending_credits")
564
            else ""
565
        )
566

567
        return FFMPEG_DRESSING_WATERMARK % {
×
568
            "opacity": opacity,
569
            "position": position,
570
            "name_out": name_out,
571
        }
572

573
    def add_dressing_credits(
1✔
574
        self,
575
        filters: list,
576
        params: str,
577
        height: str,
578
        credit_type: str,
579
        name: str,
580
        order: str,
581
        interval_silent: str,
582
    ):
583
        """
584
        Add opening or ending credits to the FFmpeg command by updating the filters and parameters.
585

586
        Args:
587
            filters (list): A list of existing FFmpeg filters to which new filters will be appended.
588
            params (str): The current filter parameters string that will be updated to include the credits.
589
            height (str): The height of the video used for scaling the credit overlay.
590
            credit_type (str): Specifies the type of credits to add, either 'opening_credits' or 'ending_credits'.
591
            name (str): The identifier for the credit video or overlay to be used in the FFmpeg filter graph.
592
            order (str): The position identifier for the audio stream, used to sync audio with the credits.
593
            interval_silent (str): Counter indicating the number of silent audio intervals inserted, used when adding silent audio tracks.
594

595
        Returns:
596
            tuple:
597
                - Updated list of filters with the added credit filters.
598
                - Updated filter parameter string reflecting the new credit positioning.
599
                - Updated interval_silent value if a silent audio track was added.
600
        """
601
        audio_out = f"{order}:a"
×
602

603
        if not self.json_dressing.get(f"{credit_type}_video_hasaudio"):
×
604
            audio_out = f"a{order}"
×
605
            filters.append(
×
606
                FFMPEG_DRESSING_AUDIO
607
                % {
608
                    "param_in": f"{interval_silent + 1}:a",
609
                    "param_out": audio_out,
610
                }
611
            )
612
            interval_silent = interval_silent + 1
×
613

614
        if credit_type == "opening_credits":
×
615
            params = f"[{name}][{audio_out}]{params}"
×
616
        else:
617
            params = f"{params}[{name}][{audio_out}]"
×
618

619
        filters.append(
×
620
            FFMPEG_DRESSING_SCALE % {"number": str(order), "height": height, "name": name}
621
        )
622

623
        return filters, params, interval_silent
×
624

625
    def encode_video_dressing(self) -> None:
1✔
626
        """Encode the dressed video."""
627
        dressing_command = self.get_dressing_command()
×
628
        return_value, return_msg = launch_cmd(dressing_command)
×
629
        self.add_encoding_log(
×
630
            "dressing_command", dressing_command, return_value, return_msg
631
        )
632
        self.video_file = self.get_dressing_file()
×
633

634
    def encode_video_part(self) -> None:
1✔
635
        """Encode the video part of a file."""
636
        mp4_command = self.get_mp4_command()
1✔
637
        return_value, return_msg = launch_cmd(mp4_command)
1✔
638
        self.add_encoding_log("mp4_command", mp4_command, return_value, return_msg)
1✔
639
        if not return_value:
1✔
640
            self.error_encoding = True
×
641
        if self.duration == 0:
1✔
642
            list_rendition = get_list_rendition()
×
643
            first_item = list_rendition.popitem(last=False)
×
644
            self.fix_duration(self.list_mp4_files[first_item[0]])
×
645
        hls_command = self.get_hls_command()
1✔
646
        return_value, return_msg = launch_cmd(hls_command)
1✔
647
        if return_value:
1✔
648
            self.create_main_livestream()
1✔
649
        self.add_encoding_log("hls_command", hls_command, return_value, return_msg)
1✔
650

651
    def create_main_livestream(self) -> None:
1✔
652
        list_rendition = get_list_rendition()
1✔
653
        livestream_content = ""
1✔
654
        for index, rend in enumerate(list_rendition):
1✔
655
            rend_livestream = os.path.join(
1✔
656
                self.get_output_dir(), "livestream%s.m3u8" % rend
657
            )
658
            if os.path.exists(rend_livestream):
1✔
659
                with open(rend_livestream, "r") as file:
1✔
660
                    data = file.read()
1✔
661
                if index == 0:
1✔
662
                    livestream_content += data
1✔
663
                else:
664
                    livestream_content += "\n".join(data.split("\n")[2:])
×
665
                os.remove(rend_livestream)
1✔
666
        livestream_file = open(
1✔
667
            os.path.join(self.get_output_dir(), "livestream.m3u8"), "w"
668
        )
669
        livestream_file.write(livestream_content.replace("\n\n", "\n"))
1✔
670
        livestream_file.close()
1✔
671

672
    def get_mp3_command(self) -> str:
1✔
673
        mp3_command = "%s " % FFMPEG_CMD
1✔
674
        mp3_command += FFMPEG_INPUT % {
1✔
675
            "input": self.video_file,
676
            "nb_threads": FFMPEG_NB_THREADS,
677
        }
678
        output_file = os.path.join(self.output_dir, "audio_%s.mp3" % FFMPEG_AUDIO_BITRATE)
1✔
679
        mp3_command += FFMPEG_MP3_ENCODE % {
1✔
680
            # "audio_bitrate": AUDIO_BITRATE,
681
            "cut": self.get_subtime(self.cutting_start, self.cutting_stop),
682
            "output": output_file,
683
        }
684
        self.list_mp3_files[FFMPEG_AUDIO_BITRATE] = output_file
1✔
685
        return mp3_command
1✔
686

687
    def get_m4a_command(self) -> str:
1✔
688
        m4a_command = "%s " % FFMPEG_CMD
1✔
689
        m4a_command += FFMPEG_INPUT % {
1✔
690
            "input": self.video_file,
691
            "nb_threads": FFMPEG_NB_THREADS,
692
        }
693
        output_file = os.path.join(self.output_dir, "audio_%s.m4a" % FFMPEG_AUDIO_BITRATE)
1✔
694
        m4a_command += FFMPEG_M4A_ENCODE % {
1✔
695
            "cut": self.get_subtime(self.cutting_start, self.cutting_stop),
696
            "audio_bitrate": FFMPEG_AUDIO_BITRATE,
697
            "output": output_file,
698
        }
699
        self.list_m4a_files[FFMPEG_AUDIO_BITRATE] = output_file
1✔
700
        return m4a_command
1✔
701

702
    def encode_audio_part(self) -> None:
1✔
703
        """Encode the audio part of a video."""
704
        mp3_command = self.get_mp3_command()
1✔
705
        return_value, return_msg = launch_cmd(mp3_command)
1✔
706
        self.add_encoding_log("mp3_command", mp3_command, return_value, return_msg)
1✔
707
        if self.duration == 0:
1✔
708
            new_k = list(self.list_mp3_files)[0]
×
709
            self.fix_duration(self.list_mp3_files[new_k])
×
710
        if not self.is_video():
1✔
711
            m4a_command = self.get_m4a_command()
1✔
712
            return_value, return_msg = launch_cmd(m4a_command)
1✔
713
            self.add_encoding_log("m4a_command", m4a_command, return_value, return_msg)
1✔
714

715
    def get_extract_thumbnail_command(self) -> str:
1✔
716
        thumbnail_command = "%s " % FFMPEG_CMD
×
717
        thumbnail_command += FFMPEG_INPUT % {
×
718
            "input": self.video_file,
719
            "nb_threads": FFMPEG_NB_THREADS,
720
        }
721
        for img in self.list_image_track:
×
722
            output_file = os.path.join(self.output_dir, "thumbnail_%s.png" % img)
×
723
            thumbnail_command += FFMPEG_EXTRACT_THUMBNAIL % {
×
724
                "index": img,
725
                "output": output_file,
726
            }
727
            self.list_thumbnail_files[img] = output_file
×
728
        return thumbnail_command
×
729

730
    def get_create_thumbnail_command(self) -> str:
1✔
731
        thumbnail_command = "%s " % FFMPEG_CMD
1✔
732
        first_item = self.get_first_item()
1✔
733
        input_file = self.list_mp4_files[first_item[0]]
1✔
734
        thumbnail_command += FFMPEG_INPUT % {
1✔
735
            "input": input_file,
736
            "nb_threads": FFMPEG_NB_THREADS,
737
        }
738
        output_file = os.path.join(self.output_dir, "thumbnail")
1✔
739
        thumbnail_command += FFMPEG_CREATE_THUMBNAIL % {
1✔
740
            "duration": self.duration,
741
            "nb_thumbnail": FFMPEG_NB_THUMBNAIL,
742
            "output": output_file,
743
        }
744
        for nb in range(0, FFMPEG_NB_THUMBNAIL):
1✔
745
            num_thumb = str(nb + 1)
1✔
746
            self.list_thumbnail_files[num_thumb] = "%s_000%s.png" % (
1✔
747
                output_file,
748
                num_thumb,
749
            )
750
        return thumbnail_command
1✔
751

752
    def get_first_item(self):
1✔
753
        """Get the first mp4 render from setting."""
754
        list_rendition = get_list_rendition()
1✔
755
        for rend in list_rendition.copy():
1✔
756
            if list_rendition[rend]["encode_mp4"] is False:
1✔
757
                list_rendition.pop(rend)
1✔
758
        if len(list_rendition) == 0:
1✔
759
            return None
×
760
        else:
761
            return list_rendition.popitem(last=False)
1✔
762

763
    def create_overview(self) -> None:
1✔
764
        first_item = self.get_first_item()
1✔
765
        # overview combine for 160x90
766
        in_height = list(self.list_video_track.items())[0][1]["height"]
1✔
767
        in_width = list(self.list_video_track.items())[0][1]["width"]
1✔
768
        image_height = 90
1✔
769
        coef = in_height / image_height
1✔
770
        image_width = int(in_width / coef)
1✔
771
        input_file = self.list_mp4_files[first_item[0]]
1✔
772
        nb_img = 100 if self.duration >= 100 else 10
1✔
773

774
        overviewimagefilename = os.path.join(self.output_dir, "overview.png")
1✔
775
        overview_image_command = (
1✔
776
            FFMPEG_CMD
777
            + " "
778
            + FFMPEG_INPUT
779
            % {
780
                "input": input_file,
781
                "nb_threads": FFMPEG_NB_THREADS,
782
            }
783
            + FFMPEG_CREATE_OVERVIEW
784
            % {
785
                "duration": self.duration,
786
                "image_count": nb_img,
787
                "width": image_width,
788
                "height": image_height,
789
                "output": overviewimagefilename,
790
            }
791
        )
792
        return_value, output_message = launch_cmd(overview_image_command)
1✔
793
        if not return_value or not check_file(overviewimagefilename):
1✔
NEW
794
            logger.error(f"FFmpeg failed with output: {output_message}")
×
795

796
        overviewfilename = os.path.join(self.output_dir, "overview.vtt")
1✔
797
        image_url = os.path.basename(overviewimagefilename)
1✔
798
        webvtt = WebVTT()
1✔
799
        for i in range(0, nb_img):
1✔
800
            start = format(float(self.duration * i / nb_img), ".3f")
1✔
801
            end = format(float(self.duration * (i + 1) / nb_img), ".3f")
1✔
802
            start_time = time.strftime(
1✔
803
                "%H:%M:%S", time.gmtime(int(str(start).split(".")[0]))
804
            )
805
            start_time += ".%s" % (str(start).split(".")[1])
1✔
806
            end_time = time.strftime(
1✔
807
                "%H:%M:%S", time.gmtime(int(str(end).split(".")[0]))
808
            ) + ".%s" % (str(end).split(".")[1])
809
            caption = Caption(
1✔
810
                "%s" % start_time,
811
                "%s" % end_time,
812
                "%s#xywh=%d,%d,%d,%d"
813
                % (image_url, image_width * i, 0, image_width, image_height),
814
            )
815
            webvtt.captions.append(caption)
1✔
816
        webvtt.save(overviewfilename)
1✔
817
        if check_file(overviewfilename) and check_file(overviewimagefilename):
1✔
818
            self.list_overview_files["0"] = overviewimagefilename
1✔
819
            self.list_overview_files["1"] = overviewfilename
1✔
820
            # self.encoding_log += "\n- overviewfilename:\n%s" % overviewfilename
821
        else:
822
            self.add_encoding_log("create_overview", "", False, "")
×
823

824
    def encode_image_part(self) -> None:
1✔
825
        if len(self.list_image_track) > 0:
1✔
826
            thumbnail_command = self.get_extract_thumbnail_command()
×
827
            return_value, return_msg = launch_cmd(thumbnail_command)
×
828
            self.add_encoding_log(
×
829
                "extract_thumbnail_command", thumbnail_command, return_value, return_msg
830
            )
831
        elif self.is_video():
1✔
832
            thumbnail_command = self.get_create_thumbnail_command()
1✔
833
            return_value, return_msg = launch_cmd(thumbnail_command)
1✔
834
            self.add_encoding_log(
1✔
835
                "create_thumbnail_command", thumbnail_command, return_value, return_msg
836
            )
837
        # on ne fait pas d'overview pour les videos de moins de 10 secondes
838
        # (laisser les 10sec inclus pour laisser les tests passer) --> OK
839
        if self.is_video() and self.duration >= 10:
1✔
840
            self.create_overview()
1✔
841

842
    def get_extract_subtitle_command(self) -> str:
1✔
843
        subtitle_command = "%s " % FFMPEG_CMD
×
844
        subtitle_command += FFMPEG_INPUT % {
×
845
            "input": self.video_file,
846
            "nb_threads": FFMPEG_NB_THREADS,
847
        }
848
        for sub in self.list_subtitle_track:
×
849
            lang = self.list_subtitle_track[sub]["language"]
×
850
            output_file = os.path.join(self.output_dir, "subtitle_%s.vtt" % lang)
×
851
            subtitle_command += FFMPEG_EXTRACT_SUBTITLE % {
×
852
                "index": sub,
853
                "output": output_file,
854
            }
855
            self.list_subtitle_files[sub] = [lang, output_file]
×
856
        return subtitle_command
×
857

858
    def get_subtitle_part(self) -> None:
1✔
859
        if len(self.list_subtitle_track) > 0:
×
860
            subtitle_command = self.get_extract_subtitle_command()
×
861
            return_value, return_msg = launch_cmd(subtitle_command)
×
862
            self.add_encoding_log(
×
863
                "subtitle_command", subtitle_command, return_value, return_msg
864
            )
865

866
    def export_to_json(self) -> None:
1✔
867
        data_to_dump = {}
1✔
868
        for attribute, value in self.__dict__.items():
1✔
869
            data_to_dump[attribute] = value
1✔
870
        with open(self.output_dir + "/info_video.json", "w") as outfile:
1✔
871
            json.dump(data_to_dump, outfile, indent=2)
1✔
872

873
    def add_encoding_log(self, title, command, result, msg) -> None:
1✔
874
        """Add Encoding step to the encoding_log dict."""
875
        self.encoding_log[title] = {"command": command, "result": result, "msg": msg}
1✔
876
        if result is False and self.error_encoding is False:
1✔
877
            self.error_encoding = True
×
878

879
    def start_encode(self) -> None:
1✔
880
        self.start = time.ctime()
1✔
881
        self.create_output_dir()
1✔
882
        self.get_video_data()
1✔
883
        if self.json_dressing is not None:
1✔
884
            self.encode_video_dressing()
×
885
        logger.info(
1✔
886
            "start_encode {id: %s, file: %s, duration: %s}"
887
            % (self.id, self.video_file, self.duration)
888
        )
889
        if self.is_video():
1✔
890
            logger.debug("* encode_video_part")
1✔
891
            self.encode_video_part()
1✔
892
        if len(self.list_audio_track) > 0:
1✔
893
            logger.debug("* encode_audio_part")
1✔
894
            self.encode_audio_part()
1✔
895
        logger.debug("* encode_image_part")
1✔
896
        self.encode_image_part()
1✔
897
        if len(self.list_subtitle_track) > 0:
1✔
NEW
898
            logger.debug("* get_subtitle_part")
×
899
            self.get_subtitle_part()
×
900
        self.stop = time.ctime()
1✔
901
        self.export_to_json()
1✔
902

903

904
def fix_input(input) -> str:
1✔
905
    filename = ""
×
906
    if args.input.startswith("/"):
×
907
        path_file = args.input
×
908
    else:
909
        path_file = os.path.join(os.getcwd(), args.input)
×
910
    if os.access(path_file, os.F_OK) and os.stat(path_file).st_size > 0:
×
911
        # remove accent and space
912
        filename = "".join(
×
913
            (
914
                c
915
                for c in unicodedata.normalize("NFD", path_file)
916
                if unicodedata.category(c) != "Mn"
917
            )
918
        )
919
        filename = filename.replace(" ", "_")
×
920
        os.rename(
×
921
            path_file,
922
            filename,
923
        )
NEW
924
        logger.info("Encoding file {} \n".format(filename))
×
925
    return filename
×
926

927

928
"""
929
  remote encode???
930
"""
931
if __name__ == "__main__":
1✔
932
    start = "Start at: %s" % time.ctime()
×
933
    parser = argparse.ArgumentParser(description="Running encoding video.")
×
934
    parser.add_argument("--id", required=True, help="the ID of the video")
×
935
    parser.add_argument("--start", required=False, help="Start cut")
×
936
    parser.add_argument("--stop", required=False, help="Stop cut")
×
937
    parser.add_argument("--input", required=True, help="name of input file to encode")
×
938
    parser.add_argument("--dressing", required=False, help="Dressing for the video")
×
939

940
    args = parser.parse_args()
×
NEW
941
    logger.debug(args.start)
×
942
    filename = fix_input(args.input)
×
943
    encoding_video = Encoding_video(
×
944
        args.id, filename, args.start, args.stop, args.dressing
945
    )
946
    # error if uncommented
947
    # encoding_video.encoding_log += start
948
    # AttributeError: 'NoneType' object has no attribute 'get'
949
    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

© 2025 Coveralls, Inc