bdmvkit 0.5.0__tar.gz → 0.7.0__tar.gz

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.
Files changed (34) hide show
  1. {bdmvkit-0.5.0/bdmvkit.egg-info → bdmvkit-0.7.0}/PKG-INFO +20 -5
  2. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/README.md +19 -4
  3. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit/__init__.py +1 -1
  4. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit/clip.py +1 -1
  5. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit/disc.py +12 -8
  6. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit/formats.py +27 -1
  7. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit/igs.py +11 -28
  8. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit/m2ts.py +49 -0
  9. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit/nav.py +30 -5
  10. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit/playlist.py +5 -4
  11. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit/program.py +10 -1
  12. {bdmvkit-0.5.0 → bdmvkit-0.7.0/bdmvkit.egg-info}/PKG-INFO +20 -5
  13. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit.egg-info/SOURCES.txt +1 -0
  14. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/pyproject.toml +1 -1
  15. bdmvkit-0.7.0/tests/test_dts.py +130 -0
  16. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/tests/test_menus.py +9 -0
  17. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/COPYING +0 -0
  18. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/COPYING.LESSER +0 -0
  19. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit/__main__.py +0 -0
  20. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit/encode.py +0 -0
  21. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit/errors.py +0 -0
  22. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit/hdmv.py +0 -0
  23. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit/pgs.py +0 -0
  24. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit/uops.py +0 -0
  25. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit.egg-info/dependency_links.txt +0 -0
  26. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit.egg-info/entry_points.txt +0 -0
  27. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/bdmvkit.egg-info/top_level.txt +0 -0
  28. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/setup.cfg +0 -0
  29. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/tests/test_disc.py +0 -0
  30. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/tests/test_files.py +0 -0
  31. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/tests/test_motion.py +0 -0
  32. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/tests/test_nav.py +0 -0
  33. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/tests/test_pgs.py +0 -0
  34. {bdmvkit-0.5.0 → bdmvkit-0.7.0}/tests/test_popup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bdmvkit
3
- Version: 0.5.0
3
+ Version: 0.7.0
4
4
  Summary: Blu-ray (BDMV) authoring in pure Python: playlists, clip information, HDMV navigation, PGS subtitles
5
5
  Author: kajisho5
6
6
  License-Expression: LGPL-3.0-or-later
@@ -35,14 +35,15 @@ only to encode.
35
35
 
36
36
  日本語の説明は [README.ja.md](README.ja.md) にあります。
37
37
 
38
- **Status: 0.5.** Titles with chapters, sound and subtitle tracks;
38
+ **Status: 0.7.** Titles with chapters, sound and subtitle tracks;
39
39
  playlists (in order, at random or shuffled) and play all; menus whose
40
40
  buttons start titles, chapters, playlists and other menus, switch sound and
41
41
  subtitle tracks, or open a menu on a chosen button; loop counts, end-action
42
42
  overrides, link transitions, remote keys a title turns off, and 720p. This
43
43
  navigation is the one [oncemore](https://github.com/kajisho5/oncemore)
44
44
  writes, byte for byte. 0.4 adds pop-up menus over a playing title, 0.5
45
- menus with motion or music.
45
+ menus with motion or music, 0.6 button streams for 720p menus, 0.7 DTS-HD
46
+ sound tracks.
46
47
 
47
48
  ## Why
48
49
 
@@ -95,6 +96,18 @@ disc.add_title("feature.m2ts", audio=[("ac3", 2, "en"), ("lpcm", 2, "en"), ("ac3
95
96
 
96
97
  `Disc.write` checks that every track a title declares is in its clip.
97
98
 
99
+ DTS copied with its extensions is declared as what it is: `"dtshd"` (DTS-HD
100
+ High Resolution Audio) or `"dtshd_ma"` (DTS-HD Master Audio), with its
101
+ sampling rate when it is above 48 kHz (`("dtshd_ma", 8, "en", 96000)`;
102
+ LPCM may run at 96 or 192 kHz too). ffmpeg marks a DTS stream in the clip by
103
+ its channels, not by its extensions, so `Disc.write` marks each DTS track
104
+ with the type the title declares, in the copy it puts on the disc:
105
+
106
+ ```python
107
+ encode_clip("feature.mkv", "feature.m2ts", audio=[AudioTrack("feature.mkv", "copy", 8)])
108
+ disc.add_title("feature.m2ts", audio=[("dtshd_ma", 8, "en")])
109
+ ```
110
+
98
111
  A menu is a picture and its buttons. Each button is a picture of how it
99
112
  looks when selected (and, if given, when activated and before it is
100
113
  selected), placed on the 1920 x 1080 menu, and a link:
@@ -117,7 +130,8 @@ actions: `title:<n>`, `chapter:<n>:<c>`, `playlist:<id>`, `playall`,
117
130
  `resume`, `audio:<n>`, `subtitle:<n>` or `subtitle:off`, and `stop`. The
118
131
  arrow keys go to the nearest button that way unless a button's `nav` says
119
132
  (`{"down": "scene2"}`). `bdmvkit.igs` makes the button stream on its own,
120
- for other tools.
133
+ for other tools: `igs.ig_stream(buttons, frame_rate, size=(1280, 720))`
134
+ places the buttons on a 720p menu.
121
135
 
122
136
  ```python
123
137
  disc = Disc(title_key="menu:main")
@@ -181,7 +195,8 @@ How the disc is laid out:
181
195
  progressive frames in a 1080i stream, as the format asks. A program can
182
196
  also be 720p (23.976, 50, 59.94; 25 and 29.97 go on at twice their rate);
183
197
  `encode_clip` makes 1080 clips.
184
- * Sound is AC-3, LPCM or DTS.
198
+ * Sound is AC-3, LPCM, DTS, DTS-HD High Resolution Audio or DTS-HD Master
199
+ Audio (a DTS-HD track above 48 kHz is marked as such over its 48 kHz core).
185
200
  * Subtitles are PGS streams muxed into the clip. `pgs.write_sup` makes them
186
201
  from pictures, and `encode_clip(..., sups=[...])` muxes them in.
187
202
  * First play and the Top Menu key open the first menu, or start title 1
@@ -18,14 +18,15 @@ only to encode.
18
18
 
19
19
  日本語の説明は [README.ja.md](README.ja.md) にあります。
20
20
 
21
- **Status: 0.5.** Titles with chapters, sound and subtitle tracks;
21
+ **Status: 0.7.** Titles with chapters, sound and subtitle tracks;
22
22
  playlists (in order, at random or shuffled) and play all; menus whose
23
23
  buttons start titles, chapters, playlists and other menus, switch sound and
24
24
  subtitle tracks, or open a menu on a chosen button; loop counts, end-action
25
25
  overrides, link transitions, remote keys a title turns off, and 720p. This
26
26
  navigation is the one [oncemore](https://github.com/kajisho5/oncemore)
27
27
  writes, byte for byte. 0.4 adds pop-up menus over a playing title, 0.5
28
- menus with motion or music.
28
+ menus with motion or music, 0.6 button streams for 720p menus, 0.7 DTS-HD
29
+ sound tracks.
29
30
 
30
31
  ## Why
31
32
 
@@ -78,6 +79,18 @@ disc.add_title("feature.m2ts", audio=[("ac3", 2, "en"), ("lpcm", 2, "en"), ("ac3
78
79
 
79
80
  `Disc.write` checks that every track a title declares is in its clip.
80
81
 
82
+ DTS copied with its extensions is declared as what it is: `"dtshd"` (DTS-HD
83
+ High Resolution Audio) or `"dtshd_ma"` (DTS-HD Master Audio), with its
84
+ sampling rate when it is above 48 kHz (`("dtshd_ma", 8, "en", 96000)`;
85
+ LPCM may run at 96 or 192 kHz too). ffmpeg marks a DTS stream in the clip by
86
+ its channels, not by its extensions, so `Disc.write` marks each DTS track
87
+ with the type the title declares, in the copy it puts on the disc:
88
+
89
+ ```python
90
+ encode_clip("feature.mkv", "feature.m2ts", audio=[AudioTrack("feature.mkv", "copy", 8)])
91
+ disc.add_title("feature.m2ts", audio=[("dtshd_ma", 8, "en")])
92
+ ```
93
+
81
94
  A menu is a picture and its buttons. Each button is a picture of how it
82
95
  looks when selected (and, if given, when activated and before it is
83
96
  selected), placed on the 1920 x 1080 menu, and a link:
@@ -100,7 +113,8 @@ actions: `title:<n>`, `chapter:<n>:<c>`, `playlist:<id>`, `playall`,
100
113
  `resume`, `audio:<n>`, `subtitle:<n>` or `subtitle:off`, and `stop`. The
101
114
  arrow keys go to the nearest button that way unless a button's `nav` says
102
115
  (`{"down": "scene2"}`). `bdmvkit.igs` makes the button stream on its own,
103
- for other tools.
116
+ for other tools: `igs.ig_stream(buttons, frame_rate, size=(1280, 720))`
117
+ places the buttons on a 720p menu.
104
118
 
105
119
  ```python
106
120
  disc = Disc(title_key="menu:main")
@@ -164,7 +178,8 @@ How the disc is laid out:
164
178
  progressive frames in a 1080i stream, as the format asks. A program can
165
179
  also be 720p (23.976, 50, 59.94; 25 and 29.97 go on at twice their rate);
166
180
  `encode_clip` makes 1080 clips.
167
- * Sound is AC-3, LPCM or DTS.
181
+ * Sound is AC-3, LPCM, DTS, DTS-HD High Resolution Audio or DTS-HD Master
182
+ Audio (a DTS-HD track above 48 kHz is marked as such over its 48 kHz core).
168
183
  * Subtitles are PGS streams muxed into the clip. `pgs.write_sup` makes them
169
184
  from pictures, and `encode_clip(..., sups=[...])` muxes them in.
170
185
  * First play and the Top Menu key open the first menu, or start title 1
@@ -16,5 +16,5 @@
16
16
  from .disc import Disc, MenuButton
17
17
  from .errors import BdmvError
18
18
 
19
- __version__ = "0.5.0"
19
+ __version__ = "0.7.0"
20
20
  __all__ = ["Disc", "MenuButton", "BdmvError"]
@@ -32,7 +32,7 @@ def ep_map(entries):
32
32
 
33
33
  def clpi(scan, video_format, frame_rate, audio, pg=(), ig=False):
34
34
  """Clip information of one .m2ts: its streams, time span and EP map.
35
- audio: [(coding, channels, lang3)]; pg: [lang3]; ig: menu buttons."""
35
+ audio: [(coding, channels, lang3[, rate])]; pg: [lang3]; ig: menu buttons."""
36
36
  ts_type = bytes([0x80]) + b"HDMV" + bytes(9) + bytes(16)
37
37
  info = _u16(0) + _u8(1) + _u8(1) + _u32(0) + _u32(TS_RATE) + _u32(scan.packets) + \
38
38
  bytes(128) + _u16(len(ts_type)) + ts_type
@@ -36,7 +36,7 @@ import tempfile
36
36
 
37
37
  from . import encode, hdmv, igs, program
38
38
  from .errors import BdmvError
39
- from .formats import AUDIO_PID, CODECS, FORMATS, HEIGHT, PG_PID, WIDTH, lang3
39
+ from .formats import AUDIO_PID, CODECS, FORMATS, HEIGHT, PG_PID, WIDTH, lang3, rate_code
40
40
  from .m2ts import stream_pids
41
41
  from .program import parse_action
42
42
  from .nav import DIRS, Navigation, _write, chapter_marks, write_program # noqa: F401
@@ -114,17 +114,21 @@ class Disc:
114
114
  subtitles=(), end=None, default_audio=None, default_subtitle=None,
115
115
  prohibit=()):
116
116
  """Add a title; returns its number (1-based), its id in actions
117
- ("title:2"). audio: (codec, channels, language) per track, codec
118
- "ac3", "lpcm" or "dts"; languages are ISO 639-1 ("en") or 639-2
119
- ("eng") codes. end: the action when it ends (default: the next title
117
+ ("title:2"). audio: (codec, channels, language[, rate]) per track,
118
+ codec "ac3", "lpcm", "dts", "dtshd" (DTS-HD High Resolution) or
119
+ "dtshd_ma" (DTS-HD Master Audio); languages are ISO 639-1 ("en") or
120
+ 639-2 ("eng") codes; rate 48000 (the default), or 96000 or 192000
121
+ for LPCM and DTS-HD. end: the action when it ends (default: the next title
120
122
  with play_all). default_audio: the sound track the disc starts with;
121
123
  default_subtitle: the subtitle track shown from its start (else
122
124
  none); prohibit: remote keys it does not allow (uops.KEYS)."""
123
125
  if tuple(fps) not in FORMATS:
124
126
  raise BdmvError(f"{fps[0]}/{fps[1]} fps has no Blu-ray format")
125
- for codec, _, _ in audio:
127
+ for codec, _, _, *rate in audio:
126
128
  if codec not in CODECS:
127
- raise BdmvError(f"unknown audio codec {codec!r} (ac3, lpcm or dts)")
129
+ raise BdmvError(f"unknown audio codec {codec!r} "
130
+ f"({', '.join(CODECS)})")
131
+ rate_code(CODECS[codec], *rate)
128
132
  if not audio:
129
133
  raise BdmvError("a title needs at least one audio track")
130
134
  for name, k, n in (("default_audio", default_audio, len(audio)),
@@ -194,8 +198,8 @@ class Disc:
194
198
  end = t.end or (f"title:{n + 1}" if play_all and n < n_titles else None)
195
199
  titles.append(program.Title(
196
200
  str(n), t.clip, t.fps, list(t.chapters),
197
- [program.Audio(CODECS[c], ch, _lang(lang), k == t.default_audio)
198
- for k, (c, ch, lang) in enumerate(t.audio, 1)],
201
+ [program.Audio(CODECS[c], ch, _lang(lang), k == t.default_audio, *rate)
202
+ for k, (c, ch, lang, *rate) in enumerate(t.audio, 1)],
199
203
  [program.Subtitle(_lang(lang), k == t.default_subtitle)
200
204
  for k, lang in enumerate(t.subtitles, 1)], end, list(t.prohibit),
201
205
  popup=n in self.popups,
@@ -1,6 +1,8 @@
1
1
  """Numbers of the BD-ROM format bdmvkit writes: stream PIDs, coding types,
2
2
  video format and frame rate codes, languages."""
3
3
 
4
+ from .errors import BdmvError
5
+
4
6
  VERSION = b"0200" # of the navigation files
5
7
  WIDTH, HEIGHT = 1920, 1080
6
8
 
@@ -49,7 +51,16 @@ def video_codes(fps, video="1080"):
49
51
 
50
52
 
51
53
  CODING_H264, CODING_LPCM, CODING_AC3, CODING_DTS = 0x1B, 0x80, 0x81, 0x82
54
+ # DTS-HD High Resolution Audio and DTS-HD Master Audio: a DTS core with its
55
+ # extensions (the stream types of libbluray's bluray.h)
56
+ CODING_DTSHD, CODING_DTSHD_MA = 0x85, 0x86
52
57
  CODING_PG, CODING_IG = 0x90, 0x91
58
+ DTS_CODINGS = (CODING_DTS, CODING_DTSHD, CODING_DTSHD_MA)
59
+
60
+ # sampling_frequency of a sound track (bluray.h): 48, 96 and 192 kHz, and
61
+ # 96 or 192 kHz over a 48 kHz core (a DTS core runs at 48 kHz at most)
62
+ RATE_CODES = {48000: 1, 96000: 4, 192000: 5}
63
+ CORE_RATE_CODES = {96000: 14, 192000: 12}
53
64
 
54
65
  # ISO 639-1 -> ISO 639-2/B (the disc's codes)
55
66
  LANGS = {
@@ -67,4 +78,19 @@ def lang3(code):
67
78
  return LANGS.get((code or "").lower(), "und")
68
79
 
69
80
 
70
- CODECS = {"ac3": CODING_AC3, "lpcm": CODING_LPCM, "dts": CODING_DTS}
81
+ CODECS = {"ac3": CODING_AC3, "lpcm": CODING_LPCM, "dts": CODING_DTS, "dtshd": CODING_DTSHD,
82
+ "dtshd_ma": CODING_DTSHD_MA}
83
+ # the codings a track may have above 48 kHz
84
+ HIGH_RATE_CODINGS = (CODING_LPCM, CODING_DTSHD, CODING_DTSHD_MA)
85
+
86
+
87
+ def rate_code(coding, rate=48000):
88
+ """A sound track's sampling_frequency code; a DTS-HD track above 48 kHz
89
+ has its 48 kHz core's code."""
90
+ if rate != 48000 and coding not in HIGH_RATE_CODINGS:
91
+ raise BdmvError(f"{rate} Hz: only LPCM and DTS-HD tracks go above 48 kHz")
92
+ if coding in (CODING_DTSHD, CODING_DTSHD_MA) and rate in CORE_RATE_CODES:
93
+ return CORE_RATE_CODES[rate]
94
+ if rate not in RATE_CODES:
95
+ raise BdmvError(f"{rate} Hz: a sound track runs at 48, 96 or 192 kHz")
96
+ return RATE_CODES[rate]
@@ -34,7 +34,7 @@ DIRECTIONS = ("up", "down", "left", "right")
34
34
  @dataclasses.dataclass
35
35
  class Button:
36
36
  id: str
37
- x: int # top-left on the 1920 x 1080 frame
37
+ x: int # top-left on the frame (1920 x 1080, or 1280 x 720)
38
38
  y: int
39
39
  w: int
40
40
  h: int
@@ -124,10 +124,12 @@ def _objects(oid, w, h, pixels):
124
124
 
125
125
 
126
126
  def ig_stream(buttons, frame_rate, default=None, popup=False, button_offset=0,
127
- follow_selection=False):
127
+ follow_selection=False, size=(WIDTH, HEIGHT)):
128
128
  """The buttons as an IG stream (.sup layout: "PG" segments).
129
129
 
130
- frame_rate: the menu clip's frame rate code (formats.FORMATS);
130
+ frame_rate: the menu clip's frame rate code (formats.FORMATS, or
131
+ FORMATS_720 with size (1280, 720)); size: the video's frame, which the
132
+ buttons are placed on;
131
133
  default: the id of the button selected when the menu starts (the
132
134
  first); follow_selection: keep the player's selection instead (a menu
133
135
  entered with a chosen button, set_button before playing it);
@@ -137,9 +139,10 @@ def ig_stream(buttons, frame_rate, default=None, popup=False, button_offset=0,
137
139
  ids = [b.id for b in buttons]
138
140
  if len(set(ids)) != len(ids):
139
141
  raise BdmvError("button ids must be unique")
142
+ width, height = size
140
143
  for b in buttons:
141
- if b.x < 0 or b.y < 0 or b.x + b.w > WIDTH or b.y + b.h > HEIGHT:
142
- raise BdmvError(f"button {b.id!r} is not inside the {WIDTH} x {HEIGHT} frame")
144
+ if b.x < 0 or b.y < 0 or b.x + b.w > width or b.y + b.h > height:
145
+ raise BdmvError(f"button {b.id!r} is not inside the {width} x {height} frame")
143
146
  for name in ("selected", "activated", "normal"):
144
147
  pic = getattr(b, name)
145
148
  if pic is not None and len(pic) != b.w * b.h * 4:
@@ -194,7 +197,7 @@ def ig_stream(buttons, frame_rate, default=None, popup=False, button_offset=0,
194
197
  # multiplexed; always on, or a pop-up (the Pop-up key shows it); no time-outs
195
198
  body = bytes([0x40 if popup else 0x00]) + bytes(10)
196
199
  body += (0).to_bytes(3, "big") + bytes([1]) + page # no user time-out; one page
197
- ics = struct.pack(">HHB", WIDTH, HEIGHT, frame_rate << 4)
200
+ ics = struct.pack(">HHB", width, height, frame_rate << 4)
198
201
  ics += struct.pack(">HB", 0, 0x80) # composition 0, epoch start
199
202
  ics += bytes([0xC0]) + len(body).to_bytes(3, "big") + body
200
203
  if len(ics) > pgs.MAX_SEGMENT:
@@ -206,28 +209,8 @@ def ig_stream(buttons, frame_rate, default=None, popup=False, button_offset=0,
206
209
  def patch_ig_stream_type(path, pmt_pid=PMT_PID, pid=IG_PID):
207
210
  """ffmpeg muxes the IG stream as a PGS stream (stream type 0x90): mark it
208
211
  0x91 in every PMT of the clip (and fix the section CRC)."""
209
- with open(path, "r+b") as f:
210
- data = bytearray(f.read())
211
- for off in range(0, len(data), 192):
212
- p = off + 4
213
- if (data[p + 1] & 0x1F) << 8 | data[p + 2] != pmt_pid or not data[p + 1] & 0x40:
214
- continue
215
- q = p + 4
216
- if data[p + 3] & 0x20:
217
- q += 1 + data[q]
218
- q += 1 + data[q] # pointer field
219
- length = (data[q + 1] & 0x0F) << 8 | data[q + 2]
220
- end = q + 3 + length - 4
221
- info = (data[q + 10] & 0x0F) << 8 | data[q + 11]
222
- e = q + 12 + info
223
- while e < end:
224
- es_pid = (data[e + 1] & 0x1F) << 8 | data[e + 2]
225
- if es_pid == pid:
226
- data[e] = CODING_IG
227
- e += 5 + ((data[e + 3] & 0x0F) << 8 | data[e + 4])
228
- data[end:end + 4] = crc32(bytes(data[q:end])).to_bytes(4, "big")
229
- f.seek(0)
230
- f.write(data)
212
+ from .m2ts import set_stream_types
213
+ set_stream_types(path, {pid: CODING_IG}, pmt_pid)
231
214
 
232
215
 
233
216
  def crc32(data):
@@ -100,3 +100,52 @@ def stream_pids(path, pmt_pid=PMT_PID):
100
100
  e += 5 + ((pkt[e + 3] & 0x0F) << 8 | pkt[e + 4])
101
101
  return pids
102
102
  raise BdmvError(f"{path}: no program map table (PID {pmt_pid:#06x})")
103
+
104
+
105
+ def set_stream_types(path, types, pmt_pid=PMT_PID, chunk=1 << 22):
106
+ """Give the elementary streams their stream types `types` ({PID: type})
107
+ in every program map table of the clip, in place, with the section CRC
108
+ made again. The clip is read a piece at a time and only its PMT packets
109
+ are written, so a long clip costs no more memory than a short one."""
110
+ from .igs import crc32
111
+ head = bytes([0x47, 0x40 | pmt_pid >> 8, pmt_pid & 0xFF]) # (a section starts in it)
112
+ chunk -= chunk % 192
113
+ with open(path, "r+b") as f:
114
+ pos = 0
115
+ while (data := f.read(chunk)):
116
+ i = data.find(head)
117
+ while i >= 0:
118
+ start = i - 4 # (the 4-byte packet header)
119
+ if start >= 0 and start % 192 == 0 and start + 192 <= len(data):
120
+ pkt = bytearray(data[start:start + 192])
121
+ if _retype(pkt, types, crc32):
122
+ f.seek(pos + start)
123
+ f.write(pkt)
124
+ f.seek(pos + len(data))
125
+ i = data.find(head, i + 1)
126
+ pos += len(data)
127
+
128
+
129
+ def _retype(pkt, types, crc32):
130
+ """Set the stream types in one PMT packet; whether it changed."""
131
+ p = 4
132
+ q = p + 4
133
+ if pkt[p + 3] & 0x20:
134
+ q += 1 + pkt[q]
135
+ q += 1 + pkt[q] # pointer field
136
+ if pkt[q] != 2: # (not a PMT section)
137
+ return False
138
+ end = q + 3 + ((pkt[q + 1] & 0x0F) << 8 | pkt[q + 2]) - 4
139
+ if end + 4 > len(pkt):
140
+ raise BdmvError("a program map table runs over its packet")
141
+ e = q + 12 + ((pkt[q + 10] & 0x0F) << 8 | pkt[q + 11])
142
+ changed = False
143
+ while e < end:
144
+ pid = (pkt[e + 1] & 0x1F) << 8 | pkt[e + 2]
145
+ if pid in types and pkt[e] != types[pid]:
146
+ pkt[e] = types[pid]
147
+ changed = True
148
+ e += 5 + ((pkt[e + 3] & 0x0F) << 8 | pkt[e + 4])
149
+ if changed:
150
+ pkt[end:end + 4] = crc32(bytes(pkt[q:end])).to_bytes(4, "big")
151
+ return changed
@@ -17,11 +17,11 @@ import shutil
17
17
 
18
18
  from .clip import clpi
19
19
  from .errors import BdmvError
20
- from .formats import CODING_AC3, video_codes
20
+ from .formats import AUDIO_PID, CODING_AC3, DTS_CODINGS, video_codes
21
21
  from .hdmv import (add, goto, if_at_least, if_equal, if_not_equal, index_bdmv, jump_object,
22
22
  jump_title, jump_title_reg, move, movie_objects, play_pl, play_pl_mark, resume,
23
23
  rnd, set_button, set_streams, set_subtitles)
24
- from .m2ts import scan_m2ts
24
+ from .m2ts import scan_m2ts, set_stream_types, stream_pids
25
25
  from .playlist import mpls
26
26
  from .program import parse_action, transition_key
27
27
  from .uops import mask
@@ -67,7 +67,7 @@ class Piece:
67
67
  clip: str # clip name, e.g. "00001"
68
68
  video_format: int
69
69
  frame_rate: int
70
- audio: list # [(coding, channels, lang3)]
70
+ audio: list # [(coding, channels, lang3, rate)]
71
71
  pg: list # subtitle tracks [lang3]
72
72
  marks: list # chapter starts, 45 kHz on the clip's time line
73
73
  end: int # end of the clip, 45 kHz
@@ -332,21 +332,26 @@ def write_program(program, out_dir, move=True):
332
332
  dest = os.path.join(out_dir, "BDMV", "STREAM", f"{name}.m2ts")
333
333
  if os.path.abspath(src) != os.path.abspath(dest):
334
334
  place(src, dest)
335
+ return dest
335
336
 
336
337
  pieces, chapters = {}, []
337
338
  for n, t in enumerate(p.titles, 1):
338
339
  name = f"{n:05d}"
339
340
  scan = scan_m2ts(t.clip)
340
341
  video_format, frame_rate = _codes(t.fps, p)
341
- audio = [(a.coding, a.channels, a.lang) for a in t.audio]
342
+ audio = [(a.coding, a.channels, a.lang, a.rate) for a in t.audio]
342
343
  pg = [s.lang for s in t.subtitles]
343
344
  marks = chapter_marks(t.chapters, scan)
344
345
  chapters.append(len(marks))
345
346
  pieces[t.id] = Piece(name, video_format, frame_rate, audio, pg, marks,
346
347
  scan.end_pts // 2, ig=t.popup, hold=t.hold, uo=mask(t.prohibit))
348
+ types = audio_stream_types(t)
347
349
  _write(out_dir, os.path.join("CLIPINF", f"{name}.clpi"),
348
350
  clpi(scan, video_format, frame_rate, audio, pg, ig=t.popup))
349
- clip(t.clip, name)
351
+ if types:
352
+ set_stream_types(clip(t.clip, name), types)
353
+ else:
354
+ clip(t.clip, name)
350
355
  for a in p.actions():
351
356
  kind, tid, c = parse_action(a)
352
357
  if kind == "chapter" and c > chapters[p.titles.index(p.title(tid))]:
@@ -404,6 +409,26 @@ def write_program(program, out_dir, move=True):
404
409
  "chapters": chapters}
405
410
 
406
411
 
412
+ def audio_stream_types(title):
413
+ """{PID: stream type} the title's clip needs changed so that its sound
414
+ tracks are marked as the title declares them. ffmpeg marks DTS by its
415
+ channels (0x85 above 6, else 0x82), not by the extensions it carries, so
416
+ a DTS track takes the declared DTS, DTS-HD or DTS-HD Master Audio type; a
417
+ track of another kind than declared is an error."""
418
+ have = stream_pids(title.clip)
419
+ out = {}
420
+ for k, a in enumerate(title.audio):
421
+ got = have.get(AUDIO_PID + k)
422
+ if got is None or got == a.coding:
423
+ continue
424
+ if got in DTS_CODINGS and a.coding in DTS_CODINGS:
425
+ out[AUDIO_PID + k] = a.coding
426
+ else:
427
+ raise BdmvError(f"title {title.id!r}: sound track {k + 1} has stream type "
428
+ f"{got:#04x} in {title.clip}, not the declared {a.coding:#04x}")
429
+ return out
430
+
431
+
407
432
  def _parts(p, nav, kind, ident, pieces):
408
433
  """(piece, first chapter, last chapter) of one Blu-ray title's playlist."""
409
434
  if kind == "title":
@@ -1,7 +1,7 @@
1
1
  """Playlists (.mpls): play items with their streams, and chapter marks."""
2
2
 
3
3
  from .formats import (AUDIO_PID, CODING_H264, CODING_IG, CODING_PG, IG_PID, PG_PID, VERSION,
4
- VIDEO_PID)
4
+ VIDEO_PID, rate_code)
5
5
  from .hdmv import _u8, _u16, _u32
6
6
 
7
7
 
@@ -10,9 +10,10 @@ def _video_attr(video_format, frame_rate):
10
10
 
11
11
 
12
12
  def _audio_attr(track):
13
- coding, channels, lang = track
13
+ """(coding, channels, lang3[, rate]): the rate 48000 unless given."""
14
+ coding, channels, lang, *rate = track
14
15
  fmt = 6 if channels > 2 else 3
15
- return bytes([coding, fmt << 4 | 1]) + lang.encode("ascii")
16
+ return bytes([coding, fmt << 4 | rate_code(coding, *rate)]) + lang.encode("ascii")
16
17
 
17
18
 
18
19
  def _pg_attr(lang, coding=CODING_PG):
@@ -22,7 +23,7 @@ def _pg_attr(lang, coding=CODING_PG):
22
23
  def mpls(items, marks, uo=0):
23
24
  """A playlist. items: [(clip name, in, out, video_format, frame_rate,
24
25
  audio, pg, ig, still[, uo])] played one after the other, times in 45 kHz
25
- on each clip's time line, audio [(coding, channels, lang3)], pg [lang3]
26
+ on each clip's time line, audio [(coding, channels, lang3, rate)], pg [lang3]
26
27
  (subtitles), ig: the clip carries menu buttons, still: 2 holds the
27
28
  last picture (a still menu), (1, s) holds it for s seconds, uo: the
28
29
  item's UO mask; marks: chapter marks as (item index, time); uo: the
@@ -24,6 +24,7 @@ Actions are strings:
24
24
  import dataclasses
25
25
 
26
26
  from .errors import BdmvError
27
+ from .formats import rate_code
27
28
  from .uops import KEYS
28
29
 
29
30
 
@@ -51,10 +52,12 @@ def parse_action(s):
51
52
  class Audio:
52
53
  """A sound track as the playlist declares it (the clip carries it with
53
54
  PID AUDIO_PID + its index, as encode.encode_clip muxes it)."""
54
- coding: int # formats.CODING_AC3, CODING_LPCM or CODING_DTS
55
+ coding: int # formats.CODING_AC3, CODING_LPCM, CODING_DTS,
56
+ # CODING_DTSHD or CODING_DTSHD_MA
55
57
  channels: int = 2
56
58
  lang: str = "und" # ISO 639-2 ("eng")
57
59
  default: bool = False # the disc starts with it (first play)
60
+ rate: int = 48000 # 96000 or 192000: LPCM and DTS-HD only
58
61
 
59
62
 
60
63
  @dataclasses.dataclass
@@ -223,6 +226,12 @@ class Program:
223
226
  for it in p.items:
224
227
  if it.title not in titles:
225
228
  raise BdmvError(f"playlist {p.id!r}: no title {it.title!r}")
229
+ for t in self.titles:
230
+ for k, a in enumerate(t.audio, 1):
231
+ try:
232
+ rate_code(a.coding, a.rate)
233
+ except BdmvError as e:
234
+ raise BdmvError(f"title {t.id!r}, sound track {k}: {e.message}") from e
226
235
  for x in self.titles + self.menus:
227
236
  for k in x.prohibit:
228
237
  if k not in KEYS:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bdmvkit
3
- Version: 0.5.0
3
+ Version: 0.7.0
4
4
  Summary: Blu-ray (BDMV) authoring in pure Python: playlists, clip information, HDMV navigation, PGS subtitles
5
5
  Author: kajisho5
6
6
  License-Expression: LGPL-3.0-or-later
@@ -35,14 +35,15 @@ only to encode.
35
35
 
36
36
  日本語の説明は [README.ja.md](README.ja.md) にあります。
37
37
 
38
- **Status: 0.5.** Titles with chapters, sound and subtitle tracks;
38
+ **Status: 0.7.** Titles with chapters, sound and subtitle tracks;
39
39
  playlists (in order, at random or shuffled) and play all; menus whose
40
40
  buttons start titles, chapters, playlists and other menus, switch sound and
41
41
  subtitle tracks, or open a menu on a chosen button; loop counts, end-action
42
42
  overrides, link transitions, remote keys a title turns off, and 720p. This
43
43
  navigation is the one [oncemore](https://github.com/kajisho5/oncemore)
44
44
  writes, byte for byte. 0.4 adds pop-up menus over a playing title, 0.5
45
- menus with motion or music.
45
+ menus with motion or music, 0.6 button streams for 720p menus, 0.7 DTS-HD
46
+ sound tracks.
46
47
 
47
48
  ## Why
48
49
 
@@ -95,6 +96,18 @@ disc.add_title("feature.m2ts", audio=[("ac3", 2, "en"), ("lpcm", 2, "en"), ("ac3
95
96
 
96
97
  `Disc.write` checks that every track a title declares is in its clip.
97
98
 
99
+ DTS copied with its extensions is declared as what it is: `"dtshd"` (DTS-HD
100
+ High Resolution Audio) or `"dtshd_ma"` (DTS-HD Master Audio), with its
101
+ sampling rate when it is above 48 kHz (`("dtshd_ma", 8, "en", 96000)`;
102
+ LPCM may run at 96 or 192 kHz too). ffmpeg marks a DTS stream in the clip by
103
+ its channels, not by its extensions, so `Disc.write` marks each DTS track
104
+ with the type the title declares, in the copy it puts on the disc:
105
+
106
+ ```python
107
+ encode_clip("feature.mkv", "feature.m2ts", audio=[AudioTrack("feature.mkv", "copy", 8)])
108
+ disc.add_title("feature.m2ts", audio=[("dtshd_ma", 8, "en")])
109
+ ```
110
+
98
111
  A menu is a picture and its buttons. Each button is a picture of how it
99
112
  looks when selected (and, if given, when activated and before it is
100
113
  selected), placed on the 1920 x 1080 menu, and a link:
@@ -117,7 +130,8 @@ actions: `title:<n>`, `chapter:<n>:<c>`, `playlist:<id>`, `playall`,
117
130
  `resume`, `audio:<n>`, `subtitle:<n>` or `subtitle:off`, and `stop`. The
118
131
  arrow keys go to the nearest button that way unless a button's `nav` says
119
132
  (`{"down": "scene2"}`). `bdmvkit.igs` makes the button stream on its own,
120
- for other tools.
133
+ for other tools: `igs.ig_stream(buttons, frame_rate, size=(1280, 720))`
134
+ places the buttons on a 720p menu.
121
135
 
122
136
  ```python
123
137
  disc = Disc(title_key="menu:main")
@@ -181,7 +195,8 @@ How the disc is laid out:
181
195
  progressive frames in a 1080i stream, as the format asks. A program can
182
196
  also be 720p (23.976, 50, 59.94; 25 and 29.97 go on at twice their rate);
183
197
  `encode_clip` makes 1080 clips.
184
- * Sound is AC-3, LPCM or DTS.
198
+ * Sound is AC-3, LPCM, DTS, DTS-HD High Resolution Audio or DTS-HD Master
199
+ Audio (a DTS-HD track above 48 kHz is marked as such over its 48 kHz core).
185
200
  * Subtitles are PGS streams muxed into the clip. `pgs.write_sup` makes them
186
201
  from pictures, and `encode_clip(..., sups=[...])` muxes them in.
187
202
  * First play and the Top Menu key open the first menu, or start title 1
@@ -23,6 +23,7 @@ bdmvkit.egg-info/dependency_links.txt
23
23
  bdmvkit.egg-info/entry_points.txt
24
24
  bdmvkit.egg-info/top_level.txt
25
25
  tests/test_disc.py
26
+ tests/test_dts.py
26
27
  tests/test_files.py
27
28
  tests/test_menus.py
28
29
  tests/test_motion.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "bdmvkit"
7
- version = "0.5.0"
7
+ version = "0.7.0"
8
8
  description = "Blu-ray (BDMV) authoring in pure Python: playlists, clip information, HDMV navigation, PGS subtitles"
9
9
  readme = "README.md"
10
10
  license = "LGPL-3.0-or-later"
@@ -0,0 +1,130 @@
1
+ """DTS-HD sound tracks: a title declares DTS-HD High Resolution or Master
2
+ Audio (above 48 kHz too), the clip's PMT is marked so (ffmpeg marks DTS by
3
+ its channels), and libbluray reads the streams as declared."""
4
+
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ import tempfile
9
+ import unittest
10
+
11
+ from bdmvkit import BdmvError, Disc
12
+ from bdmvkit.encode import AudioTrack, encode_clip
13
+ from bdmvkit.formats import (AUDIO_PID, CODING_DTS, CODING_DTSHD, CODING_DTSHD_MA, PMT_PID,
14
+ rate_code)
15
+ from bdmvkit.igs import crc32
16
+ from bdmvkit.m2ts import set_stream_types, stream_pids
17
+
18
+ from .test_disc import ENCODE_OK, LIBBLURAY, bluray_sim, source
19
+
20
+
21
+ def pmts(path):
22
+ """[(stream type of the first sound track, section CRC good)] of every
23
+ PMT of a clip."""
24
+ out = []
25
+ with open(path, "rb") as f:
26
+ while len(pkt := f.read(192)) == 192:
27
+ if (pkt[5] & 0x1F) << 8 | pkt[6] != PMT_PID or not pkt[5] & 0x40:
28
+ continue
29
+ q = 8 + 1 + pkt[8]
30
+ end = q + 3 + ((pkt[q + 1] & 0x0F) << 8 | pkt[q + 2])
31
+ e = q + 12 + ((pkt[q + 10] & 0x0F) << 8 | pkt[q + 11])
32
+ while (pkt[e + 1] & 0x1F) << 8 | pkt[e + 2] != AUDIO_PID:
33
+ e += 5 + ((pkt[e + 3] & 0x0F) << 8 | pkt[e + 4])
34
+ out.append((pkt[e], crc32(pkt[q:end]) == 0))
35
+ return out
36
+
37
+
38
+ class TestRates(unittest.TestCase):
39
+ def test_codes(self):
40
+ self.assertEqual(rate_code(CODING_DTS), 1)
41
+ self.assertEqual(rate_code(CODING_DTSHD_MA, 96000), 14) # (over a 48 kHz core)
42
+ self.assertEqual(rate_code(CODING_DTSHD, 192000), 12)
43
+ self.assertEqual(rate_code(0x80, 96000), 4) # LPCM
44
+ for coding, rate in ((0x81, 96000), (CODING_DTS, 96000), (CODING_DTSHD_MA, 44100)):
45
+ with self.assertRaises(BdmvError):
46
+ rate_code(coding, rate)
47
+
48
+ def test_add_title(self):
49
+ d = Disc()
50
+ d.add_title("a.m2ts", audio=[("dtshd_ma", 8, "en", 96000), ("dtshd", 6, "ja")])
51
+ a = d.program().titles[0].audio
52
+ self.assertEqual([(x.coding, x.rate) for x in a],
53
+ [(CODING_DTSHD_MA, 96000), (CODING_DTSHD, 48000)])
54
+ with self.assertRaises(BdmvError):
55
+ d.add_title("a.m2ts", audio=[("ac3", 2, "en", 96000)])
56
+ with self.assertRaises(BdmvError):
57
+ d.add_title("a.m2ts", audio=[("dts-hd", 6, "en")])
58
+
59
+
60
+ @unittest.skipUnless(ENCODE_OK, "needs ffmpeg with libx264")
61
+ class TestDtsHd(unittest.TestCase):
62
+ @classmethod
63
+ def setUpClass(cls):
64
+ cls.tmp = d = tempfile.mkdtemp(prefix="bdmvkit-dts-")
65
+ # a 5.1 DTS stream (ffmpeg's encoder writes the core alone; what
66
+ # bdmvkit does is the same for a core with extensions)
67
+ dts = os.path.join(d, "sound.dts")
68
+ subprocess.run(["ffmpeg", "-hide_banner", "-v", "error", "-y", "-f", "lavfi", "-i",
69
+ "sine=d=3:r=48000", "-ac", "6", "-c:a", "dca", "-strict", "-2", dts],
70
+ check=True)
71
+ cls.clip = encode_clip(source(os.path.join(d, "v.mp4"), 3, tone=False),
72
+ os.path.join(d, "v.m2ts"), fast=True,
73
+ audio=[AudioTrack(dts, "copy", 6)])
74
+
75
+ @classmethod
76
+ def tearDownClass(cls):
77
+ shutil.rmtree(cls.tmp, ignore_errors=True)
78
+
79
+ def write(self, *audio):
80
+ out = tempfile.mkdtemp(dir=self.tmp)
81
+ disc = Disc()
82
+ for a in audio:
83
+ disc.add_title(self.clip, audio=[a])
84
+ disc.write(out)
85
+ return out
86
+
87
+ def test_marked_as_declared(self):
88
+ self.assertEqual(stream_pids(self.clip)[AUDIO_PID], CODING_DTS) # (ffmpeg: 6 channels)
89
+ out = self.disc()
90
+ for name, want in (("00001", CODING_DTSHD_MA), ("00002", CODING_DTSHD),
91
+ ("00003", CODING_DTS)):
92
+ got = pmts(os.path.join(out, "BDMV", "STREAM", f"{name}.m2ts"))
93
+ self.assertGreater(len(got), 1)
94
+ self.assertEqual(set(got), {(want, True)}, name) # every PMT, CRC made again
95
+ self.assertEqual(set(pmts(self.clip)), {(CODING_DTS, True)}) # (the source as it was)
96
+
97
+ @unittest.skipUnless(LIBBLURAY, "needs libbluray")
98
+ def test_read_by_libbluray(self):
99
+ with bluray_sim.Disc(LIBBLURAY, self.disc()) as d:
100
+ a, b, c = d.playlist(1), d.playlist(2), d.playlist(3)
101
+ self.assertEqual(a["audio"], [(CODING_DTSHD_MA, 6, "eng")])
102
+ self.assertEqual((b["audio"], b["audio_rate"]), ([(CODING_DTSHD, 6, "eng")], [14]))
103
+ self.assertEqual((c["audio"], c["audio_rate"]), ([(CODING_DTS, 6, "eng")], [1]))
104
+
105
+ def disc(self):
106
+ """Three titles of the same clip: DTS-HD Master Audio, DTS-HD High
107
+ Resolution at 96 kHz (over its 48 kHz core) and DTS."""
108
+ return self.write(("dtshd_ma", 6, "en"), ("dtshd", 6, "en", 96000), ("dts", 6, "en"))
109
+
110
+ def test_not_dts(self):
111
+ with self.assertRaises(BdmvError) as e:
112
+ self.write(("ac3", 6, "en"))
113
+ self.assertIn("stream type 0x82", e.exception.message)
114
+
115
+ def test_retyped_a_piece_at_a_time(self):
116
+ copy = os.path.join(self.tmp, "copy.m2ts")
117
+ shutil.copyfile(self.clip, copy)
118
+ set_stream_types(copy, {AUDIO_PID: CODING_DTSHD_MA}, chunk=192 * 7)
119
+ got = pmts(copy)
120
+ self.assertEqual(set(got), {(CODING_DTSHD_MA, True)})
121
+ self.assertEqual(len(got), len(pmts(self.clip)))
122
+ with open(copy, "rb") as f, open(self.clip, "rb") as g:
123
+ a, b = f.read(), g.read()
124
+ self.assertEqual(len(a), len(b))
125
+ diff = {i // 192 for i in range(len(a)) if a[i] != b[i]}
126
+ self.assertEqual(len(diff), len(got)) # (only the PMTs)
127
+
128
+
129
+ if __name__ == "__main__":
130
+ unittest.main()
@@ -57,6 +57,15 @@ class TestStream(unittest.TestCase):
57
57
  page = ics.index(bytes(8) + bytes(4)) + 12 # after the page's UO mask, effects
58
58
  self.assertEqual(struct.unpack(">H", ics[page + 1:page + 3])[0], 1)
59
59
 
60
+ def test_720p(self):
61
+ data = igs.ig_stream([button("a", 1100, 600)], frame_rate=1, size=(1280, 720))
62
+ ics = segments(data)[0][1]
63
+ self.assertEqual(struct.unpack(">HH", ics[:4]), (1280, 720))
64
+ # placed on the 720p frame: past its edge is refused
65
+ with self.assertRaises(BdmvError) as cm:
66
+ igs.ig_stream([button("a", 1200, 600)], 1, size=(1280, 720))
67
+ self.assertIn("1280 x 720", cm.exception.args[0])
68
+
60
69
  def test_auto_nav(self):
61
70
  nav = igs.auto_nav([button("a", 100, 100), button("b", 100, 300), button("c", 600, 300),
62
71
  button("d", 100, 500, nav={"up": "c"})])
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes