codecin 7.22.10__py3-none-win_amd64.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.
Files changed (202) hide show
  1. codecin/__init__.py +27 -0
  2. codecin/aot.py +1057 -0
  3. codecin/assembler.py +619 -0
  4. codecin/cbackend.py +3024 -0
  5. codecin/cin.py +4265 -0
  6. codecin/cli.py +670 -0
  7. codecin/codecin_native.dll +0 -0
  8. codecin/config.py +50 -0
  9. codecin/console.py +183 -0
  10. codecin/cpu.py +312 -0
  11. codecin/crom.py +449 -0
  12. codecin/cvm.py +708 -0
  13. codecin/disasm.py +149 -0
  14. codecin/environment.py +176 -0
  15. codecin/errors.py +54 -0
  16. codecin/isa.py +560 -0
  17. codecin/lib/array/pic.toml +10 -0
  18. codecin/lib/array/src/array.cin +103 -0
  19. codecin/lib/bigint/pic.toml +10 -0
  20. codecin/lib/bigint/src/bigint.cin +589 -0
  21. codecin/lib/bits/pic.toml +10 -0
  22. codecin/lib/bits/src/bits.cin +143 -0
  23. codecin/lib/bitset/pic.toml +10 -0
  24. codecin/lib/bitset/src/bitset.cin +374 -0
  25. codecin/lib/codec/pic.toml +10 -0
  26. codecin/lib/codec/src/codec.cin +563 -0
  27. codecin/lib/combin/pic.toml +10 -0
  28. codecin/lib/combin/src/combin.cin +414 -0
  29. codecin/lib/conv/pic.toml +10 -0
  30. codecin/lib/conv/src/conv.cin +151 -0
  31. codecin/lib/cppstd/pic.toml +10 -0
  32. codecin/lib/cppstd/src/cppstd.cin +418 -0
  33. codecin/lib/cstd/pic.toml +10 -0
  34. codecin/lib/cstd/src/cstd.cin +424 -0
  35. codecin/lib/csv/pic.toml +10 -0
  36. codecin/lib/csv/src/csv.cin +405 -0
  37. codecin/lib/dp/pic.toml +10 -0
  38. codecin/lib/dp/src/dp.cin +325 -0
  39. codecin/lib/ffi/pic.toml +10 -0
  40. codecin/lib/ffi/src/ffi.cin +163 -0
  41. codecin/lib/fmt/pic.toml +10 -0
  42. codecin/lib/fmt/src/fmt.cin +325 -0
  43. codecin/lib/frac/pic.toml +10 -0
  44. codecin/lib/frac/src/frac.cin +252 -0
  45. codecin/lib/gostd/pic.toml +10 -0
  46. codecin/lib/gostd/src/gostd.cin +415 -0
  47. codecin/lib/graph/pic.toml +10 -0
  48. codecin/lib/graph/src/graph.cin +367 -0
  49. codecin/lib/gui/pic.toml +10 -0
  50. codecin/lib/gui/src/gui.cin +218 -0
  51. codecin/lib/hash/pic.toml +10 -0
  52. codecin/lib/hash/src/hash.cin +67 -0
  53. codecin/lib/heap/pic.toml +10 -0
  54. codecin/lib/heap/src/heap.cin +199 -0
  55. codecin/lib/io/pic.toml +10 -0
  56. codecin/lib/io/src/io.cin +141 -0
  57. codecin/lib/json/pic.toml +10 -0
  58. codecin/lib/json/src/json.cin +84 -0
  59. codecin/lib/key/pic.toml +10 -0
  60. codecin/lib/key/src/key.cin +78 -0
  61. codecin/lib/math/pic.toml +10 -0
  62. codecin/lib/math/src/math.cin +50 -0
  63. codecin/lib/matrix/pic.toml +10 -0
  64. codecin/lib/matrix/src/matrix.cin +155 -0
  65. codecin/lib/net/pic.toml +10 -0
  66. codecin/lib/net/src/net.cin +171 -0
  67. codecin/lib/path/pic.toml +10 -0
  68. codecin/lib/path/src/path.cin +372 -0
  69. codecin/lib/queue/pic.toml +10 -0
  70. codecin/lib/queue/src/queue.cin +112 -0
  71. codecin/lib/rand/pic.toml +10 -0
  72. codecin/lib/rand/src/rand.cin +46 -0
  73. codecin/lib/set/pic.toml +10 -0
  74. codecin/lib/set/src/set.cin +269 -0
  75. codecin/lib/sort/pic.toml +10 -0
  76. codecin/lib/sort/src/sort.cin +93 -0
  77. codecin/lib/stat/pic.toml +10 -0
  78. codecin/lib/stat/src/stat.cin +138 -0
  79. codecin/lib/str/pic.toml +10 -0
  80. codecin/lib/str/src/str.cin +54 -0
  81. codecin/lib/termux/pic.toml +10 -0
  82. codecin/lib/termux/src/termux.cin +118 -0
  83. codecin/lib/test/pic.toml +10 -0
  84. codecin/lib/test/src/test.cin +74 -0
  85. codecin/lib/text/pic.toml +10 -0
  86. codecin/lib/text/src/text.cin +323 -0
  87. codecin/lib/time/pic.toml +10 -0
  88. codecin/lib/time/src/time.cin +54 -0
  89. codecin/lib/token/pic.toml +10 -0
  90. codecin/lib/token/src/token.cin +183 -0
  91. codecin/lib/tree/pic.toml +10 -0
  92. codecin/lib/tree/src/tree.cin +256 -0
  93. codecin/lib/unionfind/pic.toml +10 -0
  94. codecin/lib/unionfind/src/unionfind.cin +115 -0
  95. codecin/lib/validate/pic.toml +10 -0
  96. codecin/lib/validate/src/validate.cin +148 -0
  97. codecin/lib/vec/pic.toml +10 -0
  98. codecin/lib/vec/src/vec.cin +88 -0
  99. codecin/logger.py +145 -0
  100. codecin/memory.py +306 -0
  101. codecin/mkn.py +916 -0
  102. codecin/native/aot/aot.go +114 -0
  103. codecin/native/aot/stub_main.go.txt +23 -0
  104. codecin/native/build.ps1 +33 -0
  105. codecin/native/build.sh +48 -0
  106. codecin/native/cmd/cincc/main.go +66 -0
  107. codecin/native/compiler/codegen.go +2238 -0
  108. codecin/native/compiler/compile_test.go +1069 -0
  109. codecin/native/compiler/parser.go +1331 -0
  110. codecin/native/compiler/syscalls.go +166 -0
  111. codecin/native/compiler/tokenizer.go +394 -0
  112. codecin/native/compiler/types.go +217 -0
  113. codecin/native/engine/args.go +37 -0
  114. codecin/native/engine/audio.go +402 -0
  115. codecin/native/engine/audio_other.go +105 -0
  116. codecin/native/engine/audio_test.go +279 -0
  117. codecin/native/engine/audio_windows.go +190 -0
  118. codecin/native/engine/canvas.go +271 -0
  119. codecin/native/engine/console_other.go +9 -0
  120. codecin/native/engine/console_windows.go +43 -0
  121. codecin/native/engine/crom.go +86 -0
  122. codecin/native/engine/encode.go +93 -0
  123. codecin/native/engine/engine_test.go +198 -0
  124. codecin/native/engine/ffi_nocgo.go +20 -0
  125. codecin/native/engine/ffi_registry.go +69 -0
  126. codecin/native/engine/ffi_unix.go +109 -0
  127. codecin/native/engine/ffi_windows.go +117 -0
  128. codecin/native/engine/gui.go +209 -0
  129. codecin/native/engine/gui_stub.go +13 -0
  130. codecin/native/engine/gui_test.go +148 -0
  131. codecin/native/engine/gui_windows.go +604 -0
  132. codecin/native/engine/gui_x11.go +723 -0
  133. codecin/native/engine/host_test.go +139 -0
  134. codecin/native/engine/hostcrypto.go +30 -0
  135. codecin/native/engine/hostdesktop.go +173 -0
  136. codecin/native/engine/hostnet.go +127 -0
  137. codecin/native/engine/isa_gen.go +689 -0
  138. codecin/native/engine/keyboard.go +432 -0
  139. codecin/native/engine/keyboard_other.go +94 -0
  140. codecin/native/engine/keyboard_stub.go +17 -0
  141. codecin/native/engine/keyboard_termios_darwin.go +9 -0
  142. codecin/native/engine/keyboard_termios_linux.go +9 -0
  143. codecin/native/engine/keyboard_test.go +246 -0
  144. codecin/native/engine/keyboard_windows.go +208 -0
  145. codecin/native/engine/keyboard_windows_test.go +123 -0
  146. codecin/native/engine/lineedit.go +262 -0
  147. codecin/native/engine/lineedit_test.go +105 -0
  148. codecin/native/engine/lineint_unix.go +17 -0
  149. codecin/native/engine/lineint_windows.go +19 -0
  150. codecin/native/engine/mem_other.go +37 -0
  151. codecin/native/engine/mem_windows.go +33 -0
  152. codecin/native/engine/native.go +640 -0
  153. codecin/native/engine/netsock.go +321 -0
  154. codecin/native/engine/ops_ext.go +515 -0
  155. codecin/native/engine/stdin.go +72 -0
  156. codecin/native/engine/stdin_other.go +9 -0
  157. codecin/native/engine/stdin_windows.go +60 -0
  158. codecin/native/engine/system.go +313 -0
  159. codecin/native/engine/termux.go +180 -0
  160. codecin/native/engine/version_gen.go +7 -0
  161. codecin/native/engine/vkb_darwin.go +62 -0
  162. codecin/native/engine/vkb_linux.go +95 -0
  163. codecin/native/engine/vkb_stub.go +11 -0
  164. codecin/native/engine/vm.go +1677 -0
  165. codecin/native/go.mod +3 -0
  166. codecin/native/ir/ir.go +48 -0
  167. codecin/native/main.go +448 -0
  168. codecin/native/mc/aarch64.go +165 -0
  169. codecin/native/mc/aarch64_test.go +30 -0
  170. codecin/native/mc/elf.go +88 -0
  171. codecin/native/mc/print_test.go +52 -0
  172. codecin/native/mc/x86_64.go +1262 -0
  173. codecin/native/mc/x86_64_test.go +102 -0
  174. codecin/native.py +432 -0
  175. codecin/native_codegen.py +987 -0
  176. codecin/nativegen.py +786 -0
  177. codecin/object.py +539 -0
  178. codecin/optimizer.py +236 -0
  179. codecin/packaging/__init__.py +46 -0
  180. codecin/packaging/archive.py +177 -0
  181. codecin/packaging/model.py +519 -0
  182. codecin/packaging/spec.py +193 -0
  183. codecin/packaging/store.py +372 -0
  184. codecin/packaging/toml.py +541 -0
  185. codecin/packaging/vcs.py +215 -0
  186. codecin/pic.py +1917 -0
  187. codecin/pic_api.py +374 -0
  188. codecin/pic_login.py +519 -0
  189. codecin/pic_registry.py +515 -0
  190. codecin/registers.py +130 -0
  191. codecin/sdgcc.py +493 -0
  192. codecin/stats.py +230 -0
  193. codecin/stdlib.py +138 -0
  194. codecin/toolchain.py +396 -0
  195. codecin/toolkit.py +26 -0
  196. codecin/version.py +260 -0
  197. codecin-7.22.10.dist-info/METADATA +1077 -0
  198. codecin-7.22.10.dist-info/RECORD +202 -0
  199. codecin-7.22.10.dist-info/WHEEL +5 -0
  200. codecin-7.22.10.dist-info/entry_points.txt +5 -0
  201. codecin-7.22.10.dist-info/licenses/LICENSE +7 -0
  202. codecin-7.22.10.dist-info/top_level.txt +1 -0
@@ -0,0 +1,217 @@
1
+ // Package compiler 是 Code CIN 语言的 Go 版编译器 (Python codecin/cin.py 的忠实移植)。
2
+ // 它将 CIN 源码编译为 ir.Program, 与 Python CINCompiler 的产物逐字节一致。
3
+ package compiler
4
+
5
+ import "codecin-native/ir"
6
+
7
+ // ---------------- 类型系统 ----------------
8
+
9
+ // TypeKind 类型类别。
10
+ type TypeKind uint8
11
+
12
+ const (
13
+ kInt TypeKind = iota
14
+ kFloat
15
+ kBool
16
+ kString
17
+ kVoid
18
+ kStruct
19
+ kArray
20
+ kPtrArray
21
+ )
22
+
23
+ // Type 表示一个 CIN 类型。等价于 Python 侧的元组表示:
24
+ //
25
+ // int/float/bool/string/void -> Kind 对应标量
26
+ // ('struct', Name) -> kStruct
27
+ // ('array', elem, size) -> kArray
28
+ // ('ptrarray', elem) -> kPtrArray
29
+ type Type struct {
30
+ Kind TypeKind
31
+ Elem *Type
32
+ Size int
33
+ Name string
34
+ }
35
+
36
+ func scalarT(k TypeKind) *Type { return &Type{Kind: k} }
37
+
38
+ func isFixedArray(t *Type) bool { return t != nil && t.Kind == kArray }
39
+ func isPtrArray(t *Type) bool { return t != nil && t.Kind == kPtrArray }
40
+ func isStruct(t *Type) bool { return t != nil && t.Kind == kStruct }
41
+ func isScalar(t *Type) bool {
42
+ return t != nil && (t.Kind == kInt || t.Kind == kFloat || t.Kind == kBool ||
43
+ t.Kind == kString || t.Kind == kVoid)
44
+ }
45
+
46
+ func typeSlots(t *Type) int {
47
+ if isFixedArray(t) {
48
+ return t.Size * typeSlots(t.Elem)
49
+ }
50
+ return 1
51
+ }
52
+
53
+ func typeName(t *Type) string {
54
+ if t == nil {
55
+ return "nil"
56
+ }
57
+ switch t.Kind {
58
+ case kInt:
59
+ return "int"
60
+ case kFloat:
61
+ return "float"
62
+ case kBool:
63
+ return "bool"
64
+ case kString:
65
+ return "string"
66
+ case kVoid:
67
+ return "void"
68
+ case kStruct:
69
+ return t.Name
70
+ case kArray:
71
+ return typeName(t.Elem) + "[]"
72
+ case kPtrArray:
73
+ return typeName(t.Elem) + "[]"
74
+ }
75
+ return "?"
76
+ }
77
+
78
+ // ---------------- AST ----------------
79
+
80
+ // Node 是 AST 节点 (等价于 Python 侧的位置元组)。
81
+ type Node struct {
82
+ Kind string // num/bool/str/var/call/binop/not/bitnot/neg/preinc/predec/postinc/postdec/cond/member/index
83
+ // block/return/if/while/for/rangefor/dowhile/switch/break/continue/decl/cpu/assert/expr
84
+ // declitem/case/caseval/caserange/arraylit
85
+ Num float64
86
+ Ival int64
87
+ IsFloat bool
88
+ Bool bool
89
+ Str string
90
+ Name string
91
+ Op string
92
+ A, B, C, D *Node
93
+ List []*Node
94
+ Int int
95
+ Type *Type
96
+ Filename string
97
+ // 数组字面量: Is2D=false 时 ArrayLit[0] 为元素; Is2D=true 时 ArrayLit 为行。
98
+ ArrayLit [][]*Node
99
+ Is2D bool
100
+ // cpu 语句操作数 (kind, value) 对。
101
+ Operands [][2]string
102
+
103
+ // Alts 仅用于 Kind=="case": case 备选列表, 每项为 caseval (A=常量表达式)
104
+ // 或 caserange (A=low, B=high); Alts==nil 表示 default 分支。case 的语句体
105
+ // 仍放在 List 中。RangeID 仅用于 Kind=="rangefor": 隐藏局部名
106
+ // $rf<id>p / $rf<id>e 的 id (自增序号, 与 Python 侧 _range_id 一致 ->
107
+ // 保证两编译器的栈槽布局相同)。
108
+ Alts []*Node // case 备选; nil = default
109
+ RangeID int // rangefor 的隐藏局部名序号
110
+ }
111
+
112
+ // DeclItem 一条变量声明 (name, type, init, arrayLit)。
113
+ type DeclItem struct {
114
+ Name string
115
+ Type *Type
116
+ Init *Node
117
+ ArrayLit *Node
118
+ }
119
+
120
+ // ---------------- 编译上下文 ----------------
121
+
122
+ // compiler 持有整个编译过程的可变状态。
123
+ type compiler struct {
124
+ // 词法/语法产物
125
+ structs map[string]*StructDef
126
+ functions map[string]*FuncDef
127
+ globals []*GlobalVar
128
+ enums map[string]int64 // 枚举成员 -> 编译期整数常量 (来自 parser)
129
+
130
+ // 代码生成状态
131
+ res *ir.Program
132
+ dataPtr int
133
+ heapStr map[string]int
134
+ filename string
135
+ bounds bool
136
+
137
+ // err 是粘性的首个编译错误 (语义错误不再被静默吞掉, 由 Compile 统一返回)。
138
+ // 见 docs/SUGGESTIONS.md §3.1.4: 旧实现在语义错误分支只 return/continue,
139
+ // 会漏发射指令并带着上一次的 x0 继续生成, 产出静默错误的字节码。
140
+ err error
141
+
142
+ // 函数生成上下文
143
+ funcDef *FuncDef
144
+ locals map[string]localVar
145
+ frameBytes int
146
+ breakLbls []string
147
+ continueLbls []string
148
+ labelCounter int
149
+ globalsSym map[string]globalVar
150
+ }
151
+
152
+ type localVar struct {
153
+ t *Type
154
+ off int
155
+ isBlock bool
156
+ }
157
+
158
+ type globalVar struct {
159
+ t *Type
160
+ addr int
161
+ isBlock bool
162
+ }
163
+
164
+ // StructDef struct 定义。
165
+ type StructDef struct {
166
+ name string
167
+ fields []fieldDef
168
+ offsets map[string]int
169
+ sizeSlots int
170
+ }
171
+
172
+ type fieldDef struct {
173
+ name string
174
+ t *Type
175
+ }
176
+
177
+ // FuncDef 函数定义。
178
+ type FuncDef struct {
179
+ name string
180
+ params []paramDef
181
+ retType *Type
182
+ body []*Node
183
+ line int
184
+ }
185
+
186
+ type paramDef struct {
187
+ name string
188
+ t *Type
189
+ }
190
+
191
+ // GlobalVar 全局变量。
192
+ type GlobalVar struct {
193
+ name string
194
+ t *Type
195
+ addr int
196
+ init *Node
197
+ arrayLit *Node
198
+ }
199
+
200
+ // newCompiler 构建编译器。
201
+ func newCompiler(filename string, bounds bool) *compiler {
202
+ return &compiler{
203
+ structs: map[string]*StructDef{},
204
+ functions: map[string]*FuncDef{},
205
+ globals: []*GlobalVar{},
206
+ res: &ir.Program{
207
+ Labels: map[string]int{},
208
+ DataLabels: map[string]int{},
209
+ },
210
+ enums: map[string]int64{},
211
+ heapStr: map[string]int{},
212
+ filename: filename,
213
+ bounds: bounds,
214
+ locals: map[string]localVar{},
215
+ globalsSym: map[string]globalVar{},
216
+ }
217
+ }
@@ -0,0 +1,37 @@
1
+ package engine
2
+
3
+ import "sync"
4
+
5
+ var (
6
+ argsMu sync.RWMutex
7
+ programArgs []string
8
+ )
9
+
10
+ // SetProgramArgs 设置 CIN 程序可见的命令行参数 (arg_count / arg 的数据源)。
11
+ // 传入 nil / 空切片表示无参数; 内部复制, 调用方随后修改无副作用。
12
+ func SetProgramArgs(args []string) {
13
+ argsMu.Lock()
14
+ defer argsMu.Unlock()
15
+ programArgs = append([]string(nil), args...)
16
+ }
17
+
18
+ // currentProgramArgs 返回参数快照 (复制; VM 创建时取一次, 执行期间稳定)。
19
+ func currentProgramArgs() []string {
20
+ argsMu.RLock()
21
+ defer argsMu.RUnlock()
22
+ return append([]string(nil), programArgs...)
23
+ }
24
+
25
+ // argCount SYS 129: arg_count() -> 参数个数。
26
+ func (vm *vmState) argCount() uint64 {
27
+ return uint64(len(vm.args)) & mask64
28
+ }
29
+
30
+ // argAt SYS 130: arg(x0=i) -> 第 i 个参数 (堆字符串; 越界/负数为空串)。
31
+ func (vm *vmState) argAt(i uint64) uint64 {
32
+ idx := toSigned(i)
33
+ if idx < 0 || idx >= int64(len(vm.args)) {
34
+ return vm.empty()
35
+ }
36
+ return vm.hs(vm.args[idx])
37
+ }
@@ -0,0 +1,402 @@
1
+ package engine
2
+
3
+ import (
4
+ "encoding/binary"
5
+ "fmt"
6
+ "io"
7
+ "math"
8
+ "net/http"
9
+ "os"
10
+ "os/exec"
11
+ "strings"
12
+ "sync"
13
+ "time"
14
+ )
15
+
16
+ // 宿主全局音频状态 (同一时刻一个音频流)。
17
+ var (
18
+ audioMu sync.Mutex
19
+ audioActive bool
20
+ audioDur time.Duration
21
+ audioStarted time.Time
22
+ audioEnd time.Time
23
+ audioLevel int = 100 // 0..100 (audio_volume; Windows 实时生效, Unix 传入播放器)
24
+ audioDone chan struct{}
25
+ audioTemp string // 当前播放的临时 WAV 文件路径 (Unix 异步播放时保留)
26
+ audioCmd *exec.Cmd
27
+ audioCmdMu sync.Mutex
28
+ audioData []byte // 播放中的 WAV 字节 (waveOut 直接引用, 保活防 GC)
29
+ audioPaused bool // audio_pause 之后为 true (audio_pos 冻结在暂停时刻)
30
+ audioPausedAt time.Time
31
+ )
32
+
33
+ // MaxResourceBytes 是 FetchResource 的下载/读取上限 (音频等宿主资源)。
34
+ const MaxResourceBytes = 64 << 20 // 64 MiB
35
+
36
+ // audioTestOff 测试钩子: 置 true 时 playPlatform 一律视为失败,
37
+ // 测试不触碰真实音频设备 (与 guiForcedOff 同模式)。
38
+ var audioTestOff bool
39
+
40
+ // FetchResource 下载 URL 或读取本地文件, 返回原始字节。
41
+ func FetchResource(loc string) ([]byte, error) {
42
+ if strings.HasPrefix(loc, "http://") || strings.HasPrefix(loc, "https://") {
43
+ client := &http.Client{Timeout: 30 * time.Second}
44
+ resp, err := client.Get(loc)
45
+ if err != nil {
46
+ return nil, err
47
+ }
48
+ defer resp.Body.Close()
49
+ if resp.StatusCode != http.StatusOK {
50
+ return nil, fmt.Errorf("http status %d", resp.StatusCode)
51
+ }
52
+ // 有上限读取: Content-Length 与实际读取量双重限制,
53
+ // 防止恶意/异常 URL 用无限流把宿主 OOM。
54
+ if resp.ContentLength > MaxResourceBytes {
55
+ return nil, fmt.Errorf("resource too large: %d bytes", resp.ContentLength)
56
+ }
57
+ data, err := io.ReadAll(io.LimitReader(resp.Body, MaxResourceBytes+1))
58
+ if err != nil {
59
+ return nil, err
60
+ }
61
+ if len(data) > MaxResourceBytes {
62
+ return nil, fmt.Errorf("resource too large: >%d bytes", MaxResourceBytes)
63
+ }
64
+ return data, nil
65
+ }
66
+ fi, err := os.Stat(loc)
67
+ if err == nil && fi.Size() > MaxResourceBytes {
68
+ return nil, fmt.Errorf("resource too large: %d bytes", fi.Size())
69
+ }
70
+ return os.ReadFile(loc)
71
+ }
72
+
73
+ // wavInfo 是 WAV 解析结果 (fmt 与 data chunk)。
74
+ type wavInfo struct {
75
+ channels uint16
76
+ sampleRate uint32
77
+ bits uint16
78
+ dataOffset int
79
+ dataLength int
80
+ }
81
+
82
+ // wavParse 遍历 RIFF chunk 提取 fmt 与 data (容忍 fact/LIST 等额外块与截断)。
83
+ func wavParse(data []byte) (wavInfo, bool) {
84
+ var wi wavInfo
85
+ if len(data) < 12 || string(data[0:4]) != "RIFF" || string(data[8:12]) != "WAVE" {
86
+ return wi, false
87
+ }
88
+ pos := 12
89
+ gotFmt := false
90
+ for pos+8 <= len(data) {
91
+ id := string(data[pos : pos+4])
92
+ size := int(binary.LittleEndian.Uint32(data[pos+4 : pos+8]))
93
+ body := pos + 8
94
+ if body+size > len(data) {
95
+ size = len(data) - body // 截断容错
96
+ }
97
+ switch id {
98
+ case "fmt ":
99
+ if size < 16 {
100
+ return wi, false
101
+ }
102
+ wi.channels = binary.LittleEndian.Uint16(data[body+2 : body+4])
103
+ wi.sampleRate = binary.LittleEndian.Uint32(data[body+4 : body+8])
104
+ wi.bits = binary.LittleEndian.Uint16(data[body+14 : body+16])
105
+ gotFmt = true
106
+ case "data":
107
+ wi.dataOffset = body
108
+ wi.dataLength = size
109
+ }
110
+ pos = body + size
111
+ if size%2 == 1 {
112
+ pos++ // chunk 按字对齐
113
+ }
114
+ }
115
+ if !gotFmt || wi.dataLength <= 0 || wi.channels == 0 ||
116
+ wi.sampleRate == 0 || wi.bits == 0 || wi.bits%8 != 0 {
117
+ return wi, false
118
+ }
119
+ return wi, true
120
+ }
121
+
122
+ // isWav 判断是否为 WAV (RIFF/WAVE)。
123
+ func isWav(data []byte) bool {
124
+ _, ok := wavParse(data)
125
+ return ok
126
+ }
127
+
128
+ // WavDuration 解析 WAV 头并返回时长 (0 表示无法识别)。
129
+ func WavDuration(data []byte) time.Duration {
130
+ wi, ok := wavParse(data)
131
+ if !ok {
132
+ return 0
133
+ }
134
+ blockAlign := uint64(wi.channels) * uint64(wi.bits) / 8
135
+ if blockAlign == 0 {
136
+ return 0
137
+ }
138
+ return time.Duration(uint64(wi.dataLength) / blockAlign *
139
+ uint64(time.Second) / uint64(wi.sampleRate))
140
+ }
141
+
142
+ // writeTempWav 将 WAV 字节写入临时文件并记录路径 (Unix 外部播放器用)。
143
+ func writeTempWav(data []byte) (string, error) {
144
+ f, err := os.CreateTemp("", "codecin_*.wav")
145
+ if err != nil {
146
+ return "", err
147
+ }
148
+ if _, err := f.Write(data); err != nil {
149
+ _ = f.Close()
150
+ _ = os.Remove(f.Name())
151
+ return "", err
152
+ }
153
+ if err := f.Close(); err != nil {
154
+ _ = os.Remove(f.Name())
155
+ return "", err
156
+ }
157
+ audioTemp = f.Name()
158
+ return audioTemp, nil
159
+ }
160
+
161
+ // cleanupTempWav 删除临时 WAV 文件。
162
+ func cleanupTempWav() {
163
+ if audioTemp != "" {
164
+ _ = os.Remove(audioTemp)
165
+ audioTemp = ""
166
+ }
167
+ }
168
+
169
+ func (vm *vmState) audioPlay(loc string) uint64 {
170
+ data, err := FetchResource(loc)
171
+ if err != nil {
172
+ return mask64 // -1
173
+ }
174
+ if !isWav(data) {
175
+ return mask64 // 不支持的格式
176
+ }
177
+ return vm.audioPlayBytes(data)
178
+ }
179
+
180
+ func (vm *vmState) audioPlayBytes(data []byte) uint64 {
181
+ vm.audioStop() // 停掉上一段 (若在播)
182
+ if audioTestOff {
183
+ return mask64
184
+ }
185
+ if err := playPlatform(data); err != nil {
186
+ return mask64
187
+ }
188
+ audioData = data
189
+ audioActive = true
190
+ audioDur = WavDuration(data)
191
+ audioStarted = time.Now()
192
+ audioEnd = audioStarted.Add(audioDur)
193
+ audioPaused = false
194
+ audioPausedAt = time.Time{}
195
+ audioDone = make(chan struct{})
196
+ if audioDur <= 0 {
197
+ close(audioDone) // 无法确定时长: 立即视为结束
198
+ return 0
199
+ }
200
+ go func(done chan struct{}) {
201
+ waitPlatform()
202
+ close(done)
203
+ }(audioDone)
204
+ return 0
205
+ }
206
+
207
+ func (vm *vmState) audioStop() {
208
+ audioMu.Lock()
209
+ done := audioDone
210
+ audioActive = false
211
+ audioPaused = false
212
+ audioPausedAt = time.Time{}
213
+ audioMu.Unlock()
214
+ stopPlatform()
215
+ if done != nil {
216
+ <-done // 等 wait goroutine 退出, 避免与下一次播放竞争
217
+ }
218
+ }
219
+
220
+ func (vm *vmState) audioVolume(level uint64) {
221
+ if level > 100 {
222
+ level = 100
223
+ }
224
+ audioMu.Lock()
225
+ audioLevel = int(level)
226
+ audioMu.Unlock()
227
+ setVolumePlatform(int(level))
228
+ }
229
+
230
+ func audioLevelNow() int {
231
+ audioMu.Lock()
232
+ defer audioMu.Unlock()
233
+ return audioLevel
234
+ }
235
+
236
+ // audioPos SYS 126: audio_pos() -> 当前播放已进行毫秒 / -1 (无播放或已播完)。
237
+ // 暂停期间冻结在暂停时刻 (audio_pause 前的进度), 不随真实时间前进。
238
+ func (vm *vmState) audioPos() uint64 {
239
+ audioMu.Lock()
240
+ defer audioMu.Unlock()
241
+ if !audioActive || audioDur <= 0 {
242
+ return mask64
243
+ }
244
+ if audioPaused {
245
+ el := audioPausedAt.Sub(audioStarted)
246
+ if el < 0 {
247
+ el = 0
248
+ }
249
+ if el > audioDur {
250
+ el = audioDur
251
+ }
252
+ return uint64(el.Milliseconds())
253
+ }
254
+ now := time.Now()
255
+ if !audioEnd.IsZero() && now.After(audioEnd) {
256
+ return mask64 // 已自然播完 (audio_wait 之前也视为无进度)
257
+ }
258
+ el := now.Sub(audioStarted)
259
+ if el > audioDur {
260
+ el = audioDur
261
+ }
262
+ return uint64(el.Milliseconds())
263
+ }
264
+
265
+ // audioDuration SYS 132: audio_duration() -> 当前播放总时长毫秒 / -1。
266
+ // 播放与暂停期间都返回总时长; 自然播完 / 未播放 / 时长未知 (WAV 头缺失) 为 -1。
267
+ func (vm *vmState) audioDuration() uint64 {
268
+ audioMu.Lock()
269
+ defer audioMu.Unlock()
270
+ if !audioActive || audioDur <= 0 {
271
+ return mask64
272
+ }
273
+ if !audioPaused && !audioEnd.IsZero() && time.Now().After(audioEnd) {
274
+ return mask64 // 已自然播完
275
+ }
276
+ return uint64(audioDur.Milliseconds())
277
+ }
278
+
279
+ // audioPlayingNow SYS 133 的判定: 1 表示正在发声 (已开始、未暂停、未播完)。
280
+ func audioPlayingNow() bool {
281
+ audioMu.Lock()
282
+ defer audioMu.Unlock()
283
+ if !audioActive || audioPaused {
284
+ return false
285
+ }
286
+ if audioDur > 0 && !audioEnd.IsZero() && time.Now().After(audioEnd) {
287
+ return false // 已自然播完
288
+ }
289
+ return true
290
+ }
291
+
292
+ // audioPause SYS 134: audio_pause() -> 0 成功 / -1 (无播放、已暂停或平台失败)。
293
+ // Windows 用 waveOutPause; Unix 向播放器进程投递 SIGSTOP。
294
+ func (vm *vmState) audioPause() uint64 {
295
+ audioMu.Lock()
296
+ ok := audioActive && !audioPaused
297
+ audioMu.Unlock()
298
+ if !ok || !pausePlatform() {
299
+ return mask64
300
+ }
301
+ audioMu.Lock()
302
+ defer audioMu.Unlock()
303
+ // 复核: 平台调用期间可能已被 stop / 自然结束 / 播放完毕
304
+ if !audioActive || audioPaused {
305
+ return mask64
306
+ }
307
+ audioPaused = true
308
+ audioPausedAt = time.Now()
309
+ return 0
310
+ }
311
+
312
+ // audioResume SYS 135: audio_resume() -> 0 成功 / -1 (无暂停可恢复或平台失败)。
313
+ // 恢复时把播放时间基线整体后移暂停时长, audio_pos / 自然结束时刻保持连续。
314
+ func (vm *vmState) audioResume() uint64 {
315
+ audioMu.Lock()
316
+ ok := audioActive && audioPaused
317
+ pausedAt := audioPausedAt
318
+ audioMu.Unlock()
319
+ if !ok || !resumePlatform() {
320
+ return mask64
321
+ }
322
+ audioMu.Lock()
323
+ defer audioMu.Unlock()
324
+ if !audioActive || !audioPaused {
325
+ return mask64
326
+ }
327
+ delta := time.Since(pausedAt)
328
+ if delta < 0 {
329
+ delta = 0
330
+ }
331
+ audioStarted = audioStarted.Add(delta)
332
+ if !audioEnd.IsZero() {
333
+ audioEnd = audioEnd.Add(delta)
334
+ }
335
+ audioPaused = false
336
+ audioPausedAt = time.Time{}
337
+ return 0
338
+ }
339
+
340
+ func (vm *vmState) audioBeep(freq, ms uint64) uint64 {
341
+ if freq < 20 || freq > 20000 || ms == 0 {
342
+ return mask64
343
+ }
344
+ if ms > 10000 {
345
+ ms = 10000
346
+ }
347
+ return vm.audioPlayBytes(synthBeepWav(freq, ms))
348
+ }
349
+
350
+ func (vm *vmState) audioWait() {
351
+ audioMu.Lock()
352
+ done := audioDone
353
+ audioMu.Unlock()
354
+ if done == nil {
355
+ return
356
+ }
357
+ <-done
358
+ audioMu.Lock()
359
+ audioActive = false
360
+ audioMu.Unlock()
361
+ }
362
+
363
+ // synthBeepWav 合成 16-bit 单声道 22050Hz 正弦波 WAV (带 5ms 淡入淡出防爆音)。
364
+ func synthBeepWav(freq, ms uint64) []byte {
365
+ const rate = 22050
366
+ n := int(rate * ms / 1000)
367
+ if n < 1 {
368
+ n = 1
369
+ }
370
+ fade := n / 10
371
+ if fade > rate/200 { // 最多 5ms
372
+ fade = rate / 200
373
+ }
374
+ data := make([]byte, 44+n*2)
375
+ copy(data[0:4], "RIFF")
376
+ binary.LittleEndian.PutUint32(data[4:8], uint32(36+n*2))
377
+ copy(data[8:12], "WAVE")
378
+ copy(data[12:16], "fmt ")
379
+ binary.LittleEndian.PutUint32(data[16:20], 16)
380
+ binary.LittleEndian.PutUint16(data[20:22], 1) // PCM
381
+ binary.LittleEndian.PutUint16(data[22:24], 1) // mono
382
+ binary.LittleEndian.PutUint32(data[24:28], rate) // 采样率
383
+ binary.LittleEndian.PutUint32(data[28:32], rate*2) // byte rate
384
+ binary.LittleEndian.PutUint16(data[32:34], 2) // block align
385
+ binary.LittleEndian.PutUint16(data[34:36], 16) // bits
386
+ copy(data[36:40], "data")
387
+ binary.LittleEndian.PutUint32(data[40:44], uint32(n*2))
388
+ w := 2 * math.Pi * float64(freq) / float64(rate)
389
+ for i := 0; i < n; i++ {
390
+ amp := 1.0
391
+ if fade > 0 {
392
+ if i < fade {
393
+ amp = float64(i) / float64(fade)
394
+ } else if i >= n-fade {
395
+ amp = float64(n-1-i) / float64(fade)
396
+ }
397
+ }
398
+ v := int16(28000 * amp * math.Sin(w*float64(i)))
399
+ binary.LittleEndian.PutUint16(data[44+i*2:], uint16(v))
400
+ }
401
+ return data
402
+ }