Debian Codegraph @

subprojects/clapper-enhancers/src/yt-dlp/clapper_yt_dlp_hls.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 # Clapper Enhancer yt-dlp
2 # Copyright (C) 2024 Rafał Dzięgiel <[email protected]m>
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License, or (at your option) any later version.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, see
16 # <https://www.gnu.org/licenses/>.
17
18 import io
19
20 def _add_x_media(manifest, fmt):
21 acodec = None if fmt['acodec'] == 'none' else fmt['acodec']
22 media_type = 'AUDIO' if acodec else 'CLOSED-CAPTIONS'
23
24 manifest.write(f'\n#EXT-X-MEDIA:TYPE={media_type}')
25
26 fmt_id = fmt['format_id'].split('-')[0]
27 manifest.write(f',GROUP-ID="{fmt_id}"')
28
29 is_default = 'YES'
30
31 # NOTE: GStreamer expects variants of single language to have the same NAME
32 if ((language := fmt.get('language')) and language != 'none'):
33 # Convert to ISO-639
34 lang = language.split('-')[0]
35 manifest.write(f',LANGUAGE="{lang}"')
36 manifest.write(f',NAME="{language}"')
37 is_default = 'YES' if (fmt.get('language_preference') or 0) > 0 else 'NO'
38 else:
39 manifest.write(f',NAME="Default"')
40
41 manifest.write(f',DEFAULT={is_default},AUTOSELECT=YES')
42
43 url = fmt['url']
44 manifest.write(f',URI="{url}"')
45
46 def _add_x_stream_inf(manifest, fmt, audio, captions):
47 # Existence ensured before calling this function
48 bandwidth = int(fmt['tbr'] * 1000)
49 manifest.write(f'\n#EXT-X-STREAM-INF:BANDWIDTH={bandwidth}')
50
51 vcodec = None if fmt['vcodec'] == 'none' else fmt['vcodec']
52 acodec = None if fmt['acodec'] == 'none' else fmt['acodec']
53
54 if not acodec and audio:
55 acodec = None if audio['acodec'] == 'none' else audio['acodec']
56
57 if vcodec and acodec:
58 manifest.write(f',CODECS="{vcodec},{acodec}"')
59 else:
60 codec = vcodec if vcodec else acodec
61 manifest.write(f',CODECS="{codec}"')
62
63 width = fmt.get('width') or 0
64 height = fmt.get('height') or 0
65 if width > 0 and height > 0:
66 manifest.write(f',RESOLUTION={width}x{height}')
67
68 if ((fps := fmt.get('fps') or 0) > 0):
69 manifest.write(f',FRAME-RATE={fps}')
70
71 if (dyn_range := fmt.get('dynamic_range')):
72 manifest.write(f',VIDEO-RANGE={dyn_range}')
73
74 if vcodec and audio:
75 audio_id = fmt['audio_id']
76 manifest.write(f',AUDIO="{audio_id}"')
77
78 if vcodec and captions:
79 captions_id = fmt['captions_id']
80 manifest.write(f',CLOSED-CAPTIONS="{captions_id}"')
81
82 url = fmt['url']
83 manifest.write(f'\n{url}')
84
85 def _insert_streams(manifest, formats, matches):
86 for fmt in formats:
87 have_bandwidth = (fmt.get('tbr') != None)
88
89 if have_bandwidth:
90 audio = None
91 captions = None
92
93 if (audio_id := fmt.get('audio_id')):
94 audio = next(filter(lambda m: m['format_id'].split('-')[0] == audio_id, matches), None)
95 if (captions_id := fmt.get('captions_id')):
96 captions = next(filter(lambda m: m['format_id'].split('-')[0] == captions_id, matches), None)
97
98 _add_x_stream_inf(manifest, fmt, audio, captions)
99 else:
100 _add_x_media(manifest, fmt)
101
102 def _add_streams(manifest, info, vcoding, acoding):
103 formats = []
104 matches = []
105
106 for fmt in info['formats']:
107 # Ensure all required values before creating adding stream
108 if (
109 not ((val := fmt.get('protocol')) and val == 'm3u8_native')
110 or not fmt.get('url')
111 or not fmt.get('vcodec', 'none').startswith(vcoding)
112 or not fmt.get('acodec', 'none').startswith(acoding)
113 or not ((val := fmt.get('format_id')) and not val.endswith('-drc'))
114 ):
115 continue
116
117 if vcoding != 'none':
118 # Ignore ultralow video qualities
119 if (height := fmt.get('height') or 0) < 240:
120 continue
121
122 if ((audio_id := fmt.get('audio_id')) and not any(m['format_id'].split('-')[0] == audio_id for m in matches)):
123 for audio_fmt in info['formats']:
124 if (audio_fmt.get('format_id', '').split('-')[0] == audio_id):
125 matches.append(audio_fmt)
126
127 if acoding != 'none':
128 # Ignore ultralow audio qualities
129 if (val := fmt.get('format_note')) == 'ultralow':
130 continue
131
132 # All is good
133 formats.append(fmt)
134
135 if len(formats) == 0:
136 return False
137
138 _insert_streams(manifest, formats, matches)
139
140 return True
141
142 def _make_manifest(info, vcoding, acoding, separate=False):
143 manifest = io.StringIO()
144 success = True
145
146 manifest.write('#EXTM3U\n#EXT-X-INDEPENDENT-SEGMENTS')
147
148 if separate:
149 # Start with audio stream as video streams often point to audio
150 if acoding != 'none':
151 success &= _add_streams(manifest, info, 'none', acoding)
152 if vcoding != 'none':
153 success &= _add_streams(manifest, info, vcoding, 'none')
154 else:
155 success = _add_streams(manifest, info, vcoding, acoding)
156
157 if not success:
158 return None
159
160 return manifest
161
162 def generate_manifest(info):
163 # Check if HLS is requested
164 if not ((protocol := info.get('protocol')) and protocol.startswith('m3u8_native')):
165 return None
166
167 separate = (len(protocol.split('+')) > 1)
168 vcoding = (info.get('vcodec') or 'none')[:4]
169 acoding = (info.get('acodec') or 'none')[:4]
170
171 if vcoding == acoding or (separate and 'none' in {vcoding, acoding}):
172 return None
173
174 # Video + Audio separately if more than 1 format, otherwise combined
175 if (manifest := _make_manifest(info, vcoding, acoding, separate)):
176 return manifest.getvalue()
177
178 return None