forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBce0dca2Tahinli6 days ago3957 commits

splice-eac3-dependent.py214 lines, 7.2 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Splice E-AC-3 dependent substreams onto an independent stream (test-fixture tool).
3
4usage: splice-eac3-dependent.py <independent.eac3> <dependent.eac3> <chanmap-hex> <out.eac3> <dep.convsnr.txt>
5
6ffmpeg's E-AC-3 encoder stops at 5.1, so a 7.1 fixture cannot be encoded directly. This
7builds one from two ordinary encodes: each output packet is one independent syncframe
8followed by one dependent syncframe. The dependent frame is the second stream's frame with
9strmtyp set to 1 (dependent) and the 16-bit custom channel map (Table E2.5) inserted where
10bsi() reads it, the one field a dependent header carries and an independent one does not.
11The map is written bit 15 first, so 0x8000 is L and 0x0001 is LFE.
12
13The dependent source is an independent frame, and an independent frame carries fields a
14dependent one does not: convexpstr in audfrm() and convsnroffste in each audblk(). Their
15bit positions come from the table in <dep.convsnr.txt> (one "position flag" row per block,
16six per frame, recorded by the crate's own parser from the dependent source; see
17gen-ac3dep-fixtures.sh). Both streams must have the same frame count.
18
19Asserts the other preconditions: the source frames are independent, six blocks per frame,
20no AHT, and no mixing metadata (mixmdate = 0).
21"""
22import sys
23
24
25class Bits:
26 def __init__(self, data):
27 self.data, self.pos = data, 0
28
29 def read(self, n):
30 v = 0
31 for _ in range(n):
32 byte = self.data[self.pos >> 3]
33 v = (v << 1) | ((byte >> (7 - (self.pos & 7))) & 1)
34 self.pos += 1
35 return v
36
37
38def bits_of(data):
39 return [(byte >> i) & 1 for byte in data for i in range(7, -1, -1)]
40
41
42def to_bytes(bitlist):
43 """Pack bits to bytes, zero-padding to a whole 16-bit word (frames are even-sized)."""
44 bitlist = list(bitlist)
45 while len(bitlist) % 16:
46 bitlist.append(0)
47 out = bytearray()
48 for i in range(0, len(bitlist), 8):
49 v = 0
50 for b in bitlist[i:i + 8]:
51 v = (v << 1) | b
52 out.append(v)
53 return bytes(out)
54
55
56def frames(data):
57 pos = 0
58 while pos < len(data):
59 assert data[pos:pos + 2] == b"\x0b\x77", "not at a sync word"
60 size = (((data[pos + 2] & 7) << 8) | data[pos + 3]) + 1
61 size *= 2
62 yield data[pos:pos + size]
63 pos += size
64
65
66def audfrm_convexpstr_span(bits, pos, acmod, lfeon, nfchans):
67 """Bit span [start, end) of the convexpstr fields in an independent 6-block audfrm().
68
69 Annex E sends convexpstr (5 bits per full-bandwidth channel) in independent substreams
70 only. Walks audfrm() the way eac3.rs does, for the case the splice supports: six blocks,
71 no AHT, expstre set.
72 """
73 p = pos
74 expstre, ahte = bits[p], bits[p + 1]
75 p += 2
76 assert ahte == 0, "splice expects ahte=0"
77 p += 2 + 8 # snroffststr, then transproce..spxattene (eight flags)
78 cplinu = [0] * 6
79 if acmod >= 2:
80 cplstre = [0] * 6
81 cplinu[0] = bits[p]
82 p += 1
83 for blk in range(1, 6):
84 cplstre[blk] = bits[p]
85 p += 1
86 if cplstre[blk]:
87 cplinu[blk] = bits[p]
88 p += 1
89 else:
90 cplinu[blk] = cplinu[blk - 1]
91 if expstre:
92 for blk in range(6):
93 if cplinu[blk]:
94 p += 2 # cplexpstr
95 p += 2 * nfchans # chexpstr per channel
96 else:
97 if acmod >= 2 and any(cplinu):
98 p += 5 # frmcplexpstr
99 p += 5 * nfchans # frmchexpstr per channel
100 if lfeon:
101 p += 6 # lfeexpstr per block
102 start = p
103 p += 5 * nfchans # convexpstr, present because numblkscod == 3
104 return start, p
105
106
107# Full-bandwidth channels per acmod (Table 5.8).
108FBW_CHANNELS = {0: 2, 1: 1, 2: 2, 3: 3, 4: 3, 5: 4, 6: 4, 7: 5}
109
110
111def dependent_frame(frame, chanmap, convsnr):
112 bits = bits_of(frame)
113 r = Bits(frame)
114 r.pos = 16
115 assert r.read(2) == 0, "source frame must be independent"
116 r.read(3) # substreamid
117 r.read(11) # frmsiz, rewritten below
118 fscod = r.read(2)
119 if fscod == 3:
120 r.read(2) # fscod2
121 numblkscod = 3
122 else:
123 numblkscod = r.read(2)
124 assert numblkscod == 3, "splice expects six blocks per frame"
125 acmod = r.read(3)
126 lfeon = r.read(1)
127 r.read(5) # bsid
128 r.read(5) # dialnorm
129 if r.read(1):
130 r.read(8) # compr
131 if acmod == 0:
132 r.read(5) # dialnorm2
133 if r.read(1):
134 r.read(8) # compr2
135 insert_at = r.pos
136 nfchans = FBW_CHANNELS[acmod]
137 # Walk bsi() past mixmdate (asserted zero), infomdate and addbsi to audfrm().
138 p = insert_at
139 assert bits[p] == 0, "mixing metadata (mixmdate) is not spliceable"
140 p += 1
141 if bits[p]: # infomdate: flag, bsmod(3), copyrightb, origbs, then mode-dependent fields
142 p += 1 + 3 + 1 + 1
143 if acmod == 2:
144 p += 4 # dsurmod, dheadphonmod
145 if acmod >= 6:
146 p += 2 # dsurexmod
147 if bits[p]: # mixlevel
148 p += 1 + 5 + 2 + 1
149 else:
150 p += 1
151 if acmod == 0:
152 if bits[p]:
153 p += 1 + 5 + 2 + 1
154 else:
155 p += 1
156 if fscod < 3:
157 p += 1 # sourcefscod
158 else:
159 p += 1
160 if bits[p]: # addbsi
161 p += 1 + 6
162 addbsil = int("".join(map(str, bits[p - 6:p])), 2)
163 p += (addbsil + 1) * 8
164 else:
165 p += 1
166 audfrm = p
167 cstart, cend = audfrm_convexpstr_span(bits, audfrm, acmod, lfeon, nfchans)
168
169 # Independent-only fields to drop: convexpstr in audfrm(), and convsnroffste (a flag, plus
170 # ten bits of convsnroffst when set) at the start of each audblk()'s bit allocation.
171 spans = [(cstart, cend)]
172 for pos, flag in convsnr:
173 spans.append((pos, pos + (11 if flag else 1)))
174 spans.sort()
175 new = bits[:16] + [0, 1] + bits[18:insert_at] # strmtyp = 1, substreamid kept
176 new += [1] + [(chanmap >> (15 - i)) & 1 for i in range(16)] # chanmap present
177 at = insert_at
178 for start, end in spans:
179 new += bits[at:start]
180 at = end
181 new += bits[at:]
182 frame_bytes = len(to_bytes(new))
183 frmsiz = frame_bytes // 2 - 1
184 assert frmsiz < 2048, "frame too large for frmsiz"
185 new[21:32] = [(frmsiz >> (10 - i)) & 1 for i in range(11)]
186 return to_bytes(new)
187
188
189def read_convsnr(path, frames_count):
190 """Per-frame lists of (bit position, flag) for convsnroffste, six blocks per frame."""
191 with open(path) as f:
192 rows = [tuple(int(x) for x in line.split()) for line in f if line.strip()]
193 assert len(rows) == 6 * frames_count, "convsnr table does not match the frame count"
194 return [rows[6 * i:6 * i + 6] for i in range(frames_count)]
195
196
197def main():
198 ind_path, dep_path, chanmap_hex, out_path, convsnr_path = sys.argv[1:6]
199 chanmap = int(chanmap_hex, 16)
200 with open(ind_path, "rb") as f:
201 ind = list(frames(f.read()))
202 with open(dep_path, "rb") as f:
203 dep = list(frames(f.read()))
204 assert len(ind) == len(dep), f"frame counts differ: {len(ind)} vs {len(dep)}"
205 table = read_convsnr(convsnr_path, len(dep))
206 with open(out_path, "wb") as out:
207 for a, b, convsnr in zip(ind, dep, table):
208 out.write(a)
209 out.write(dependent_frame(b, chanmap, convsnr))
210 print(f"wrote {len(ind)} packets to {out_path}")
211
212
213if __name__ == "__main__":
214 main()