threefive3 3.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
scte35/hls.py ADDED
@@ -0,0 +1,1171 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ scte35.hls hls.py
4
+ (replaces showcues)
5
+
6
+ """
7
+
8
+ import datetime
9
+ import sys
10
+ import time
11
+ from collections import deque
12
+ from scte35 import Segment, Cue
13
+ from m3ufu import M3uFu, TagParser, HEADER_TAGS
14
+ from new_reader import reader
15
+
16
+ REV = "\033[7m"
17
+ NORM = "\033[27m"
18
+ # REV = ""
19
+ # NORM = ""
20
+ SUB = "\t"
21
+ NSUB = f"\n{SUB}"
22
+ ROLLOVER = 95443.717678
23
+ HEADER_TAGS = list(HEADER_TAGS)
24
+ HEADER_TAGS.append("#EXTM3U")
25
+
26
+
27
+ def atoif(value):
28
+ """
29
+ atoif converts ascii to (int|float)
30
+ """
31
+ ## if isinstance(value, (int, float)):
32
+ ## return value
33
+ if isinstance(value, str):
34
+ try:
35
+ value = float(value)
36
+ return value
37
+ except:
38
+ value = int(value)
39
+ return value
40
+ return value
41
+
42
+
43
+ def iso8601():
44
+ """
45
+ return UTC time in iso8601 format.
46
+
47
+ '2023-05-11T15:55:51.'
48
+
49
+ """
50
+ return f"{datetime.datetime.utcnow().isoformat()[:-4]}Z "
51
+
52
+
53
+ class Scte35Profile:
54
+ """
55
+ Scte35Profile Manages the Scte35 Parsing Profile
56
+ """
57
+
58
+ def __init__(self):
59
+ """
60
+ A Scte35Profile
61
+ """
62
+ self.expand_cues = False # Show SCTE-35 Cues fully expanded.
63
+ self.parse_segments = True # Parse Segments for SCTE-35.
64
+ self.parse_manifests = True # Parse m3u8 files for SCTE-35 HLS tags.
65
+ self.hls_tags = [
66
+ "#EXT-OATCLS-SCTE35",
67
+ "#EXT-X-CUE-OUT-CONT",
68
+ "#EXT-X-DATERANGE",
69
+ "#EXT-X-SCTE35",
70
+ "#EXT-X-CUE-IN",
71
+ "#EXT-X-CUE-OUT",
72
+ ] # Parse these types of HLS SCTE-35 tags.
73
+ self.command_types = [6, 5] # Which SCTE-35 Commands to parse.
74
+ self.descriptor_tags = [
75
+ 2,
76
+ ] # Which Descriptors to parse.
77
+ # Which Descriptor Segmentation Types IDs should be parsed
78
+ self.starts = [0x22, 0x30, 0x32, 0x34, 0x36, 0x44, 0x46]
79
+ self.seg_type = 0x23
80
+
81
+ # self.stops = [0x23, 0x31, 0x33, 0x35, 0x37, 0x45, 0x47]
82
+
83
+ def _is_int(self, vee, line):
84
+ for item in vee:
85
+ if isinstance(item, int):
86
+ line = f"{line}{hex(item)},"
87
+ else:
88
+ line = f"{line}{item},"
89
+ return line
90
+
91
+ def _list_in_profile(self, vee, line):
92
+ if isinstance(vee, list):
93
+ line = self._is_int(vee, line)
94
+ return line
95
+
96
+ def _bool_in_profile(self, vee, line):
97
+ if isinstance(vee, bool):
98
+ line = f"{line}{vee}"
99
+ return line
100
+
101
+ def write_profile(self, pro_file):
102
+ """
103
+ write_profile writes sc.profile for editing.
104
+ """
105
+ with open(pro_file, "w") as pro_f:
106
+ for que, vee in vars(self).items():
107
+ line = f"{que} = "
108
+ line = self._list_in_profile(vee, line)
109
+ line = self._bool_in_profile(vee, line)
110
+ line = line.strip(",")
111
+ pro_f.write(line + "\n")
112
+
113
+ def show_profile(self, headline):
114
+ """
115
+ show_profile displays profile settings.
116
+ """
117
+ print(f"\n\n\t{REV}{headline}{NORM}\n")
118
+ for que, vee in vars(self).items():
119
+ if isinstance(vee, list):
120
+ if isinstance(vee[0], int):
121
+ vee = [hex(eye) for eye in vee]
122
+ print(f"\t{que} = {vee}\n")
123
+ time.sleep(0.3)
124
+
125
+ def clean_n_split(self, line):
126
+ """
127
+ clean_n_split a line.
128
+ """
129
+ this, that = None, None
130
+ bad = [" ", "\n", "\t", '"', "'"]
131
+ for bee in bad:
132
+ line = line.replace(bee, "")
133
+ if line:
134
+ this, that = line.split("=", 1)
135
+ that = list(that.split(","))
136
+ if line.startswith("#") or line.startswith("//"):
137
+ this = None
138
+ return this, that
139
+
140
+ def _string2bool(self, this, that):
141
+ print(that[0])
142
+ if this.startswith("parse") or this.startswith("expand"):
143
+ return [False, True][that[0] == "True"]
144
+ return that
145
+
146
+ def _hexed(self, this, that):
147
+ if this in ["command_types", "descriptor_tags", "starts"]:
148
+ new_that = []
149
+ for s in that:
150
+ if s.lower().startswith("0x"):
151
+ new_that.append(int(s, 16))
152
+ else:
153
+ new_that.append(int(s))
154
+ return new_that
155
+ return that
156
+
157
+ def format4profile(self, this, that):
158
+ """
159
+ format4profile formats data read from hls.profile for internal use.
160
+ """
161
+ if this is None or that is None:
162
+ return
163
+ this = this.lower()
164
+ that = self._string2bool(this, that)
165
+ that = self._hexed(this, that)
166
+ self.__dict__.update({this: that})
167
+
168
+ def read_profile(self, pro_file):
169
+ """
170
+ read_profile reads sc.profile
171
+ """
172
+ try:
173
+ with open(pro_file, "r") as pro_file:
174
+ for line in pro_file:
175
+ this, that = self.clean_n_split(line)
176
+ self.format4profile(this, that)
177
+ finally:
178
+ self.show_profile("Profile:")
179
+
180
+ def set_pts(self, cue):
181
+ """
182
+ set_pts cue.command.pts_time +
183
+ cue.info_section.pts_adjustment
184
+ % ROLLOVER
185
+ """
186
+ pts = cue.command.pts_time + cue.info_section.pts_adjustment
187
+ return pts % ROLLOVER
188
+
189
+ def validate_cue(self, cue):
190
+ """
191
+ validate_cue use the parsing profile to validate a SCTE-35 Cue.
192
+ """
193
+ pts = None
194
+ line = None
195
+ cue.decode()
196
+ if cue.command.command_type in self.command_types:
197
+ if "pts_time" in vars(cue.command) and cue.command.pts_time:
198
+ pts = self.set_pts(cue)
199
+ if self.expand_cues:
200
+ cue.show()
201
+ if cue.command.command_type == 5:
202
+ line = self.validate_splice_insert(cue)
203
+ if cue.command.command_type == 6:
204
+ line = self.validate_time_signal(cue)
205
+ return pts, line
206
+
207
+ def validate_splice_insert(self, cue):
208
+ """
209
+ validate_splice_insert is named appropriately.
210
+ """
211
+ line = None
212
+ if cue.command.out_of_network_indicator:
213
+ if "break_duration" in vars(cue.command) and cue.command.break_duration:
214
+ duration = cue.command.break_duration
215
+ line = f"#EXT-X-CUE-OUT:{duration}\n"
216
+ return line
217
+ else:
218
+ line = "#EXT-X-CUE-IN\n"
219
+ return line
220
+ return line
221
+
222
+ def validate_time_signal(self, cue):
223
+ """
224
+ validate_time_signal is named appropriately.
225
+ """
226
+ line = None
227
+ for dscptr in cue.descriptors:
228
+ if dscptr.tag in self.descriptor_tags:
229
+ if dscptr.segmentation_type_id in self.starts:
230
+ self.seg_type = dscptr.segmentation_type_id + 1
231
+ if "segmentation_duration" in vars(dscptr):
232
+ duration = dscptr.segmentation_duration
233
+ line = f"#EXT-X-CUE-OUT:{duration}\n"
234
+ return line
235
+ if dscptr.segmentation_type_id == self.seg_type:
236
+ line = "#EXT-X-CUE-IN\n"
237
+ self.seg_type = None
238
+ return line
239
+ return line
240
+
241
+
242
+ class Pane:
243
+ """
244
+ Pane class. Sliding_Window slides Panes
245
+ """
246
+
247
+ def __init__(self, media, lines):
248
+ self.media = media
249
+ self.lines = lines
250
+
251
+ def get(self):
252
+ """
253
+ get merges self.lines and self.media for
254
+ writing m3u8 files.
255
+ """
256
+ all_lines = self.lines + [self.media]
257
+ return "".join(all_lines)
258
+
259
+
260
+ class SlidingWindow:
261
+ """
262
+ The Sliding Window class
263
+ """
264
+
265
+ def __init__(self, size=101):
266
+ self.size = size
267
+ self.panes = deque()
268
+ self.delete = False
269
+
270
+ def pop_pane(self):
271
+ """
272
+ pop_pane removes the first item in self.panes
273
+ """
274
+ if len(self.panes) > self.size:
275
+ self.panes.popleft()
276
+
277
+ def all_panes(self):
278
+ """
279
+ all_panes returns the current window panes joined.
280
+ """
281
+ return "\n".join(set([a_pane.get() for a_pane in self.panes]))
282
+
283
+ def slide_panes(self, a_pane):
284
+ """
285
+ slide calls self.push_pane with a_pane
286
+ and then calls self.pop_pane to trim self.panes
287
+ as needed.
288
+ """
289
+ self.panes.append(a_pane)
290
+ self.pop_pane()
291
+
292
+
293
+ class AacParser:
294
+ """
295
+ AacParser parses aac segments.
296
+ """
297
+
298
+ applehead = b"com.apple.streaming.transportStreamTimestamp"
299
+
300
+ @staticmethod
301
+ def is_header(header):
302
+ """
303
+ is_header tests aac and ac3 files for ID3 headers.
304
+ """
305
+ if header[:3] == b"ID3":
306
+ return True
307
+ return False
308
+
309
+ @staticmethod
310
+ def id3_len(header):
311
+ """
312
+ id3_len parses the length value from ID3 headers
313
+ """
314
+ id3len = int.from_bytes(header[6:], byteorder="big")
315
+ return id3len
316
+
317
+ @staticmethod
318
+ def syncsafe5(somebytes):
319
+ """
320
+ syncsafe5 parses PTS from ID3 tags.
321
+ """
322
+ lsb = len(somebytes) - 1
323
+ syncd = 0
324
+ for idx, bite in enumerate(somebytes):
325
+ syncd += bite << ((lsb - idx) << 3)
326
+ return round(syncd / 90000.0, 6)
327
+
328
+ def parse(self, media):
329
+ """
330
+ aac_pts parses the ID3 header tags in aac and ac3 audio files
331
+ """
332
+ pts = 0
333
+ aac = reader(media)
334
+ header = aac.read(10)
335
+ if self.is_header(header):
336
+ id3len = self.id3_len(header)
337
+ data = aac.read(id3len)
338
+ if self.applehead in data:
339
+ try:
340
+ pts = float(data.split(self.applehead)[1].split(b"\x00", 2)[1])
341
+ except:
342
+ pts = self.syncsafe5(data.split(self.applehead)[1][:9])
343
+ return round((pts % ROLLOVER), 6)
344
+
345
+
346
+ class CuePuller:
347
+ """
348
+ CuePuller is the main object.
349
+ """
350
+
351
+ def __init__(self):
352
+ self.media = deque()
353
+ self.sidecar = "hls.sidecar"
354
+ self.dumpfile = "hls.dump"
355
+ self.flat = "hlsflat.m3u8"
356
+ self.pro_file = "hls.profile"
357
+ self.m3u8 = "hls.m3u8"
358
+ self.last_dump_line = None
359
+ self.base_uri = None
360
+ self.iv = None
361
+ self.key_uri = None
362
+ self.last_iv = None
363
+ self.last_key_uri = None
364
+ self.break_timer = None
365
+ self.break_duration = None
366
+ self.reload = True
367
+ self.sleep_duration = 0
368
+ self.window_size = None
369
+ self.sliding_window = SlidingWindow()
370
+ self.cue_state = None
371
+ self.last_cue = None
372
+ self.headers = []
373
+ self.pts = 0
374
+ self.cont_resume = False
375
+ self.first_segment = True
376
+ self.hls_pts = "HLS"
377
+ self.prof = Scte35Profile()
378
+ self.prof.read_profile(self.pro_file)
379
+ self.clear_files()
380
+
381
+ @staticmethod
382
+ def clear():
383
+ """
384
+ clear previous line.
385
+ """
386
+ print(" " * 80, end="\r")
387
+ print(" " * 80, file=sys.stderr, end="\r", flush=True)
388
+
389
+ def clear_files(self):
390
+ """
391
+ clear_files clobbers the appended files
392
+ self.sidecar, self.dumpfile, self.flat, self.m3u8
393
+ when showcues is started.
394
+ """
395
+ for sidef in [self.sidecar, self.dumpfile, self.flat, self.m3u8]:
396
+ with open(sidef, "w+") as side_file: # touch
397
+ pass
398
+
399
+ def chk_aes(self, line):
400
+ """
401
+ chk_aes checks for AES encryption
402
+ """
403
+ if "#EXT-X-KEY" in line:
404
+ tags = TagParser([line]).tags
405
+ if "URI" in tags["#EXT-X-KEY"]:
406
+ self.key_uri = tags["#EXT-X-KEY"]["URI"]
407
+ if not self.key_uri.startswith("http"):
408
+ re_uri = self.base_uri + self.key_uri
409
+ self.key_uri = re_uri
410
+ if "IV" in tags["#EXT-X-KEY"]:
411
+ self.iv = tags["#EXT-X-KEY"]["IV"]
412
+
413
+ def to_sidecar(self, pts, line):
414
+ """
415
+ to_sidecar writes (pts,hls tag) pairs to the sidecar file.
416
+ """
417
+ with open(self.sidecar, "a") as sidecar:
418
+ sidecar.write(f"{round(pts,6)},{line}\n")
419
+
420
+ def to_dump(self, pts, line):
421
+ """
422
+ to_dump copies all SCTE-35 lines to self.dumpfile.
423
+ """
424
+ with open(self.dumpfile, "a") as dump:
425
+ dump_line = f"{pts},{line}\n"
426
+ if dump_line != self.last_dump_line:
427
+ dump.write(dump_line)
428
+ self.last_dump_line = dump_line
429
+
430
+ def media_stuff(self):
431
+ """
432
+ media_stuff trims segment URI to just the file name.
433
+ """
434
+ media = self.media[-1]
435
+ short_media = media.rsplit("/", 1)[1].split("?", 1)[0]
436
+ return f"Media: {short_media.strip()}"
437
+
438
+ def cue_stuff(self):
439
+ """
440
+ cue_stuff returns self.cue_state formated.
441
+ """
442
+ return f"Cue {REV}{self.cue_state} {NORM}"
443
+
444
+ def diff_stuff(self):
445
+ """
446
+ diff gonzo returns formated self.break_timer
447
+ and if possible the difference between the actual break duration
448
+ and the specified SCTE-35 break duration.
449
+ """
450
+ if self.break_timer is not None:
451
+ if not self.break_duration:
452
+ return f"{NSUB}Break Timer: {round(self.break_timer,6)}"
453
+ return (NSUB).join(
454
+ [
455
+ f"{NSUB}Timer: { round(self.break_timer,6)}",
456
+ f"Duration: {self.break_duration}",
457
+ f"Diff: {round(self.break_timer - self.break_duration,6)}",
458
+ ]
459
+ )
460
+ return ""
461
+
462
+ def dur_stuff(self):
463
+ """
464
+ dur_stuff returns self.break_duration formated.
465
+ """
466
+ return f"{NSUB}Duration: {self.break_duration}"
467
+
468
+ def pts_stuff(self):
469
+ """
470
+ pts_stuff returns PTS formated.
471
+ """
472
+ return f"{NSUB}{self.hls_pts}: {self.pts}"
473
+
474
+ def _chk_cue_in(self, line, head):
475
+ if line.startswith("#EXT-X-CUE-IN") and self.cue_state == "CONT":
476
+ self.cue_state = "IN"
477
+ self.to_sidecar(self.pts, line)
478
+ self.clear()
479
+ print(f"{head}{self.diff_stuff()}{NSUB}{self.media_stuff()}\n")
480
+ self.reset_break()
481
+ return line
482
+
483
+ def _chk_cue_out(self, line, head):
484
+ if line.startswith("#EXT-X-CUE-OUT") and self.cue_state in [None, "IN"]:
485
+ self.reset_break()
486
+ self.cue_state = "OUT"
487
+ self.break_timer = 0.0
488
+ if ":" in line:
489
+ self.break_duration = atoif(line.split(":")[1])
490
+ self.to_sidecar(self.pts, line)
491
+ self.clear()
492
+ print(f"{head}{self.dur_stuff()}{NSUB}{self.media_stuff()}\n")
493
+ return line
494
+
495
+ def set_cue_state(self, cue, line):
496
+ """
497
+ set_cue_state determines cue_state
498
+
499
+ """
500
+ if cue.encode() == self.last_cue:
501
+ return ""
502
+ self.last_cue = cue.encode()
503
+ if "CONT" not in line:
504
+ head = f"\n{iso8601()}{REV}{line}{NORM}{self.pts_stuff()} {REV} Splice Point {NORM}"
505
+ line = self._chk_cue_in(line, head)
506
+ line = self._chk_cue_out(line, head)
507
+
508
+ elif self.cue_state in ["OUT", "CONT"]:
509
+ self.to_sidecar(self.pts, line)
510
+ self.cue_state = "CONT"
511
+ return line
512
+
513
+ def invalid(self, line):
514
+ """
515
+ invalid print invalid SCTE-35 HLS tags
516
+ """
517
+ self.clear()
518
+ print(
519
+ f"\n{iso8601()}{REV} Skipped {NORM} {line}{self.pts_stuff()}{NSUB}{self.media_stuff()}\n"
520
+ )
521
+ return "## " + line
522
+
523
+ def show_tags(self, tags):
524
+ try:
525
+ for que, vee in tags.items():
526
+ print(f"{SUB}{que}: {vee}")
527
+ except:
528
+ return
529
+
530
+ def _set_break_timer(self, line, cont_tags):
531
+ """
532
+ _set_break_timer sets self.break_timer to ElaspsedTime
533
+ read from a CUE-OUT-CONT tag or to 0.0.
534
+ """
535
+ if self.break_timer:
536
+ return
537
+ if "ElapsedTime" in cont_tags:
538
+ self.break_timer = cont_tags["ElapsedTime"]
539
+ else:
540
+ try:
541
+ self.break_timer = round(float(line.split(":", 1)[1].split("/")[0]), 3)
542
+ except:
543
+ self.break_timer = 0.0
544
+ print(f"{iso8601()}{REV} Break Timer {NORM}to {self.break_timer}\n")
545
+ time.sleep(0.1)
546
+
547
+ def _set_break_duration(self, line, cont_tags):
548
+ """
549
+ __set_break_duration sets self.break_duration from
550
+ a CUE-OUT-CONT tag or from a CUE-OUT tag.
551
+ """
552
+ if self.break_duration:
553
+ return
554
+ if "Duration" in cont_tags:
555
+ self.break_duration = cont_tags["Duration"]
556
+ else:
557
+ try:
558
+ self.break_duration = round(
559
+ float(line.split(":", 1)[1].split("/")[1]), 3
560
+ )
561
+ except:
562
+ self.break_duration = None
563
+ if self.break_duration:
564
+ print(f"{iso8601()}{REV}Break Duration {NORM}to {self.break_duration}\n")
565
+ time.sleep(0.1)
566
+
567
+ def chk_x_cue_out_cont(self, tags, line):
568
+ """
569
+ chk_x_cue_out_const processes
570
+ #EXT-X-CUE-OUT-CONT tags
571
+ """
572
+ cont_tags = tags["#EXT-X-CUE-OUT-CONT"]
573
+ if self.cue_state not in ["OUT", "CONT"] and not self.first_segment:
574
+ return None
575
+ if self.first_segment:
576
+ print(f"{iso8601()}{REV} Resuming Ad Break {NORM}\n")
577
+ self.cue_state = "CONT"
578
+ self._set_break_timer(line, cont_tags)
579
+ self._set_break_duration(line, cont_tags)
580
+ return self.auto_cont()
581
+
582
+ def chk_x_cue_in(self, tags, line):
583
+ """
584
+ chk_x_cue_in processes
585
+ #EXT-X-CUE-IN tags.
586
+ """
587
+ return self.set_cue_state(line, line)
588
+
589
+ def chk_x_cue_out(self, tags, line):
590
+ """
591
+ chk_x_cue_out processes
592
+ #EXT-X-CUE-OUT tags
593
+ """
594
+ return self.set_cue_state(line, line)
595
+
596
+ def chk_x_scte35(self, tags, line):
597
+ """
598
+ chk_x_scte35 handles #EXT-X-SCTE35 tags.
599
+ """
600
+ if "CUE" in tags["#EXT-X-SCTE35"]:
601
+ cue = Cue(tags["#EXT-X-SCTE35"]["CUE"])
602
+ pts, new_line = self.prof.validate_cue(cue)
603
+ if pts and new_line:
604
+ return self.set_cue_state(tags["#EXT-X-SCTE35"]["CUE"], new_line)
605
+ return self.invalid(line)
606
+
607
+ def chk_x_daterange(self, tags, line):
608
+ """
609
+ chk_x_daterange handles #EXT-X-DATERANGE tags.
610
+ """
611
+ self.show_tags(tags["#EXT-X-DATERANGE"])
612
+ # for scte35_tag in ["SCTE35-OUT", "SCTE35-IN"]:
613
+ if scte35_tag in tags["#EXT-X-DATERANGE"]:
614
+ cue = Cue(tags["#EXT-X-DATERANGE"][scte35_tag])
615
+ pts, new_line = self.prof.validate_cue(cue)
616
+ if pts and new_line:
617
+ return self.set_cue_state(
618
+ tags["#EXT-X-DATERANGE"][scte35_tag], new_line
619
+ )
620
+ return self.invalid(line)
621
+
622
+ def chk_x_oatcls(self, tags, line):
623
+ """
624
+ chk_x_oatcls handles
625
+ #EXT-OATCLS-SCTE35
626
+ HLS tags.
627
+ """
628
+ cue = Cue(tags["#EXT-OATCLS-SCTE35"])
629
+ pts, new_line = self.prof.validate_cue(cue)
630
+ if pts and new_line:
631
+ if abs(pts - self.pts) > 5: # Handle Cues out of sync with video PTS
632
+ pts = self.pts
633
+ return self.set_cue_state(tags["#EXT-OATCLS-SCTE35"], new_line)
634
+ return self.invalid(line)
635
+
636
+ def scte35(self, line):
637
+ """
638
+ scte35 processes SCTE-35 related tags.
639
+ """
640
+ scte35_map = {
641
+ "#EXT-X-DATERANGE": self.chk_x_daterange,
642
+ "#EXT-X-SCTE35": self.chk_x_scte35,
643
+ "#EXT-X-CUE-OUT-CONT": self.chk_x_cue_out_cont,
644
+ "#EXT-OATCLS-SCTE35": self.chk_x_oatcls,
645
+ "#EXT-X-CUE-IN": self.chk_x_cue_in,
646
+ "#EXT-X-CUE-OUT": self.chk_x_cue_out,
647
+ }
648
+ tags = TagParser([line]).tags
649
+ for key in scte35_map.keys():
650
+ if key in line:
651
+ self.to_dump(self.pts, line)
652
+ if self.prof.parse_manifests:
653
+ for que, vee in scte35_map.items():
654
+ if que in line:
655
+ if que not in self.prof.hls_tags:
656
+ return None
657
+ return vee(tags, line)
658
+ return line
659
+
660
+ def auto_cont(self):
661
+ self.cue_state = "CONT"
662
+ line = (
663
+ f"#EXT-X-CUE-OUT-CONT:{round(self.break_timer,3)}/{self.break_duration}\n"
664
+ )
665
+ line = self.set_cue_state(line, line)
666
+ return line
667
+
668
+ def auto_cuein(self, line):
669
+ """
670
+ auto_cuein handles cue.command.auto-return
671
+ """
672
+ if self.cue_state == "CONT":
673
+ if self.break_timer and self.break_duration:
674
+ if self.break_timer >= self.break_duration:
675
+ self.cue_state = "IN"
676
+ self.clear()
677
+ print(
678
+ f"{iso8601()}{REV} AUTO CUE-IN {NORM}{self.pts_stuff()}{self.diff_stuff()}{NSUB}{self.media_stuff()}\n"
679
+ )
680
+ self.reset_break()
681
+ self.to_sidecar(self.pts, "#AUTO\n#EXT-X-CUE-IN\n")
682
+ return "#AUTO\n#EXT-X-CUE-IN\n" + line
683
+ return line
684
+
685
+ def reset_break(self):
686
+ """
687
+ reset_break resets
688
+ break_duration, break_timer,
689
+ and cue_state after a CUE-IN
690
+ """
691
+ if self.cue_state == "IN":
692
+ self.break_duration = None
693
+ self.break_timer = None
694
+ self.cue_state = None
695
+
696
+ def extinf(self, line):
697
+ """
698
+ extinf parses lines that start with #EXTINF
699
+ for the segment duration.
700
+ """
701
+ tags = TagParser([line]).tags
702
+ if "#EXTINF" in tags:
703
+ if isinstance(tags["#EXTINF"], str):
704
+ tags["#EXTINF"] = tags["#EXTINF"].rsplit(",", 1)[0]
705
+ seg_time = round(atoif(tags["#EXTINF"]), 6)
706
+ line = self.auto_cuein(line)
707
+ if self.pts is not None:
708
+ self.pts += seg_time
709
+ if self.break_timer is not None:
710
+ self.break_timer += seg_time
711
+ return line
712
+
713
+ def print_time(self):
714
+ """
715
+ print_time prints wall clock and pts.
716
+ """
717
+ gonzo = ""
718
+ if self.break_timer:
719
+ gonzo = f"{REV} Break {NORM} {round(self.break_timer,3)}"
720
+ if self.break_duration:
721
+ gonzo = f"{gonzo} / {round(self.break_duration,3)}"
722
+ print(
723
+ f"\r\r{iso8601()}{REV} {self.hls_pts} {NORM} {self.pts} {gonzo}",
724
+ end="\r",
725
+ file=sys.stderr,
726
+ flush=True,
727
+ )
728
+
729
+ def ts_pts(self, seg):
730
+ """
731
+ ts_pts set pts from segment
732
+ """
733
+ if seg.pts_start:
734
+ self.pts = seg.pts_start
735
+ self.print_time()
736
+ self.hls_pts = "PTS"
737
+
738
+ def ts_cues(self, seg):
739
+ """
740
+ ts_cues process SCTE-35 cues
741
+ found in a segment.
742
+ """
743
+ for cue in seg.cues:
744
+ if "pts" in vars(cue.packet_data) and cue.packet_data.pts:
745
+ self.pts = cue.packet_data.pts
746
+ if cue.encode() != self.last_cue:
747
+ self.last_cue = cue.encode()
748
+ self.ts_set_cue(cue)
749
+
750
+ def ts_set_cue(self, cue):
751
+ """
752
+ ts_set_cue validate and set cue from ts segment.
753
+ """
754
+ cue_pts, line = self.prof.validate_cue(cue)
755
+ if cue_pts and line:
756
+ self.set_cue_state(cue.encode(), line)
757
+ self.clear()
758
+ print(
759
+ (NSUB).join(
760
+ [
761
+ f"\n{iso8601()}{REV} SCTE-35 {NORM}",
762
+ f"Stream PTS: {round(self.pts,6)}",
763
+ f"PreRoll: {round(cue_pts - self.pts,6)}",
764
+ f"Splice Point: {round(cue_pts,6)}",
765
+ f"Type: {cue.command.name}",
766
+ f"{self.media_stuff()}\n",
767
+ ]
768
+ )
769
+ )
770
+
771
+ def chk_ts(self, this):
772
+ """
773
+ chk_ts check MPEGTS for PTS and SCTE-35.
774
+ """
775
+ if ".ts" in this:
776
+ if self.first_segment:
777
+ Segment(this, key_uri=self.key_uri, iv=self.iv).show()
778
+ seg = Segment(this, key_uri=self.key_uri, iv=self.iv)
779
+ seg.shushed()
780
+ seg.decode()
781
+ self.ts_pts(seg)
782
+ if self.prof.parse_segments:
783
+ self.ts_cues(seg)
784
+ self.print_time()
785
+
786
+ def chk_aac(self, this):
787
+ """
788
+ chk_aac check aac and ac3 HLS audio segments
789
+ for PTS in ID3 header tags.
790
+ """
791
+ if ".aac" in this or ".ac3" in this:
792
+ aac_parser = AacParser()
793
+ pts = aac_parser.parse(this)
794
+ if pts:
795
+ self.pts = pts
796
+ self.hls_pts = "PTS"
797
+ self.print_time()
798
+
799
+ def new_media(self, this):
800
+ """
801
+ new_media check to see
802
+ if the media is new in a
803
+ live sliding window
804
+ """
805
+ if this not in self.media:
806
+ self.media.append(this)
807
+ if len(self.media) > self.window_size + 1:
808
+ self.media.popleft()
809
+ return True
810
+ return False
811
+
812
+ def parse_target_duration(self, line):
813
+ """
814
+ parse_target_duration reads target duration
815
+ off the manifest to set self.sleep_duration.
816
+ self.sleep_duration is used to throttle manifest
817
+ requests.
818
+ """
819
+ if "TARGETDURATION" in line:
820
+ if self.sleep_duration == 0:
821
+ target_duration = atoif(line.split(":")[1])
822
+ self.sleep_duration = round(target_duration * 0.5, 3)
823
+ print(f"{SUB}{REV} Target Duration {NORM} {target_duration}\n")
824
+
825
+ def mk_window_size(self, lines):
826
+ """
827
+ mk_window_size sets the sliding window size
828
+ for the output to match that off the input and
829
+ determine how long to keep media data info
830
+ for segments.
831
+ """
832
+ if not self.window_size:
833
+ self.window_size = len([line for line in lines if "#EXTINF:" in line])
834
+ self.sliding_window.size = self.window_size
835
+ print(f"{SUB}{REV} Window Size {NORM} {self.window_size}\n")
836
+
837
+ def update_cue_state(self):
838
+ """
839
+ update_cue_state changes CUE state.
840
+ """
841
+ if self.cue_state == "OUT":
842
+ self.cue_state = "CONT"
843
+ if self.cue_state == "IN":
844
+ self.cue_state = None
845
+
846
+ @staticmethod
847
+ def decode_lines(lines):
848
+ """
849
+ decode_lines convert bytes to ascii
850
+ """
851
+ return [line.decode() for line in lines]
852
+
853
+ def parse_line(self, line):
854
+ if "#EXT-X-PROGRAM-DATE-TIME" in line:
855
+ return None
856
+
857
+ if "#EXTINF:" in line:
858
+ line = self.extinf(line)
859
+ return line
860
+ self.chk_aes(line)
861
+ line = self.scte35(line)
862
+ return line
863
+
864
+ def parse_header(self, line):
865
+ """
866
+ parse_headers parses m3u8 files for HLS header tags.
867
+ """
868
+ if "#EXT-X-PROGRAM-DATE-TIME" in line:
869
+ return False
870
+ splitline = line.split(":", 1)
871
+ if splitline[0] in HEADER_TAGS:
872
+ self.parse_target_duration(line)
873
+ self.headers.append(line)
874
+ return True
875
+ return False
876
+
877
+ def chk_endlist(self, line):
878
+ """
879
+ chk_endlist disables manifest reloading
880
+ if line contains ENDLIST tag.
881
+ """
882
+ if "#EXT-X-ENDLIST" in line:
883
+ self.reload = False
884
+
885
+ def write_flat(self, lines, media):
886
+ """
887
+ write_flat flatten out the sliding window
888
+ and write all data to flat.m3u8.
889
+ """
890
+ with open(self.flat, "a") as flat:
891
+ if self.first_segment:
892
+ flat.write("#EXTM3U\n")
893
+ for header in self.headers:
894
+ flat.write(header)
895
+ for line in lines:
896
+ flat.write(line)
897
+ flat.write(media)
898
+
899
+ def write_manifest(self):
900
+ """
901
+ write_manifest write data to sc.m3u8
902
+ with profile rules applied.
903
+ """
904
+ with open(self.m3u8, "w") as out:
905
+ out.write("#EXTM3U\n")
906
+ out.write("".join(self.headers))
907
+ out.write(self.sliding_window.all_panes())
908
+
909
+ def _parse_new_media(self, lines, media):
910
+ self.write_flat(lines, media)
911
+ parsed = [self.parse_line(line) for line in lines]
912
+ lines = [line for line in parsed if line is not None]
913
+ media = media.replace("\n", "")
914
+ self.chk_ts(media)
915
+ self.chk_aac(media)
916
+ pane = Pane(media, lines)
917
+ self.sliding_window.slide_panes(pane)
918
+ self.first_segment = False
919
+
920
+ def _fixup_media(self, lines, media):
921
+ if not media.startswith("http"):
922
+ media = self.base_uri + "/" + media
923
+ if self.new_media(media):
924
+ self._parse_new_media(lines, media)
925
+
926
+ def _post_parse(self):
927
+ self.write_manifest()
928
+ self.headers = []
929
+ self.update_cue_state()
930
+ time.sleep(self.sleep_duration)
931
+
932
+ def _parse_manifest(self, manifest):
933
+ """
934
+ _parse_manifest, parses m3u8 files.
935
+ """
936
+ with reader(manifest) as m3u8:
937
+ lines = []
938
+ m3u8_lines = self.decode_lines(m3u8.readlines())
939
+ self.mk_window_size(m3u8_lines)
940
+ for line in m3u8_lines:
941
+ self.chk_endlist(line)
942
+ if line.startswith("#"):
943
+ if not self.parse_header(line):
944
+ lines.append(line)
945
+ else:
946
+ media = line
947
+ self._fixup_media(lines, media)
948
+ lines = []
949
+ self._post_parse()
950
+
951
+ def pull(self, manifest):
952
+ """
953
+ pull m3u8 and parse it.
954
+ """
955
+ print(f"\n{SUB}{REV} Started {NORM} {iso8601()}\n")
956
+ print(f"{SUB}{REV} Manifest {NORM} {manifest}\n")
957
+ self.base_uri = manifest.rsplit("/", 1)[0]
958
+ self.sliding_window = SlidingWindow()
959
+ while self.reload:
960
+ self._parse_manifest(manifest)
961
+ with open(self.flat, "a") as flat:
962
+ flat.write("#EXT-X-ENDLIST\n")
963
+
964
+
965
+ def precheck():
966
+ """
967
+ precheck sys.argv for keywords
968
+ that trigger a sys.exit().
969
+ """
970
+ if "help" in sys.argv:
971
+ print(helpme)
972
+ sys.exit()
973
+ if "profile" in sys.argv:
974
+ scp = Scte35Profile()
975
+ scp.write_profile("hls.profile")
976
+ sys.exit()
977
+
978
+
979
+ def find_renditions():
980
+ """
981
+ find_renditions search master.m3u8 for playable renditions.
982
+ """
983
+ with reader(sys.argv[1]) as arg:
984
+ renditions = [line for line in arg if b"#EXT-X-STREAM-INF" in line]
985
+ if renditions:
986
+ fumo = M3uFu()
987
+ fumo.m3u8 = sys.argv[1]
988
+ fumo.decode()
989
+ playlists = [
990
+ segment
991
+ for segment in fumo.segments
992
+ if "#EXT-X-STREAM-INF" in segment.tags
993
+ ]
994
+ return playlists
995
+ return False
996
+
997
+
998
+ def cli():
999
+ """
1000
+ cli is a function to use in a command line tool
1001
+
1002
+ #!/usr/bin/env python3
1003
+
1004
+ from scte35.hls import cli
1005
+
1006
+ if __name__ == "__main__":
1007
+ cli()
1008
+
1009
+
1010
+ is all that's required.
1011
+ """
1012
+ playlists = None
1013
+ m3u8 = None
1014
+ precheck()
1015
+ playlists = find_renditions()
1016
+ if playlists:
1017
+ m3u8 = playlists[0].media
1018
+ else:
1019
+ m3u8 = sys.argv[1]
1020
+ cpulr = CuePuller()
1021
+ cpulr.pull(m3u8)
1022
+ print()
1023
+ sys.exit()
1024
+
1025
+
1026
+ helpme = """
1027
+
1028
+ [ scte35 hls ]
1029
+
1030
+ [ Help ]
1031
+
1032
+ To display this help:
1033
+
1034
+ scte35 hls help
1035
+
1036
+ [ Input ]
1037
+
1038
+ scte35 hls takes an m3u8 URI as input.
1039
+
1040
+ M3U8 formats supported:
1041
+ * master ( When a master.m3u8 used,
1042
+ scte35 hls parses the first rendition it finds )
1043
+ * rendition
1044
+ Segment types supported:
1045
+ * AAC
1046
+ * AC3
1047
+ * MPEGTS
1048
+ *codecs:
1049
+ * video
1050
+ * mpeg2, h.264, h.265
1051
+ * audio
1052
+ * mpeg2, aac, ac3, mp3
1053
+
1054
+ Protocols supported:
1055
+ * file
1056
+ * http(s)
1057
+ * UDP
1058
+ * Multicast
1059
+
1060
+ Encryption supported:
1061
+ * AES-128 (segments are automatically decrypted)
1062
+
1063
+ [ SCTE-35 ]
1064
+
1065
+ scte35 hls displays SCTE-35 Embedded Cues as well as SCTE-35 HLS Tags.
1066
+
1067
+ Supported SCTE-35:
1068
+ * All Commands, Descriptors, and UPIDS
1069
+ in the 2022-b SCTE-35 specification.
1070
+
1071
+ Supported HLS Tags
1072
+ * #EXT-OATCLS-SCTE35
1073
+ * #EXT-X-CUE-OUT-CONT
1074
+ * #EXT-X-DATERANGE
1075
+ * #EXT-X-SCTE35
1076
+ * #EXT-X-CUE-IN
1077
+ * #EXT-X-CUE-OUT
1078
+
1079
+ [ SCTE-35 Parsing Profiles ]
1080
+
1081
+ SCTE-35 parsing can be fine tuned by setting a parsing profile.
1082
+
1083
+ running the command:
1084
+
1085
+ scte35 hls profile
1086
+
1087
+ will generate a default profile and write a file named hls.profile
1088
+ in the current working directory.
1089
+
1090
+ a@fu:~$ cat hls.profile
1091
+
1092
+ expand_cues = False
1093
+ parse_segments = False
1094
+ parse_manifests = True
1095
+ hls_tags = #EXT-OATCLS-SCTE35,#EXT-X-CUE-OUT-CONT,
1096
+ #EXT-X-DATERANGE,#EXT-X-SCTE35,#EXT-X-CUE-IN,#EXT-X-CUE-OUT
1097
+ command_types = 0x6,0x5
1098
+ descriptor_tags = 0x2
1099
+ starts = 0x22,0x30,0x32,0x34,0x36,0x44,0x46
1100
+
1101
+ ( Integers are show in hex (base 16),
1102
+ base 10 unsigned integers can also be used in .35rc )
1103
+
1104
+ * expand_cues: set to True to show cues fully expanded as JSON
1105
+ * parse_segments: set to true to enable parsing SCTE-35 from MPEGTS.
1106
+ * parse_manifests: set to true to parse the m3u8 file for SCTE-35 HLS Tags.
1107
+ * hls_tags: set which SCTE-35 HLS Tags to parse.
1108
+ * command_types: set which Splice Commands to parse.
1109
+ * descriptor_tags: set which Splice Descriptor Tags to parse.
1110
+ * starts: set which Segmentation Type IDs to use to start breaks.
1111
+
1112
+ Edit the file as needed and then run scte35 hls.
1113
+
1114
+ [ Profile Formatting Rules ]
1115
+
1116
+ * Values do not need to be quoted.
1117
+ * Multiple values are separated by a commas.
1118
+ * No partial line comments. Comments must be on a separate lines.
1119
+ * Comments can be started with a # or //
1120
+ * Integers can be base 10 or base 16
1121
+
1122
+ [ Output Files ]
1123
+
1124
+ * Created in the current working directory
1125
+ * Clobbered on start of showcues
1126
+ * Profile rules applied to the output:
1127
+ * hls.m3u8 - live playable rewrite of the m3u8 with the profile SCTE-35 rules.
1128
+ * hls.sidecar - list of ( pts, HLS SCTE-35 tag ) pairs
1129
+ * Profile rules not applied to the output:
1130
+ * hlsflat.m3u8 - hls live streams are flattened out into a vod playlist.
1131
+ When the live m3u8 first loads, every line is written to hlsflat.m3u8
1132
+ Wnen a live m3u8 is reloaded, everything except the headers
1133
+ is appended to hlsflat.m3u8. This give you a VOD style m3u8
1134
+ so you can fast forward or rewind while playing.
1135
+ GREAT for debugging SCTE-35 live hls.
1136
+
1137
+ [ Cool Features ]
1138
+
1139
+ * scte35 hls can resume when started in the middle of an ad break.
1140
+
1141
+ 2023-10-13T05:59:50.24Z Resuming Ad Break
1142
+ 2023-10-13T05:59:50.34Z Setting Break Timer to 17.733
1143
+ 2023-10-13T05:59:50.44Z Setting Break Duration to 60.067
1144
+
1145
+ * mpegts streams are listed on start ( like ffprobe )
1146
+
1147
+ Program: 1
1148
+ Service:
1149
+ Provider:
1150
+ Pid: 480
1151
+ Pcr Pid: 481
1152
+ Streams:
1153
+ Pid: 481[0x1e1] Type: 0x1b AVC Video
1154
+ Pid: 482[0x1e2] Type: 0xf AAC Audio
1155
+ Pid: 483[0x1e3] Type: 0x86 SCTE35 Data
1156
+ Pid: 484[0x1e4] Type: 252 Unknown
1157
+ Pid: 485[0x1e5] Type: 0x15 ID3 Timed Meta Data
1158
+
1159
+ [ Example Usage ]
1160
+
1161
+ * Show this help: scte35 hls help
1162
+
1163
+ * Generate a new hls.profile: scte35 hls profile
1164
+
1165
+ * parse an m3u8: scte35 hls https://example.com/out/master.m3u8
1166
+
1167
+ """
1168
+
1169
+
1170
+ if __name__ == "__main__":
1171
+ cli()