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/xml.py ADDED
@@ -0,0 +1,355 @@
1
+ """
2
+ xml.py The Node class for converting to xml,
3
+ The NameSpace Class.
4
+ and several helper functions
5
+ """
6
+
7
+ from xml.sax.saxutils import escape, unescape
8
+
9
+
10
+ def t2s(v):
11
+ """
12
+ _t2s converts
13
+ 90k ticks to seconds and
14
+ rounds to six decimal places
15
+ """
16
+ return round(v / 90000.0, 6)
17
+
18
+
19
+ def un_camel(k):
20
+ """
21
+ camel changes camel case xml names
22
+ to underscore_format names.
23
+ """
24
+ k = strip_ns(k)
25
+ k = "".join([f"_{i.lower()}" if i.isupper() else i for i in k])
26
+ return (k, k[1:])[k[0] == "_"]
27
+
28
+
29
+ def un_xml(v):
30
+ """
31
+ un_xml converts an xml value
32
+ to ints, floats and booleans.
33
+ """
34
+ mapped = {
35
+ "false": False,
36
+ "true": True,
37
+ }
38
+ if v.isdigit():
39
+ return int(v)
40
+ if v.replace(".", "").isdigit():
41
+ return float(v)
42
+ if v in mapped:
43
+ return mapped[v]
44
+ return v
45
+
46
+
47
+ def strip_ns(this):
48
+ """
49
+ strip_ns strip namespace off this.
50
+ """
51
+ if "xmlns:" in this:
52
+ return "xmlns"
53
+ return this.split(":")[-1]
54
+
55
+
56
+ def iter_attrs(attrs):
57
+ """
58
+ iter_attrs normalizes xml attributes
59
+ and adds them to the gonzo dict.
60
+ """
61
+ conv = {un_camel(k): un_xml(v) for k, v in attrs.items()}
62
+ pts_vars = ["pts_time", "pts_adjustment", "duration", "segmentation_duration"]
63
+ return {k: (t2s(v) if k in pts_vars else v) for k, v in conv.items()}
64
+
65
+
66
+ def val2xml(val):
67
+ """
68
+ val2xmlconvert val for xml
69
+ """
70
+ if isinstance(val, (bool, int, float)):
71
+ return str(val).lower()
72
+ if isinstance(val, str):
73
+ if val.lower()[:2] == "0x":
74
+ return str(int(val, 16))
75
+ return val
76
+
77
+
78
+ def key2xml(string):
79
+ """
80
+ key2xml convert name to camel case
81
+ """
82
+ new_string = string
83
+ if "_" in string:
84
+ new_string = string.title().replace("_", "")
85
+ return new_string[0].lower() + new_string[1:]
86
+
87
+
88
+ def mk_xml_attrs(attrs):
89
+ """
90
+ mk_xml_attrs converts a dict into
91
+ a dict of xml friendly keys and values
92
+ """
93
+ return "".join([f' {key2xml(k)}="{val2xml(v)}"' for k, v in attrs.items()])
94
+
95
+
96
+ class NameSpace:
97
+ """
98
+ Each Node instance has a NameSpace instance
99
+ to track namespace settings.
100
+ @ns is the name of the namespace
101
+ @uri is the xmlns uri
102
+ @all is a flag to signal that all elements and
103
+ attributes will have the namespace prefixed.
104
+ By default only the elements are prefixed with the namespace.
105
+ """
106
+
107
+ def __init__(self, ns=None, uri=None):
108
+ self.ns = ns
109
+ self.uri = uri
110
+ self.all = False
111
+
112
+ def prefix_all(self, abool=True):
113
+ """
114
+ prefix_all takes a boolean
115
+ True turns it on, False turns it off.
116
+ """
117
+ self.all = abool
118
+
119
+ def xmlns(self):
120
+ """
121
+ xmlns return xmlns attribute
122
+ """
123
+ if not self.uri:
124
+ return ""
125
+ if not self.ns:
126
+ return f'xmlns="{self.uri}"'
127
+ return f'xmlns:{self.ns}="{self.uri}"'
128
+
129
+ def clear(self):
130
+ """
131
+ clear clear namespace info
132
+ """
133
+ self.ns = None
134
+ self.uri = None
135
+ self.all = False
136
+
137
+
138
+ class Node:
139
+ """
140
+ The Node class is to create an xml node.
141
+
142
+ An instance of Node has:
143
+
144
+ name : <name> </name>
145
+ value : <name>value</name>
146
+ attrs : <name attrs[k]="attrs[v]">
147
+ children : <name><children[0]></children[0]</name>
148
+ depth: tab depth for printing (automatically set)
149
+
150
+ Use like this:
151
+
152
+ from scte35.xml import Node
153
+
154
+ ts = Node('TimeSignal')
155
+ st = Node('SpliceTime',attrs={'pts_time':3442857000})
156
+ ts.add_child(st)
157
+ print(ts)
158
+ """
159
+
160
+ def __init__(self, name, value="", attrs=None, ns=None):
161
+ self.name = name
162
+ self.value = value
163
+ self.depth = 0
164
+ self.namespace = NameSpace()
165
+ self.namespace.ns = ns
166
+ self.attr = None
167
+ self._handle_attrs(attrs)
168
+ self.children = []
169
+
170
+ def __repr__(self):
171
+ return self.mk()
172
+
173
+ def _handle_attrs(self, attrs):
174
+ if not attrs:
175
+ attrs = {}
176
+ if "xmlns" in attrs:
177
+ self.namespace.uri = attrs.pop("xmlns")
178
+ self.attrs = attrs
179
+
180
+ def attrs2nodes(self):
181
+ """
182
+ attrs2nodes attributes to elements
183
+ """
184
+ for k, v in self.attrs.items():
185
+ self.add_child(Node(name=key2xml(k), value=val2xml(v)), slot=0)
186
+ self.attrs = {}
187
+
188
+ def mk_ans(self, attrs):
189
+ """
190
+ mk_ans set namespace on attributes
191
+ """
192
+ new_attrs = {}
193
+ if self.namespace.all:
194
+ for k, v in attrs.items():
195
+ new_attrs[f"{self.namespace.ns}:{k}"] = v
196
+ return new_attrs
197
+
198
+ def chk_obj(self, obj):
199
+ """
200
+ chk_obj determines if
201
+ obj is self, or another obj
202
+ for self.set_ns and self.mk
203
+ """
204
+ if obj is None:
205
+ obj = self
206
+ return obj
207
+
208
+ def set_ns(self, ns=None):
209
+ """
210
+ set_ns set namespace on the Node
211
+ """
212
+ self.namespace.ns = ns
213
+
214
+ def rm_attr(self, attr):
215
+ """
216
+ rm_attr remove an attribute
217
+ """
218
+ self.attrs.pop(attr)
219
+
220
+ def add_attr(self, attr, value):
221
+ """
222
+ add_attr add an attribute
223
+ """
224
+ self.attrs[attr] = value
225
+
226
+ def set_depth(self):
227
+ """
228
+ set_depth is used to format
229
+ tabs in output
230
+ """
231
+ for child in self.children:
232
+ child.depth = self.depth + 1
233
+
234
+ def get_indent(self):
235
+ """
236
+ get_indent returns a string of spaces the required depth for a node
237
+ """
238
+ tab = " "
239
+ return tab * self.depth
240
+
241
+ def _rendrd_children(self, rendrd, ndent, name):
242
+ for child in self.children:
243
+ rendrd += self.mk(child)
244
+ return f"{rendrd}{ndent}</{name}>\n".replace(" >", ">")
245
+
246
+ def mk_name(self):
247
+ """
248
+ mk_name add namespace to node name
249
+ """
250
+ name = self.name
251
+ if self.namespace.ns:
252
+ name = f"{self.namespace.ns}:{name}"
253
+ return name
254
+
255
+ def rendr_attrs(self, ndent, name):
256
+ """
257
+ rendrd_attrs renders xml attributes
258
+ """
259
+ attrs = self.attrs
260
+ if self.namespace.all:
261
+ attrs = self.mk_ans(self.attrs)
262
+ new_attrs = mk_xml_attrs(attrs)
263
+ if self.depth == 0:
264
+ return f"{ndent}<{name} {self.namespace.xmlns()} {new_attrs}>"
265
+ return f"{ndent}<{name}{new_attrs}>"
266
+
267
+ def children_namespaces(self):
268
+ """
269
+ children_namespaces give children your namespace
270
+ """
271
+ for child in self.children:
272
+ child.namespace.ns = self.namespace.ns
273
+ child.namespace.all = self.namespace.all
274
+ child.namespace.uri = ""
275
+
276
+ def rendr_all(self, ndent, name):
277
+ """
278
+ rendr_all renders the Node instance and it's children in xml.
279
+ """
280
+ rendrd = self.rendr_attrs(ndent, name)
281
+ if self.value:
282
+ return f"{rendrd}{self.value}</{name}>\n"
283
+ rendrd = f"{rendrd}\n"
284
+ rendrd.replace(" >", ">")
285
+ if self.children:
286
+ return self._rendrd_children(rendrd, ndent, name)
287
+ return rendrd.replace(">", "/>")
288
+
289
+ def mk(self, obj=None):
290
+ """
291
+ mk make the Node as xml.
292
+ """
293
+ obj = self.chk_obj(obj)
294
+ obj.set_depth()
295
+ obj.children_namespaces()
296
+ name = obj.mk_name()
297
+ ndent = obj.get_indent()
298
+ # obj.attrs2nodes()
299
+ if isinstance(obj, Comment):
300
+ return obj.mk(obj)
301
+ return obj.rendr_all(ndent, name)
302
+
303
+ def add_child(self, child, slot=None):
304
+ """
305
+ add_child adds a child node
306
+ set slot to insert at index slot.
307
+ """
308
+ if not slot:
309
+ slot = len(self.children)
310
+ self.children = self.children[:slot] + [child] + self.children[slot:]
311
+
312
+ def rm_child(self, child):
313
+ """
314
+ rm_child remove a child
315
+
316
+ example:
317
+ a_node.rm_child(a_node.children[3])
318
+ """
319
+ self.children.remove(child)
320
+
321
+ def add_comment(self, comment, slot=None):
322
+ """
323
+ add_comment add a Comment node
324
+ """
325
+ self.add_child(Comment(comment), slot)
326
+
327
+
328
+ class Comment(Node):
329
+ """
330
+ The Comment class is to create a Node representing a xml comment.
331
+
332
+ An instance of Comment has:
333
+
334
+ name : <!-- name -->
335
+ depth: tab depth for printing (automatically set)
336
+
337
+ Since Comment is a Node, it also has attrs, value and children but
338
+ these are ignored. cf etree.Comment
339
+ Use like this:
340
+
341
+ from scte35.xml import Comment, Node
342
+
343
+ n = Node('root')
344
+ c = Comment('my first comment')
345
+
346
+ n.add_child(c)
347
+ print(n)
348
+
349
+ See also Node.add_comment:
350
+ """
351
+
352
+ def mk(self, obj=None):
353
+ obj = self.chk_obj(obj)
354
+ obj.set_depth()
355
+ return f"{obj.get_indent()}<!-- {obj.name} -->\n"
@@ -0,0 +1,365 @@
1
+ #!python
2
+
3
+ """
4
+ scte35 command line SCTE35 decoder.
5
+
6
+ """
7
+
8
+
9
+ import select
10
+ import sys
11
+ from iframes import IFramer
12
+ from new_reader import reader
13
+ from scte35 import Cue, Stream, print2, version
14
+ from scte35.hls import cli as hlscli
15
+ from scte35.sixfix import sixfix
16
+ from sideways import cli as sidecli
17
+
18
+ REV = "\033[7;1m"
19
+ NORM = "\033[27m\033[0m"
20
+ NORM = "\033[0m"
21
+ BLUE = "\033[36;1;1m"
22
+ G = "\033[32;1;1m"
23
+ B = "\033[7;1m"
24
+ U = "\033[m"
25
+
26
+
27
+ class SupaStream(Stream):
28
+ """
29
+ SupaStream is subclass of Stream used
30
+ to print raw SCTE-35 packets.
31
+ """
32
+
33
+ def _parse_scte35(self, pkt, pid):
34
+ print2(pkt)
35
+ print2("")
36
+ super()._parse_scte35(pkt, pid)
37
+
38
+
39
+ def mk_sidecar(cue):
40
+ """
41
+ mk_sidecar generates a sidecar file with the SCTE-35 Cues
42
+ """
43
+ pts = 0.0
44
+ with open("sidecar.txt", "a") as sidecar:
45
+ cue.show()
46
+ if cue.packet_data.pts:
47
+ pts = cue.packet_data.pts
48
+ data = f"{pts},{cue.encode()}\n"
49
+ sidecar.write(data)
50
+
51
+
52
+ HELP = f"""
53
+ {BLUE} scte35 cli tool {U}
54
+
55
+ {B} Default {U} {BLUE}The default action is to read a input and write a SCTE-35 output.{U}
56
+
57
+ {BLUE}Inputs {U} mpegts, base64, hex, json, xml, and xmlbin{U}.
58
+
59
+ {BLUE}Outputs{U} base64, bytes, hex, int, json, xml, and xmlbin.{U}
60
+
61
+ {BLUE}scte35 can read from {U} strings, files, stdin, http(s), multicast, and Udp.
62
+
63
+ Input {U} Output {U}
64
+ {U}{BLUE} mpegts {U} {U}{BLUE} base64 {NORM} scte35 https://example.com/video.ts base64
65
+ {U}{BLUE} xml {U} {U}{BLUE} bytes {NORM} scte35 bytes < xml.xml
66
+ {U}{BLUE} base64 {U} {U}{BLUE} hex {NORM} scte35 '/DAWAAAAAAAAAP/wBQb+AKmKxwAACzuu2Q==' hex
67
+ {U}{BLUE} xmlbin {U} {U}{BLUE} int {NORM} scte35 int < xml.xml
68
+ {U}{BLUE} mpegts {U} {U}{BLUE} json {NORM} scte35 video.ts
69
+ {U}{BLUE} json {U} {U}{BLUE} xml {NORM} scte35 < json.json xml
70
+ {U}{BLUE} hex {U} {U}{BLUE} xmlbin {NORM} scte35 0xfc301600000000000000fff00506fe00a98ac700000b3baed9 xmlbin
71
+
72
+ {B} hls {U}{NORM}{BLUE} SCTE-35 hls decode help:{U} scte35 hls help
73
+
74
+ scte35 hls https://example.com/master.m3u8{U}
75
+
76
+ {B} iframes {U}{BLUE} show MPEGTS iframes{NORM} scte35 iframes video.ts
77
+
78
+ {B} packets {U}{NORM}{BLUE} Print raw SCTE-35 packets:{NORM} scte35 packets udp://@235.35.3.5:3535
79
+
80
+ {B} proxy {U}{NORM}{BLUE} Parse a stream and copy it to stdout:{NORM} scte35 proxy video.ts
81
+
82
+ {B} pts {U}{NORM}{BLUE} Print PTS from mpegts video:{NORM} scte35 pts video.ts
83
+
84
+ {B} sidecar {U}{NORM}{BLUE} Create a sidecar file:{NORM} scte35 sidecar video.ts
85
+
86
+ {B} sixfix {U}{NORM}{BLUE} Fix SCTE-35 data mangled by ffmpeg:{NORM} scte35 sixfix video.ts
87
+
88
+ {B} show {U}{NORM}{BLUE} Probe mpegts video:{NORM} scte35 show video.ts
89
+
90
+ {B} version {U}{NORM}{BLUE} Show version:{NORM} scte35 version
91
+
92
+ {B} help {U}{NORM} {BLUE}Help:{NORM} scte35 help
93
+
94
+ """
95
+
96
+
97
+ def mk_args(keys):
98
+ """
99
+ mk_args generates a list of args for inputs
100
+ if no args are present,read from sys.stdin.buffer
101
+ """
102
+ args = [arg for arg in sys.argv[1:] if arg not in keys]
103
+ return args
104
+
105
+
106
+ # print_map functions
107
+
108
+
109
+ def hls():
110
+ sys.argv.remove("hls")
111
+ ## if "encode" in sys.argv:
112
+ ## sidecli()
113
+ ## else:
114
+ hlscli()
115
+
116
+
117
+ def print_help():
118
+ """
119
+ print_help checks sys.argv for the word help
120
+ and displays the help if found
121
+ """
122
+ print2(HELP)
123
+ sys.exit()
124
+
125
+
126
+ def print_version():
127
+ """
128
+ print_version print the scte35 version
129
+ """
130
+ print2(version)
131
+
132
+
133
+ print_map = {
134
+ "hls": hls,
135
+ "help": print_help,
136
+ "version": print_version,
137
+ }
138
+
139
+
140
+ def chk_print_map():
141
+ """
142
+ chk_print_map checks for print_map.keys() in sys.argv
143
+ """
144
+ for k, v in print_map.items():
145
+ if k in sys.argv:
146
+ v()
147
+ sys.exit()
148
+
149
+
150
+ # functions for mpegts_map
151
+
152
+
153
+ def iframe_chk(this):
154
+ """
155
+ iframe_chk show iframes pts
156
+ for a mpegts video.
157
+ """
158
+ iframer = IFramer()
159
+ iframer.do(this)
160
+
161
+
162
+ def packet_chk(this):
163
+ """
164
+ packet_chk checks for the packet keyword
165
+ and displays SCTE-35 packets if present.
166
+ """
167
+ supa = SupaStream(this)
168
+ supa.decode()
169
+
170
+
171
+ def proxy_chk(this):
172
+ """
173
+ proxy_chk checks for the proxy keyword
174
+ and proxies the stream to stdout if present.
175
+ proxy_chk also writes pts,cue pairs to sidecar.txt
176
+ """
177
+ strm = Stream(this)
178
+ strm.proxy(func=mk_sidecar)
179
+
180
+
181
+ def pts_chk(this):
182
+ """
183
+ pts_chk is used to display PTS.
184
+ """
185
+ strm = Stream(this)
186
+ strm.show_pts()
187
+
188
+
189
+ def show_chk(this):
190
+ """
191
+ show_chk checks for the show keyword
192
+ and displays the streams if present.
193
+ """
194
+ strm = Stream(this)
195
+ strm.show()
196
+
197
+
198
+ def sidecar_chk(this):
199
+ """
200
+ sidecar_chk checks for the sidecar keyword and
201
+ generates a sidecar file if present.
202
+ """
203
+ strm = Stream(this)
204
+ strm.decode(func=mk_sidecar)
205
+
206
+
207
+ mpegts_map = {
208
+ "packets": packet_chk,
209
+ "proxy": proxy_chk,
210
+ "pts": pts_chk,
211
+ "show": show_chk,
212
+ "sidecar": sidecar_chk,
213
+ "sixfix": sixfix,
214
+ "iframes": iframe_chk,
215
+ }
216
+
217
+
218
+ def chk_mpegts_map():
219
+ """
220
+ chk_mpegts_map check sys.argv for mpegts_map keys
221
+ """
222
+ m_keys = list(mpegts_map.keys())
223
+ args = mk_args(m_keys)
224
+ for key in m_keys:
225
+ if key in sys.argv:
226
+ for arg in args:
227
+ mpegts_map[key](arg)
228
+ sys.exit()
229
+
230
+
231
+ # functions for funk_map
232
+
233
+
234
+ def base64_out(cue):
235
+ """
236
+ print SCTE-35 from mpegts as base64
237
+ """
238
+ print2(cue.base64())
239
+
240
+
241
+ def bytes_out(cue):
242
+ """
243
+ print SCTE-35 from mpegts as base64
244
+ """
245
+ print2(cue.bites)
246
+
247
+
248
+ def hex_out(cue):
249
+ """
250
+ print SCTE-35 from mpegts as hex
251
+ """
252
+ print2(cue.hex())
253
+
254
+
255
+ def int_out(cue):
256
+ """
257
+ print SCTE-35 from mpegts as int
258
+ """
259
+ print2(cue.int())
260
+
261
+
262
+ def json_out(cue):
263
+ """
264
+ print SCTE-35 from mpegts as json
265
+ """
266
+ cue.show()
267
+
268
+
269
+ def xml_out(cue):
270
+ """
271
+ xml_out prints cue as xml
272
+ """
273
+ print2(cue.xml())
274
+
275
+
276
+ def xmlbin_out(cue):
277
+ """
278
+ xml_out prints cue as xml
279
+ """
280
+ print2(cue.xmlbin())
281
+
282
+
283
+ funk_map = {
284
+ "base64": base64_out,
285
+ "bytes": bytes_out,
286
+ "hex": hex_out,
287
+ "int": int_out,
288
+ "json": json_out,
289
+ "xml": xml_out,
290
+ "xmlbin": xmlbin_out,
291
+ }
292
+
293
+
294
+ def funk():
295
+ """
296
+ return a func
297
+ if a key in out_map
298
+ is also in sys.argv
299
+ """
300
+ func = json_out
301
+ for k, v in funk_map.items():
302
+ if k in sys.argv:
303
+ func = v
304
+ return func
305
+
306
+
307
+ def to_funk(this):
308
+ """
309
+ to_funk prints a cue in a variety of formats.
310
+ """
311
+ if this in ["", b""]:
312
+ return
313
+ try:
314
+ # mpegts streams handled here.
315
+ strm = Stream(this)
316
+ strm.decode(func=funk()) # funk() works here
317
+ except: # try to load json or xml
318
+ try:
319
+ cue = Cue()
320
+ cue.load(this)
321
+ except:
322
+ try:
323
+ cue = Cue(this)
324
+ except:
325
+ print("Bad Data... I think")
326
+ if cue:
327
+ funk()(cue) # func works here too.
328
+
329
+
330
+ def chk_stdin(args):
331
+ """
332
+ chk_stdin autodetects input from stdin.
333
+
334
+ """
335
+ readable, _, _ = select.select([sys.stdin], [], [], 0)
336
+ if sys.stdin in readable: # check stdin for data
337
+ one = reader(sys.stdin.buffer).read(1)
338
+ if one not in [b"G"]: # is this a packet?
339
+ two = reader(sys.stdin.buffer).read()
340
+ args.append((one + two).decode()) # no rewind on stdin
341
+ else:
342
+ reader(sys.stdin.buffer).read(187) # drop first packet
343
+ Stream(sys.stdin.buffer).decode(func=funk())
344
+ sys.exit()
345
+ return args
346
+
347
+
348
+ def chk_funk_map():
349
+ """
350
+ chk_func_map checks for func_map.keys() in sys.argv
351
+ """
352
+ funk_keys = list(funk_map.keys())
353
+ args = mk_args(funk_keys)
354
+ args = chk_stdin(args)
355
+ if args:
356
+ [to_funk(arg) for arg in args] # multiple file input
357
+ sys.exit()
358
+
359
+
360
+ if __name__ == "__main__":
361
+ if len(sys.argv) < 2:
362
+ sys.argv.append("json")
363
+ chk_print_map()
364
+ chk_mpegts_map()
365
+ chk_funk_map()