Upload 4178 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +17 -34
- LICENSE +202 -0
- NOTICE +5 -0
- README.md +204 -0
- mimamo-0.8.4.apk +3 -0
- screenshots/01_home.png +3 -0
- screenshots/02_menu.png +3 -0
- screenshots/03_calendar.png +3 -0
- screenshots/04_day.png +3 -0
- screenshots/05_plan.png +3 -0
- screenshots/06_block.png +3 -0
- screenshots/07_report.png +3 -0
- screenshots/08_settings.png +3 -0
- source/LICENSE +202 -0
- source/app/build.gradle.kts +68 -0
- source/app/libs/moonshine-voice-0.1.6.jar +3 -0
- source/app/libs/onnxruntime-classes.jar +3 -0
- source/app/src/main/AndroidManifest.xml +101 -0
- source/app/src/main/assets/avatar/avatar.html +301 -0
- source/app/src/main/assets/avatar/jsm/loaders/GLTFLoader.js +0 -0
- source/app/src/main/assets/avatar/jsm/utils/BufferGeometryUtils.js +1432 -0
- source/app/src/main/assets/avatar/lib/three-vrm.module.min.js +0 -0
- source/app/src/main/assets/avatar/lib/three.core.min.js +0 -0
- source/app/src/main/assets/avatar/lib/three.module.min.js +0 -0
- source/app/src/main/assets/avatar/model.vrm +3 -0
- source/app/src/main/assets/models/hann400.f32 +3 -0
- source/app/src/main/assets/models/smart_turn.onnx +3 -0
- source/app/src/main/assets/models/vap_ar.onnx +3 -0
- source/app/src/main/assets/models/vap_enc.onnx +3 -0
- source/app/src/main/assets/models/whisper_mel_80x201.f32 +3 -0
- source/app/src/main/assets/partlock/clip_text_q8.onnx +3 -0
- source/app/src/main/assets/partlock/clip_tok/merges.txt +0 -0
- source/app/src/main/assets/partlock/clip_tok/vocab.json +0 -0
- source/app/src/main/assets/partlock/dec2.onnx +3 -0
- source/app/src/main/assets/partlock/gen_step2_int8.onnx +3 -0
- source/app/src/main/assets/partlock/meta.json +1 -0
- source/app/src/main/assets/partlock/null.f32 +3 -0
- source/app/src/main/cpp/CMakeLists.txt +39 -0
- source/app/src/main/cpp/duplex/audio_io.h +24 -0
- source/app/src/main/cpp/duplex/audio_oboe.cpp +70 -0
- source/app/src/main/cpp/duplex/common.h +248 -0
- source/app/src/main/cpp/duplex/engine.cpp +90 -0
- source/app/src/main/cpp/duplex/engine_core.h +711 -0
- source/app/src/main/cpp/duplex/llm.h +18 -0
- source/app/src/main/cpp/duplex/models.cpp +186 -0
- source/app/src/main/cpp/duplex/models.h +68 -0
- source/app/src/main/cpp/duplex/moonshine-c-api.h +1433 -0
- source/app/src/main/cpp/duplex/moonshine_asr.cpp +99 -0
- source/app/src/main/cpp/duplex/moonshine_asr.h +31 -0
- source/app/src/main/cpp/duplex/tts.cpp +200 -0
.gitattributes
CHANGED
|
@@ -1,35 +1,18 @@
|
|
| 1 |
-
*.
|
| 2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
-
*.
|
| 18 |
-
*.
|
| 19 |
-
*.
|
| 20 |
-
*.
|
| 21 |
-
*.
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 1 |
+
*.apk filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.vrm filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.so filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.jar filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.f32 filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
source/third_party/llama.cpp-1.0.0/gguf-py/gguf/__pycache__/constants.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
source/third_party/llama.cpp-1.0.0/gguf-py/gguf/__pycache__/gguf_writer.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
source/third_party/llama.cpp-1.0.0/gguf-py/gguf/__pycache__/quants.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
source/third_party/llama.cpp-1.0.0/gguf-py/gguf/__pycache__/tensor_mapping.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
source/third_party/llama.cpp-1.0.0/tools/mtmd/test-1.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
source/third_party/llama.cpp-1.0.0/tools/mtmd/test-2.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
source/third_party/llama.cpp-1.0.0/tools/mtmd/test-3.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
source/third_party/llama.cpp-1.0.0/tools/ui/static/recommended-mcp/huggingface.ico filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
source/third_party/llama.cpp-1.0.0/tools/ui/tests/stories/fixtures/assets/beautiful-flowers-lotus.webp filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
source/third_party/llama.cpp-1.0.0/tools/ui/tests/stories/fixtures/assets/example.pdf filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
source/third_party/Vulkan-Headers/registry/validusage.json filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
NOTICE
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ミマモ(Mimamo)
|
| 2 |
+
Copyright 2026 焼きマスク(yakimask)
|
| 3 |
+
|
| 4 |
+
この作品は Apache License 2.0 で配布しています(LICENSE を参照)。
|
| 5 |
+
中に入れている部品・モデルは、それぞれ元のライセンスに従います(source/licenses/README.md を参照)。
|
README.md
CHANGED
|
@@ -1,3 +1,207 @@
|
|
| 1 |
---
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
language:
|
| 3 |
+
- ja
|
| 4 |
license: apache-2.0
|
| 5 |
+
tags:
|
| 6 |
+
- android
|
| 7 |
+
- companion
|
| 8 |
+
- full-duplex
|
| 9 |
+
- on-device
|
| 10 |
+
- vrm
|
| 11 |
+
- text-to-motion
|
| 12 |
---
|
| 13 |
+
|
| 14 |
+
# ミマモ(Mimamo)
|
| 15 |
+
|
| 16 |
+
**スマホの中だけで動く、3D の相棒アプリです。** 作者は焼きマスク(yakimask)です。
|
| 17 |
+
|
| 18 |
+
話しかけると、3D の女の子が声で返事をして、表情と体の動きでこたえます。
|
| 19 |
+
会話の AI・聞き取り・声・体の動きは、すべてスマホの中で動きます(インターネットに会話を送りません)。
|
| 20 |
+
そのうえで、1 日の予定づくり・アラーム・勉強中にアプリを止める、までを 1 つのアプリでやります。
|
| 21 |
+
|
| 22 |
+
<p>
|
| 23 |
+
<img src="screenshots/01_home.png" width="200">
|
| 24 |
+
<img src="screenshots/02_menu.png" width="200">
|
| 25 |
+
<img src="screenshots/04_day.png" width="200">
|
| 26 |
+
<img src="screenshots/06_block.png" width="200">
|
| 27 |
+
</p>
|
| 28 |
+
|
| 29 |
+
> 画面の写真は仮想端末(エミュレーター)で撮りました。会話の AI のファイルを入れていない状態なので、会話欄はあいさつだけです。
|
| 30 |
+
|
| 31 |
+
- 版: 0.8.4
|
| 32 |
+
- 入れ方: `mimamo-0.8.4.apk` をスマホに入れる(Google Play には出していません)
|
| 33 |
+
- 動く機種: Android 10 以上、64 ビットの ARM(arm64-v8a)
|
| 34 |
+
- ライセンス: Apache License 2.0(中に入れている部品・モデルは、それぞれ元のライセンス)
|
| 35 |
+
|
| 36 |
+
---
|
| 37 |
+
|
| 38 |
+
## できること
|
| 39 |
+
|
| 40 |
+
### 1. 声で話す(全二重)
|
| 41 |
+
|
| 42 |
+
アプリを開くと、すぐに声の会話が始まります。ボタンを押す必要はありません。
|
| 43 |
+
|
| 44 |
+
- **話している途中で割り込めます。** AI が話している最中にこちらが話し始めると、AI は話すのをやめて聞きます。
|
| 45 |
+
- **相づちを打ちます。** こちらが話している間に「うん」「へえ」などを返します(入り切りできます)。
|
| 46 |
+
- **話し終わりを聞き分けます。** 少し黙っただけでは割り込まず、話し終わってから返事をします。
|
| 47 |
+
- 画面を離れると声の会話は止まり、戻るとまた始まります。
|
| 48 |
+
- キーボードのボタンで、文字の会話にも切り替えられます。
|
| 49 |
+
|
| 50 |
+
声の会話の仕組みは、作者の別の作品 YAKISFULL-DUPLEX と同じです(C++ をそのまま入れています)。
|
| 51 |
+
|
| 52 |
+
### 2. 3D の体で返事をする
|
| 53 |
+
|
| 54 |
+
AI は返事の頭に、表情と動きを書きます。たとえば
|
| 55 |
+
|
| 56 |
+
```
|
| 57 |
+
<表情>うれしい<表情><3D>wave<3D>テスト満点なんだ、すごいね!
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
- **表情**: 3D の顔がその表情になります。
|
| 61 |
+
- **動き**: 英語の文(`wave`、`turn and jump` など)から、その場で全身の動きを作ります。決まった動きの一覧から選ぶのではなく、**自由な英語の文から動きを作ります。**
|
| 62 |
+
動きを作る AI は、作者が作った PartLock-CMU です。スマホで間に合うように、重みを 8 ビットに縮めて入れています。
|
| 63 |
+
- **話している間は動き続けます。** 声の会話では、AI が 1 文話すたびに「手ぶりをしながら話す」動きが延びて、話し終わると止まります。
|
| 64 |
+
- 口は話しているあいだ動きます。
|
| 65 |
+
|
| 66 |
+
### 3. カメラを見せて話す
|
| 67 |
+
|
| 68 |
+
カメラのボタンを押すと、カメラに映っているものを AI に見せながら話せます。
|
| 69 |
+
AI が返事をする番のたびに、そのときの 1 コマを AI に渡します。
|
| 70 |
+
|
| 71 |
+
使うには、会話の AI に合った「目のファイル」(mmproj)を設定で選びます(Gemma 4 E2B なら、その mmproj)。
|
| 72 |
+
|
| 73 |
+
### 4. 会話でアラームとタイマーを入れる
|
| 74 |
+
|
| 75 |
+
「明日 7 時に起こして」「3 分はかって」のように話すだけで入ります。
|
| 76 |
+
|
| 77 |
+
- 時刻の読み取りは、まずプログラムでやります(速くて確実)。
|
| 78 |
+
- プログラムで読めなかった言い方のときだけ、AI に読み取らせます。
|
| 79 |
+
- アラームが鳴ると、画面いっぱいに出て、時刻を声で言います。
|
| 80 |
+
|
| 81 |
+
### 5. 勉強中にアプリを止める
|
| 82 |
+
|
| 83 |
+
決めた時間に、選んだアプリ(YouTube など)を開くと、ホーム画面に戻します。
|
| 84 |
+
|
| 85 |
+
- 止めている間に何回も開こうとすると、ミマモが注意します。
|
| 86 |
+
- **見すぎたら休憩**: 選んだアプリを続けて 30 分見たら、5 分見られなくなります。早く解きたいときは、ミニゲーム(約 5 分)をクリアします。
|
| 87 |
+
- 見張り役は、アプリの本体とは別の入れ物(プロセス)で動きます。本体(会話の AI・3D)が重くて落ちても、見張りは止まりません。
|
| 88 |
+
- 動画の裏再生や小さな窓(ピクチャー・イン・ピクチャー)でスマホに触れなくなる問題をふせぐ作りにしています。
|
| 89 |
+
|
| 90 |
+
### 6. 予定と 1 日のまとめ(Gemini)
|
| 91 |
+
|
| 92 |
+
<p>
|
| 93 |
+
<img src="screenshots/03_calendar.png" width="200">
|
| 94 |
+
<img src="screenshots/05_plan.png" width="200">
|
| 95 |
+
<img src="screenshots/07_report.png" width="200">
|
| 96 |
+
<img src="screenshots/08_settings.png" width="200">
|
| 97 |
+
</p>
|
| 98 |
+
|
| 99 |
+
- **カレンダー**: 2020〜2050 年。日付を押すと、その日の時間割が出ます。
|
| 100 |
+
- **予定と目標**: 「1 日のうち絶対したいことと時間」「1 日・1 週間のルーティン」「明日達成したいこと」「1〜12 か月後の目標」「性格」を入れておきます。
|
| 101 |
+
- **毎晩 23:00 に自動で**: その日の会話・予定・アプリの利用時間をもとに、Gemini が「1 日のまとめ」と「明日の予定(分単位)」を作り、カレンダーに入れます。
|
| 102 |
+
- **レポート**: 1 日のまとめ、予定を破ってアプリを開こうとした回数、アプリの利用時間。7 日前まで見られます。
|
| 103 |
+
- **Gmail**: スマホに届いた Gmail の通知から、予定を見つけてカレンダーに入れます(通知を読むだけで、Google へのログインはしません)。
|
| 104 |
+
- **Google カレンダー**: スマホの中のカレンダーに書いて、Google カレンダーと同期できます。
|
| 105 |
+
|
| 106 |
+
この 6 番だけは Gemini(インターネット)を使います。Gemini の API キーを設定に入れたときだけ動きます。入れなければ、6 番以外は全部スマホの中だけで動きます。
|
| 107 |
+
|
| 108 |
+
> 無料枠の Gemini API キーで送った中身は、Google の人が品質を上げるために読む場合があります(Gemini API の規約)。
|
| 109 |
+
|
| 110 |
+
---
|
| 111 |
+
|
| 112 |
+
## はじめ方
|
| 113 |
+
|
| 114 |
+
1. `mimamo-0.8.4.apk` をスマホに入れて開きます。
|
| 115 |
+
2. マイクとカメラの許可を出します。
|
| 116 |
+
3. **設定 → 会話の AI のファイル(.gguf)** で、会話の AI を選びます。作者は **Gemma 4 E2B**(Q4_K_M)で確かめています。
|
| 117 |
+
4. **設定 → 声(VOICEVOX)** で声をダウンロードします。
|
| 118 |
+
5. (カメラを使うとき)**設定 → 目のファイル(カメラを見る)** で、会話の AI に合った mmproj を選びます。
|
| 119 |
+
6. (予定づくりを使うとき)**設定 → Gemini の API キー** を入れます。
|
| 120 |
+
7. (アプリを止めるを使うとき)スマホの設定の「ユーザー補助」で「ミマモ(アプリを止める見張り)」をオンにします。
|
| 121 |
+
灰色でオンにできないときは、先にミマモの「アプリ情報」を開き、右上の ⋮ から「制限付き設定を許可」を押します(Google Play 以外から入れたアプリは、こうしないとオンにできません)。
|
| 122 |
+
|
| 123 |
+
聞き取りのモデル(Moonshine の日本語モデル)は、初めて声の会話を始めたときに自動で取ってきます。
|
| 124 |
+
|
| 125 |
+
### 機種ごとの注意
|
| 126 |
+
|
| 127 |
+
Xiaomi・Huawei・OnePlus・Samsung などは、裏で動くアプリを強く止めることがあります。
|
| 128 |
+
アプリを止める機能やアラームが動かないときは、その機種の「自動起動」「バッテリーの最適化をしない」をミマモに許可してください。
|
| 129 |
+
|
| 130 |
+
---
|
| 131 |
+
|
| 132 |
+
## 中で動いているもの
|
| 133 |
+
|
| 134 |
+
| 役目 | 使っているもの | どこで動くか |
|
| 135 |
+
|---|---|---|
|
| 136 |
+
| 会話の AI | llama.cpp(GGUF。例: Gemma 4 E2B) | スマホ |
|
| 137 |
+
| カメラの 1 コマを読む | llama.cpp の mtmd(mmproj) | スマホ |
|
| 138 |
+
| 聞き取り | Moonshine(日本語) | スマホ |
|
| 139 |
+
| 話し終わりの判定 | Smart Turn v3 | スマホ |
|
| 140 |
+
| 相づち | VAP(MaAI の日本語の重み) | スマホ |
|
| 141 |
+
| 声 | VOICEVOX | スマホ |
|
| 142 |
+
| 体の動きを作る | PartLock-CMU(作者自作)+ CLIP の文の部分 | スマホ(ONNX Runtime) |
|
| 143 |
+
| 3D の表示 | three.js + three-vrm、千駄ヶ谷 篠(VRM) | スマホ |
|
| 144 |
+
| 1 日のまとめ・明日の予定 | Gemini | インターネット(キーを入れたときだけ) |
|
| 145 |
+
|
| 146 |
+
---
|
| 147 |
+
|
| 148 |
+
## 中身(ソース)から組み立てる
|
| 149 |
+
|
| 150 |
+
`source/` に、APK を作るのに要るものを全部入れています(YAKISFULL-DUPLEX の C++ と、llama.cpp などの部品も入っています)。
|
| 151 |
+
|
| 152 |
+
要るもの:
|
| 153 |
+
|
| 154 |
+
- JDK 17
|
| 155 |
+
- Android SDK(compileSdk 36)、NDK 29.0.14206865、CMake 3.22.1
|
| 156 |
+
- Gradle 9.9.1
|
| 157 |
+
- llama.cpp の Vulkan の部品を作るために:
|
| 158 |
+
- NDK の `shader-tools`(glslc)に PATH を通す
|
| 159 |
+
- パソコン用の C++ の組み立て道具(Windows なら llvm-mingw など)に PATH を通す
|
| 160 |
+
|
| 161 |
+
組み立て方:
|
| 162 |
+
|
| 163 |
+
```
|
| 164 |
+
cd source
|
| 165 |
+
(local.properties に sdk.dir=Android SDK の場所 を書く)
|
| 166 |
+
gradle assembleRelease
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
出来上がりは `source/app/build/outputs/apk/release/` に出ます。
|
| 170 |
+
署名したいときは、`source/keystore.properties` に `storeFile` / `storePassword` / `keyAlias` / `keyPassword` を書きます(無ければ署名なしで作ります)。
|
| 171 |
+
|
| 172 |
+
主なファイル:
|
| 173 |
+
|
| 174 |
+
| ファイル | 中身 |
|
| 175 |
+
|---|---|
|
| 176 |
+
| `app/src/main/java/jp/yaki/aibou/HomeScreen.kt` | ホーム。会話欄、声の会話、会話でアラームを入れる |
|
| 177 |
+
| `app/src/main/java/jp/yaki/aibou/Brain.kt` | 会話の AI を動かす。返事の頭の表情と動きを読む |
|
| 178 |
+
| `app/src/main/java/jp/yaki/aibou/Motion.kt` | 英語の文から体の動きをその場で作る(PartLock) |
|
| 179 |
+
| `app/src/main/assets/avatar/avatar.html` | 3D の表示。関節の位置から骨の向きを合わせる |
|
| 180 |
+
| `app/src/main/java/jp/yaki/aibou/LiveCamera.kt` | カメラの 1 コマを AI に渡す |
|
| 181 |
+
| `app/src/main/cpp/llm_vision.cpp` | 会話の AI が写真も受け取れるようにした C++ |
|
| 182 |
+
| `app/src/main/java/jp/yaki/aibou/Guard.kt` | アプリを止める見張り役(別のプロセス) |
|
| 183 |
+
| `app/src/main/java/jp/yaki/aibou/Alarms.kt` | アラームとタイマー |
|
| 184 |
+
| `app/src/main/java/jp/yaki/aibou/Nightly.kt` | 毎晩 23:00 のまとめと明日の予定(Gemini) |
|
| 185 |
+
| `app/src/main/java/jp/yaki/aibou/Mail.kt` | Gmail の通知から予定を立てる・Google カレンダー同期 |
|
| 186 |
+
|
| 187 |
+
パッケージ名は、作っている途中の仮の名前のまま `jp.yaki.aibou` です。
|
| 188 |
+
|
| 189 |
+
---
|
| 190 |
+
|
| 191 |
+
## まだ確かめていないこと・弱いところ
|
| 192 |
+
|
| 193 |
+
- **カメラを見せて話す**は、スマホで写真を見て答えるところまでは、まだ確かめていません(仮想端末には Gemma 4 E2B が入らないため)。パソコンで Gemma 4 E2B に 6 枚の写真を見せたときは 4 枚正しく答え、小さいリモコンと上下さかさまの文字を見落としました。
|
| 194 |
+
- 体の動きを作る速さは、スマホの速さで変わります。
|
| 195 |
+
- 動きの英語は AI が書くので、ときどき内容に合わない動きになります。
|
| 196 |
+
|
| 197 |
+
---
|
| 198 |
+
|
| 199 |
+
## ライセンス
|
| 200 |
+
|
| 201 |
+
- ミマモ本体(作者が書いた部分): **Apache License 2.0**(`LICENSE`、`NOTICE`)
|
| 202 |
+
- 中に入れている部品・モデルは、それぞれ元のライセンスに従います。一覧は `source/licenses/README.md` にあります。
|
| 203 |
+
- 気をつけるもの:
|
| 204 |
+
- **Moonshine の日本語モデル**(初回に取ってくるもの)は「Moonshine Community License」で、商用には制限があります。
|
| 205 |
+
- **VOICEVOX の声**は、VOICEVOX と各キャラクターの利用規約に従います。
|
| 206 |
+
- **会話の AI**(GGUF)は、選んだモデルのライセンスに従います(Gemma 4 は Apache 2.0)。
|
| 207 |
+
- 体の動きを作る AI(PartLock-CMU)は、CMU Graphics Lab Motion Capture Database(カーネギーメロン大学)の動きで学習しています。
|
mimamo-0.8.4.apk
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ef93e2325d9af2c7ac9ba2986c47b1f27e7e2d3e48b53a38166ea31d547aa6ff
|
| 3 |
+
size 223433705
|
screenshots/01_home.png
ADDED
|
Git LFS Details
|
screenshots/02_menu.png
ADDED
|
Git LFS Details
|
screenshots/03_calendar.png
ADDED
|
Git LFS Details
|
screenshots/04_day.png
ADDED
|
Git LFS Details
|
screenshots/05_plan.png
ADDED
|
Git LFS Details
|
screenshots/06_block.png
ADDED
|
Git LFS Details
|
screenshots/07_report.png
ADDED
|
Git LFS Details
|
screenshots/08_settings.png
ADDED
|
Git LFS Details
|
source/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
source/app/build.gradle.kts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import java.util.Properties
|
| 2 |
+
|
| 3 |
+
plugins {
|
| 4 |
+
id("com.android.application")
|
| 5 |
+
}
|
| 6 |
+
|
| 7 |
+
// YAKISFULL-DUPLEX の C++(会話の本体: 聞き取り・話し終わり・相づち・割り込み・llama.cpp・VOICEVOX)を組み立てて使う
|
| 8 |
+
// ミマモ用の組み立て(app/src/main/cpp/CMakeLists.txt)は、会話の LLM だけ写真も受け取れる版に差しかえる
|
| 9 |
+
val duplexCpp = file("src/main/cpp/CMakeLists.txt")
|
| 10 |
+
|
| 11 |
+
android {
|
| 12 |
+
namespace = "jp.yaki.aibou"
|
| 13 |
+
compileSdk = 36
|
| 14 |
+
ndkVersion = "29.0.14206865"
|
| 15 |
+
|
| 16 |
+
defaultConfig {
|
| 17 |
+
applicationId = "jp.yaki.aibou"
|
| 18 |
+
minSdk = 29
|
| 19 |
+
targetSdk = 36
|
| 20 |
+
versionCode = 12
|
| 21 |
+
versionName = "0.8.4"
|
| 22 |
+
ndk { abiFilters += listOf("arm64-v8a") } // 聞き取り(Moonshine)の部品が 64 ビットの ARM 用だけなので
|
| 23 |
+
externalNativeBuild {
|
| 24 |
+
cmake {
|
| 25 |
+
arguments += listOf("-DANDROID_STL=c++_shared", "-DCMAKE_BUILD_TYPE=Release")
|
| 26 |
+
cppFlags += listOf("-O3")
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
externalNativeBuild {
|
| 31 |
+
cmake {
|
| 32 |
+
path = duplexCpp
|
| 33 |
+
version = "3.22.1"
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
// 公開用の署名の鍵: 一番上のフォルダに keystore.properties(storeFile / storePassword / keyAlias / keyPassword)を置いたときだけ使う。無いときは署名なしで作る
|
| 37 |
+
val keyProps = rootProject.file("keystore.properties")
|
| 38 |
+
if (keyProps.exists()) {
|
| 39 |
+
val k = Properties()
|
| 40 |
+
keyProps.inputStream().use { k.load(it) }
|
| 41 |
+
signingConfigs.create("release") {
|
| 42 |
+
storeFile = file(k.getProperty("storeFile"))
|
| 43 |
+
storePassword = k.getProperty("storePassword")
|
| 44 |
+
keyAlias = k.getProperty("keyAlias")
|
| 45 |
+
keyPassword = k.getProperty("keyPassword")
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
packaging { jniLibs { useLegacyPackaging = true } } // 部品(.so)を縮めて入れる
|
| 49 |
+
androidResources { noCompress += listOf("onnx", "f32") } // 大きなモデルは縮めずに入れる(取り出しが速い)
|
| 50 |
+
buildTypes {
|
| 51 |
+
release {
|
| 52 |
+
isMinifyEnabled = false
|
| 53 |
+
if (keyProps.exists()) signingConfig = signingConfigs.getByName("release")
|
| 54 |
+
}
|
| 55 |
+
debug { externalNativeBuild { cmake { arguments += "-DCMAKE_BUILD_TYPE=Release" } } } // 試すときも C++ は速い形で
|
| 56 |
+
}
|
| 57 |
+
compileOptions {
|
| 58 |
+
sourceCompatibility = JavaVersion.VERSION_17
|
| 59 |
+
targetCompatibility = JavaVersion.VERSION_17
|
| 60 |
+
}
|
| 61 |
+
buildFeatures { buildConfig = true; prefab = true } // Oboe(マイクとスピーカー)を C++ から使うため
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
dependencies {
|
| 65 |
+
implementation(files("libs/moonshine-voice-0.1.6.jar")) // きろくと同じ聞き取りの部品
|
| 66 |
+
implementation("com.google.oboe:oboe:1.11.0") // YAKISFULL と同じマイクとスピーカーの部品
|
| 67 |
+
implementation(files("libs/onnxruntime-classes.jar")) // 動きの AI(PartLock)を動かす。YAKISFULL と同じ ONNX Runtime の Java の窓口
|
| 68 |
+
}
|
source/app/libs/moonshine-voice-0.1.6.jar
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:573286a599f606abce11eb81050eb849dd363b657548d12865d50f0779d8998b
|
| 3 |
+
size 103981
|
source/app/libs/onnxruntime-classes.jar
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c58e888b612da032242b74ca3d516f8984de38cb34e740973c06f4454ab77db9
|
| 3 |
+
size 149401
|
source/app/src/main/AndroidManifest.xml
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="utf-8"?>
|
| 2 |
+
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
| 3 |
+
xmlns:tools="http://schemas.android.com/tools">
|
| 4 |
+
|
| 5 |
+
<!-- アプリの利用時間を読む(「使用状況へのアクセス」。持ち主が設定画面で許可する) -->
|
| 6 |
+
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />
|
| 7 |
+
<!-- アラームとタイマー: 時刻ちょうどに鳴らす(目覚ましのアプリ向け。入れた時点で与えられる)・画面いっぱいの通知・ふるえ -->
|
| 8 |
+
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
|
| 9 |
+
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
|
| 10 |
+
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
| 11 |
+
<uses-permission android:name="android.permission.VIBRATE" />
|
| 12 |
+
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
| 13 |
+
<uses-permission android:name="android.permission.INTERNET" />
|
| 14 |
+
<!-- 声の会話のマイク(いつも録音する機能は 0.8.0 で外した。マイクは声の会話の最中だけ使う) -->
|
| 15 |
+
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
| 16 |
+
<!-- カメラを見せて話す(AI の番のたびに、最新の 1 コマを AI に見せる) -->
|
| 17 |
+
<uses-permission android:name="android.permission.CAMERA" />
|
| 18 |
+
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
| 19 |
+
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
| 20 |
+
<!-- Google カレンダーにも予定を入れる(スマホの中のカレンダーに書き込む) -->
|
| 21 |
+
<uses-permission android:name="android.permission.READ_CALENDAR" />
|
| 22 |
+
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
|
| 23 |
+
<!-- 毎晩の処理を「ネットがつながったら動かす」のに要る -->
|
| 24 |
+
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
| 25 |
+
|
| 26 |
+
<!-- ホーム画面にあるアプリの一覧を読むため(止めるアプリを選ぶ) -->
|
| 27 |
+
<queries>
|
| 28 |
+
<intent>
|
| 29 |
+
<action android:name="android.intent.action.MAIN" />
|
| 30 |
+
<category android:name="android.intent.category.LAUNCHER" />
|
| 31 |
+
</intent>
|
| 32 |
+
</queries>
|
| 33 |
+
|
| 34 |
+
<application
|
| 35 |
+
android:allowBackup="false"
|
| 36 |
+
android:label="@string/app_name"
|
| 37 |
+
android:supportsRtl="true"
|
| 38 |
+
android:enableOnBackInvokedCallback="true"
|
| 39 |
+
android:theme="@android:style/Theme.Material.Light.NoActionBar">
|
| 40 |
+
<activity
|
| 41 |
+
android:name=".MainActivity"
|
| 42 |
+
android:exported="true"
|
| 43 |
+
android:launchMode="singleTop"
|
| 44 |
+
android:windowSoftInputMode="adjustResize">
|
| 45 |
+
<intent-filter>
|
| 46 |
+
<action android:name="android.intent.action.MAIN" />
|
| 47 |
+
<category android:name="android.intent.category.LAUNCHER" />
|
| 48 |
+
</intent-filter>
|
| 49 |
+
</activity>
|
| 50 |
+
|
| 51 |
+
<!-- アラームとタイマーを鳴らす画面(鍵がかかっていても出る) -->
|
| 52 |
+
<activity
|
| 53 |
+
android:name=".RingActivity"
|
| 54 |
+
android:exported="false"
|
| 55 |
+
android:excludeFromRecents="true"
|
| 56 |
+
android:launchMode="singleInstance"
|
| 57 |
+
android:showWhenLocked="true"
|
| 58 |
+
android:turnScreenOn="true"
|
| 59 |
+
android:taskAffinity="jp.yaki.aibou.ring" />
|
| 60 |
+
|
| 61 |
+
<receiver android:name=".AlarmReceiver" android:exported="false" />
|
| 62 |
+
<!-- Gmail の通知を読んで予定を立てる(「通知へのアクセス」で持ち主が許可する) -->
|
| 63 |
+
<service
|
| 64 |
+
android:name=".MailListener"
|
| 65 |
+
android:exported="true"
|
| 66 |
+
android:label="ミマモ(メールから予定)"
|
| 67 |
+
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
|
| 68 |
+
<intent-filter>
|
| 69 |
+
<action android:name="android.service.notification.NotificationListenerService" />
|
| 70 |
+
</intent-filter>
|
| 71 |
+
</service>
|
| 72 |
+
<!-- 毎晩 23:00 の自動処理(まとめ・明日の予定・起きる時刻) -->
|
| 73 |
+
<receiver android:name=".NightlyReceiver" android:exported="false" />
|
| 74 |
+
<service
|
| 75 |
+
android:name=".NightlyJob"
|
| 76 |
+
android:exported="false"
|
| 77 |
+
android:permission="android.permission.BIND_JOB_SERVICE" />
|
| 78 |
+
<receiver android:name=".BootReceiver" android:exported="true">
|
| 79 |
+
<intent-filter>
|
| 80 |
+
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
| 81 |
+
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
| 82 |
+
</intent-filter>
|
| 83 |
+
</receiver>
|
| 84 |
+
|
| 85 |
+
<!-- アプリを止める見張り役(ユーザー補助のサービス)。
|
| 86 |
+
ミマモ本体(会話の AI・声・3D で重い)とは別の入れ物(:guard)で動かす。本体が落ちても、見張り役は巻き込まれない -->
|
| 87 |
+
<service
|
| 88 |
+
android:name=".Guard"
|
| 89 |
+
android:process=":guard"
|
| 90 |
+
android:exported="false"
|
| 91 |
+
android:label="@string/guard_name"
|
| 92 |
+
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
|
| 93 |
+
<intent-filter>
|
| 94 |
+
<action android:name="android.accessibilityservice.AccessibilityService" />
|
| 95 |
+
</intent-filter>
|
| 96 |
+
<meta-data
|
| 97 |
+
android:name="android.accessibilityservice"
|
| 98 |
+
android:resource="@xml/guard" />
|
| 99 |
+
</service>
|
| 100 |
+
</application>
|
| 101 |
+
</manifest>
|
source/app/src/main/assets/avatar/avatar.html
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<!-- ミマモの 3D アバター(VRM)。three.js 0.175.0 と three-vrm 3.4.0(どちらも MIT)。ネットにはつながない
|
| 3 |
+
Kotlin から呼ぶ入口: av.face(名前, 強さ) / av.talking(true|false) / av.motion(英語の動き) / av.frames(PartLock の動き)
|
| 4 |
+
・カメラは毎コマ、頭の骨の位置になめらかについていく(動き回っても顔は真ん中)
|
| 5 |
+
・何もしていないときは、まばたきと呼吸のゆれ -->
|
| 6 |
+
<html>
|
| 7 |
+
<head>
|
| 8 |
+
<meta charset="utf-8">
|
| 9 |
+
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
|
| 10 |
+
<style>
|
| 11 |
+
html, body { margin: 0; height: 100%; overflow: hidden; background: transparent; }
|
| 12 |
+
canvas { display: block; width: 100%; height: 100%; }
|
| 13 |
+
</style>
|
| 14 |
+
<script type="importmap">{ "imports": { "three": "./lib/three.module.min.js" } }</script>
|
| 15 |
+
</head>
|
| 16 |
+
<body>
|
| 17 |
+
<script type="module">
|
| 18 |
+
import * as THREE from 'three';
|
| 19 |
+
import { GLTFLoader } from './jsm/loaders/GLTFLoader.js';
|
| 20 |
+
import { VRMLoaderPlugin, VRMUtils } from './lib/three-vrm.module.min.js';
|
| 21 |
+
|
| 22 |
+
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
|
| 23 |
+
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
| 24 |
+
renderer.setSize(window.innerWidth, window.innerHeight);
|
| 25 |
+
renderer.setClearColor(0x000000, 0);
|
| 26 |
+
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
| 27 |
+
document.body.appendChild(renderer.domElement);
|
| 28 |
+
|
| 29 |
+
const scene = new THREE.Scene();
|
| 30 |
+
const camera = new THREE.PerspectiveCamera(28, window.innerWidth / window.innerHeight, 0.05, 50);
|
| 31 |
+
scene.add(new THREE.AmbientLight(0xffffff, 0.9));
|
| 32 |
+
const sun = new THREE.DirectionalLight(0xffffff, 1.6); sun.position.set(0.5, 1.5, 2.0); scene.add(sun);
|
| 33 |
+
|
| 34 |
+
let vrm = null;
|
| 35 |
+
const clock = new THREE.Clock();
|
| 36 |
+
const say = (m) => { try { window.Android && window.Android.log(String(m)); } catch (e) {} };
|
| 37 |
+
|
| 38 |
+
// ---------------- 読み込み
|
| 39 |
+
new GLTFLoader().register((p) => new VRMLoaderPlugin(p)).load('./model.vrm', (gltf) => {
|
| 40 |
+
vrm = gltf.userData.vrm;
|
| 41 |
+
VRMUtils.removeUnnecessaryVertices(gltf.scene);
|
| 42 |
+
VRMUtils.combineSkeletons(gltf.scene);
|
| 43 |
+
VRMUtils.rotateVRM0(vrm); // VRM 0.x を前向き(+Z)にそろえる
|
| 44 |
+
vrm.scene.traverse((o) => { o.frustumCulled = false; });
|
| 45 |
+
scene.add(vrm.scene);
|
| 46 |
+
try { measureRest(); } catch (e) { say('骨の休みの向きを測れませんでした: ' + e); }
|
| 47 |
+
restPose();
|
| 48 |
+
say('VRM を読み込みました。表情の名前: ' + (vrm.expressionManager ? vrm.expressionManager.expressions.map((e) => e.expressionName).join(',') : 'なし'));
|
| 49 |
+
try { window.Android && window.Android.ready(); } catch (e) {}
|
| 50 |
+
}, undefined, (e) => say('VRM を読み込めませんでした: ' + e));
|
| 51 |
+
|
| 52 |
+
const bone = (n) => vrm && vrm.humanoid.getNormalizedBoneNode(n);
|
| 53 |
+
|
| 54 |
+
/** T の字から、腕を下ろした立ち姿へ */
|
| 55 |
+
function restPose() {
|
| 56 |
+
const L = bone('leftUpperArm'), R = bone('rightUpperArm');
|
| 57 |
+
if (L) L.rotation.set(0, 0, 1.2); // 左腕は +、右腕は − で下がる(仮想端末で確かめた向き)
|
| 58 |
+
if (R) R.rotation.set(0, 0, -1.2);
|
| 59 |
+
const LL = bone('leftLowerArm'), RL = bone('rightLowerArm');
|
| 60 |
+
if (LL) LL.rotation.set(0, 0, 0.15);
|
| 61 |
+
if (RL) RL.rotation.set(0, 0, -0.15);
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
// ---------------- 表情(タグの言葉 → VRM の表情)
|
| 65 |
+
const FACE = { 'ふつう': {}, 'うれしい': { happy: 1 }, 'おこる': { angry: 1 }, 'かなしい': { sad: 1 },
|
| 66 |
+
'おどろき': { oh: 0.7, surprised: 1 }, 'てれ': { relaxed: 0.6, happy: 0.3 }, 'ねむい': { blink: 0.55 } };
|
| 67 |
+
let faceNow = {};
|
| 68 |
+
function face(word) {
|
| 69 |
+
let f = FACE['ふつう'];
|
| 70 |
+
for (const k in FACE) if (word && word.indexOf(k.slice(0, 2)) >= 0) f = FACE[k];
|
| 71 |
+
if (word && /喜|笑|楽し/.test(word)) f = FACE['うれしい'];
|
| 72 |
+
if (word && /怒/.test(word)) f = FACE['おこる'];
|
| 73 |
+
if (word && /悲|さみし/.test(word)) f = FACE['かなしい'];
|
| 74 |
+
if (word && /驚|びっくり/.test(word)) f = FACE['おどろき'];
|
| 75 |
+
faceNow = f;
|
| 76 |
+
say('表情: ' + word + ' → ' + JSON.stringify(f));
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
// ---------------- 口(しゃべっている間、あいうえおで動かす)
|
| 80 |
+
let talking = false, mouthT = 0, mouth = { aa: 0, ih: 0, ou: 0, ee: 0, oh: 0 }, mouthGoal = 'aa';
|
| 81 |
+
|
| 82 |
+
// ---------------- まばたき
|
| 83 |
+
let blinkT = 2 + Math.random() * 3, blinkV = 0;
|
| 84 |
+
|
| 85 |
+
// ---------------- 動き(PartLock をつなぐまでの代わり: 骨を回して作る)
|
| 86 |
+
let motion = null; // { kind, t, dur }
|
| 87 |
+
function startMotion(text) {
|
| 88 |
+
const s = String(text || '').toLowerCase();
|
| 89 |
+
const list = [];
|
| 90 |
+
if (/turn|spin|rotate/.test(s)) list.push(['turn', 0.8]);
|
| 91 |
+
if (/jump|hop/.test(s)) list.push(['jump', 0.7]);
|
| 92 |
+
if (/wave|hello|bye/.test(s)) list.push(['wave', 1.6]);
|
| 93 |
+
if (/shake/.test(s)) list.push(['shake', 1.2]);
|
| 94 |
+
if (/tilt/.test(s)) list.push(['tilt', 1.2]);
|
| 95 |
+
if (/nod|bow|yes/.test(s) || list.length === 0) list.push(['nod', 1.0]);
|
| 96 |
+
motion = { list, i: 0, t: 0 };
|
| 97 |
+
}
|
| 98 |
+
function applyMotion(dt) {
|
| 99 |
+
if (!motion || !vrm) return;
|
| 100 |
+
const [kind, dur] = motion.list[motion.i];
|
| 101 |
+
motion.t += dt;
|
| 102 |
+
const k = Math.min(1, motion.t / dur), sn = Math.sin(Math.PI * k);
|
| 103 |
+
const head = bone('head'), hips = bone('hips'), RU = bone('rightUpperArm'), RL = bone('rightLowerArm');
|
| 104 |
+
if (kind === 'nod' && head) head.rotation.x = 0.3 * Math.sin(2 * Math.PI * k * 2) * (1 - k * 0.3);
|
| 105 |
+
if (kind === 'shake' && head) head.rotation.y = 0.45 * Math.sin(2 * Math.PI * k * 3) * sn;
|
| 106 |
+
if (kind === 'tilt' && head) head.rotation.z = 0.3 * sn;
|
| 107 |
+
if (kind === 'jump' && hips) hips.position.y = baseHipY + 0.18 * sn;
|
| 108 |
+
if (kind === 'turn') vrm.scene.rotation.y = 2 * Math.PI * (k < 1 ? (1 - Math.cos(Math.PI * k)) / 2 : 1);
|
| 109 |
+
if (kind === 'wave' && RU && RL) { RU.rotation.z = -1.2 + 2.6 * Math.min(1, sn * 2); RL.rotation.z = 0.5 * Math.sin(motion.t * 12) * sn; }
|
| 110 |
+
if (motion.t >= dur) {
|
| 111 |
+
if (head) head.rotation.set(0, 0, 0);
|
| 112 |
+
if (hips) hips.position.y = baseHipY;
|
| 113 |
+
vrm.scene.rotation.y = 0;
|
| 114 |
+
restPose();
|
| 115 |
+
motion.i++; motion.t = 0;
|
| 116 |
+
if (motion.i >= motion.list.length) motion = null;
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
let baseHipY = null;
|
| 120 |
+
|
| 121 |
+
// ---------------- PartLock の動き(22 関節の位置 → VRM の骨の向き)
|
| 122 |
+
// 関節の並び(SMPL): 0 腰 1 左股 2 右股 3 背1 4 左ひざ 5 右ひざ 6 背2 7 左足首 8 右足首 9 背3 10 左つま先 11 右つま先
|
| 123 |
+
// 12 首 13 左鎖骨 14 右鎖骨 15 頭 16 左肩 17 右肩 18 左ひじ 19 右ひじ 20 左手首 21 右手首
|
| 124 |
+
// 向き: 上が +Y、正面が +Z、体の左が +X(VRM を前向きにしたときと同じ)
|
| 125 |
+
// やり方: 骨ごとに「休みの姿勢(T の字)での骨の向き」を、動きの関節の向きへ最小の回転で合わせる。胴は左右の向きも使う
|
| 126 |
+
const PL = { queue: [], cur: null, prev: null, t: 0, w: 0, idle: 0, rest: null, ratio: null, Q0: new THREE.Quaternion(), restQ: {}, origin: null };
|
| 127 |
+
const LIMB = [ // [骨, 子の骨(休みの向きを測る), 関節 a, 関節 b]
|
| 128 |
+
['leftShoulder', 'leftUpperArm', 13, 16], ['rightShoulder', 'rightUpperArm', 14, 17],
|
| 129 |
+
['leftUpperArm', 'leftLowerArm', 16, 18], ['leftLowerArm', 'leftHand', 18, 20],
|
| 130 |
+
['rightUpperArm', 'rightLowerArm', 17, 19], ['rightLowerArm', 'rightHand', 19, 21],
|
| 131 |
+
['leftUpperLeg', 'leftLowerLeg', 1, 4], ['leftLowerLeg', 'leftFoot', 4, 7], ['leftFoot', 'leftToes', 7, 10],
|
| 132 |
+
['rightUpperLeg', 'rightLowerLeg', 2, 5], ['rightLowerLeg', 'rightFoot', 5, 8], ['rightFoot', 'rightToes', 8, 11]];
|
| 133 |
+
const TORSO = [ // [骨, 関節 a, 関節 b(上向きの軸), 肩の左右をどれだけ混ぜるか]
|
| 134 |
+
['hips', 0, 3, 0], ['spine', 3, 6, 0.3], ['chest', 6, 9, 0.65], ['upperChest', 9, 12, 1], ['neck', 12, 15, 1], ['head', 12, 15, 1]];
|
| 135 |
+
const ORDER = ['hips', 'spine', 'chest', 'upperChest', 'neck', 'head', 'leftShoulder', 'leftUpperArm', 'leftLowerArm',
|
| 136 |
+
'rightShoulder', 'rightUpperArm', 'rightLowerArm', 'leftUpperLeg', 'leftLowerLeg', 'leftFoot', 'rightUpperLeg', 'rightLowerLeg', 'rightFoot'];
|
| 137 |
+
const PARENT = { spine: ['hips'], chest: ['spine'], upperChest: ['chest'], neck: ['upperChest', 'chest'], head: ['neck'],
|
| 138 |
+
leftShoulder: ['upperChest', 'chest'], rightShoulder: ['upperChest', 'chest'],
|
| 139 |
+
leftUpperArm: ['leftShoulder', 'upperChest', 'chest'], rightUpperArm: ['rightShoulder', 'upperChest', 'chest'],
|
| 140 |
+
leftLowerArm: ['leftUpperArm'], rightLowerArm: ['rightUpperArm'], leftUpperLeg: ['hips'], rightUpperLeg: ['hips'],
|
| 141 |
+
leftLowerLeg: ['leftUpperLeg'], rightLowerLeg: ['rightUpperLeg'], leftFoot: ['leftLowerLeg'], rightFoot: ['rightLowerLeg'] };
|
| 142 |
+
const parentOf = (n) => (PARENT[n] || []).find((p) => bone(p));
|
| 143 |
+
|
| 144 |
+
/** 読み込んだ直後(T の字のまま)に、骨の休みの向き(世界の向き)と脚の長さを測る */
|
| 145 |
+
function measureRest() {
|
| 146 |
+
vrm.scene.updateMatrixWorld(true);
|
| 147 |
+
const hips = bone('hips'); hips.parent.getWorldQuaternion(PL.Q0);
|
| 148 |
+
const wp = (n) => { const b = bone(n); return b ? b.getWorldPosition(new THREE.Vector3()) : null; };
|
| 149 |
+
PL.rest = {};
|
| 150 |
+
for (const [n, c] of LIMB) {
|
| 151 |
+
const a = wp(n); if (!a) continue;
|
| 152 |
+
let b = wp(c);
|
| 153 |
+
if (!b) b = n.endsWith('Foot') ? a.clone().add(new THREE.Vector3(0, -0.05, 0.13)) : null;
|
| 154 |
+
if (b) PL.rest[n] = b.sub(a).normalize();
|
| 155 |
+
}
|
| 156 |
+
const leg = wp('leftUpperLeg').distanceTo(wp('leftLowerLeg')) + wp('leftLowerLeg').distanceTo(wp('leftFoot'));
|
| 157 |
+
PL.vrmLeg = leg;
|
| 158 |
+
PL.hipsRestLocal = hips.position.clone();
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
const P3 = (P, j) => new THREE.Vector3(P[3 * j], P[3 * j + 1], P[3 * j + 2]);
|
| 162 |
+
const qInvQ0 = () => PL.Q0.clone().invert();
|
| 163 |
+
|
| 164 |
+
/** 1 コマぶんの関節の位置 → 骨ごとの「世界での回転(休みから)」 */
|
| 165 |
+
function solve(P) {
|
| 166 |
+
const D = {};
|
| 167 |
+
const lat0 = P3(P, 1).sub(P3(P, 2)).normalize(), lat1 = P3(P, 16).sub(P3(P, 17)).normalize();
|
| 168 |
+
for (const [n, a, b, mix] of TORSO) {
|
| 169 |
+
if (!bone(n)) continue;
|
| 170 |
+
const y = P3(P, b).sub(P3(P, a)).normalize();
|
| 171 |
+
const x = lat0.clone().lerp(lat1, mix); x.sub(y.clone().multiplyScalar(x.dot(y))).normalize();
|
| 172 |
+
const z = new THREE.Vector3().crossVectors(x, y);
|
| 173 |
+
D[n] = new THREE.Quaternion().setFromRotationMatrix(new THREE.Matrix4().makeBasis(x, y, z));
|
| 174 |
+
}
|
| 175 |
+
for (const [n, , a, b] of LIMB) {
|
| 176 |
+
if (!bone(n) || !PL.rest[n]) continue;
|
| 177 |
+
const p = parentOf(n), Dp = (p && D[p]) || D.hips;
|
| 178 |
+
const from = PL.rest[n].clone().applyQuaternion(Dp);
|
| 179 |
+
const to = P3(P, b).sub(P3(P, a)).normalize();
|
| 180 |
+
D[n] = new THREE.Quaternion().setFromUnitVectors(from, to).multiply(Dp);
|
| 181 |
+
}
|
| 182 |
+
// 世界での回転 → 骨そのものの回転(ふつうの骨は休みが 0 なので: 親の逆 × 自分。全体の向き Q0 をはさむ)
|
| 183 |
+
const L = {}, iQ0 = qInvQ0();
|
| 184 |
+
for (const n of ORDER) {
|
| 185 |
+
if (!D[n]) continue;
|
| 186 |
+
const p = n === 'hips' ? null : parentOf(n);
|
| 187 |
+
const Dp = p ? D[p] : new THREE.Quaternion();
|
| 188 |
+
L[n] = iQ0.clone().multiply(Dp.clone().invert()).multiply(D[n]).multiply(PL.Q0);
|
| 189 |
+
}
|
| 190 |
+
return L;
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
/** 位置を 2 コマのあいだで混ぜる */
|
| 194 |
+
function lerpP(a, b, k) { const o = new Array(66); for (let i = 0; i < 66; i++) o[i] = a.p[i] + (b.p[i] - a.p[i]) * k; return o; }
|
| 195 |
+
|
| 196 |
+
function applyPartLock(dt) {
|
| 197 |
+
if (!vrm || !PL.rest) return false;
|
| 198 |
+
const q = PL.queue;
|
| 199 |
+
if (q.length) { PL.idle = 0; } else { PL.idle += dt; }
|
| 200 |
+
// 30 コマ/秒で進める(4 コマずつ届く。足りないときは最後のコマで待つ)
|
| 201 |
+
if (PL.cur === null && q.length) { PL.cur = q.shift(); PL.prev = PL.cur; PL.t = 0; }
|
| 202 |
+
if (PL.cur === null) return false;
|
| 203 |
+
PL.t += dt * 30;
|
| 204 |
+
while (PL.t >= 1 && q.length) { PL.prev = PL.cur; PL.cur = q.shift(); PL.t -= 1; }
|
| 205 |
+
if (PL.t > 1) PL.t = 1;
|
| 206 |
+
const active = PL.idle < 0.4;
|
| 207 |
+
PL.w += ((active ? 1 : 0) - PL.w) * Math.min(1, dt * 6);
|
| 208 |
+
if (!active && PL.w < 0.01) { PL.cur = null; PL.prev = null; PL.origin = null; PL.w = 0; return false; }
|
| 209 |
+
const P = lerpP(PL.prev, PL.cur, PL.t);
|
| 210 |
+
const tr = [PL.prev.tr[0] + (PL.cur.tr[0] - PL.prev.tr[0]) * PL.t, PL.prev.tr[1] + (PL.cur.tr[1] - PL.prev.tr[1]) * PL.t];
|
| 211 |
+
if (PL.ratio === null) {
|
| 212 |
+
const leg = P3(P, 1).distanceTo(P3(P, 4)) + P3(P, 4).distanceTo(P3(P, 7));
|
| 213 |
+
PL.ratio = PL.vrmLeg / leg;
|
| 214 |
+
}
|
| 215 |
+
const L = solve(P);
|
| 216 |
+
for (const n in L) {
|
| 217 |
+
const b = bone(n); if (!b) continue;
|
| 218 |
+
if (!(n in PL.restQ)) PL.restQ[n] = b.quaternion.clone();
|
| 219 |
+
b.quaternion.copy(PL.restQ[n]).slerp(L[n], PL.w);
|
| 220 |
+
}
|
| 221 |
+
// 腰の位置(地面は 0。歩いた分も足す)。動き出した所を原点にする
|
| 222 |
+
if (!PL.origin) PL.origin = [tr[0], tr[1]];
|
| 223 |
+
const hips = bone('hips');
|
| 224 |
+
const wpos = new THREE.Vector3((P[0] + tr[0] - PL.origin[0]) * PL.ratio, P[1] * PL.ratio, (P[2] + tr[1] - PL.origin[1]) * PL.ratio);
|
| 225 |
+
const local = wpos.applyQuaternion(qInvQ0());
|
| 226 |
+
hips.position.copy(PL.hipsRestLocal).lerp(local, PL.w);
|
| 227 |
+
return true;
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
// ---------------- カメラ(頭の骨になめらかについていく)
|
| 231 |
+
const headPos = new THREE.Vector3(), aim = new THREE.Vector3(), first = { done: false };
|
| 232 |
+
function follow(dt) {
|
| 233 |
+
const head = bone('head'); if (!head) return;
|
| 234 |
+
head.getWorldPosition(headPos);
|
| 235 |
+
if (!first.done) { aim.copy(headPos); first.done = true; }
|
| 236 |
+
aim.lerp(headPos, 1 - Math.exp(-dt * 6)); // 少し遅れてついていく
|
| 237 |
+
const look = new THREE.Vector3(aim.x, aim.y - 0.22, aim.z); // 顔と胸が入るように少し下を見る(顔は画面の上のほう)
|
| 238 |
+
camera.position.set(aim.x, aim.y - 0.12, aim.z + 1.9);
|
| 239 |
+
camera.lookAt(look);
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
// ---------------- 毎コマ
|
| 243 |
+
renderer.setAnimationLoop(() => {
|
| 244 |
+
const dt = Math.min(0.05, clock.getDelta()), t = clock.elapsedTime;
|
| 245 |
+
if (vrm) {
|
| 246 |
+
const hips = bone('hips');
|
| 247 |
+
if (baseHipY === null && hips) baseHipY = hips.position.y;
|
| 248 |
+
// 呼吸のゆれ
|
| 249 |
+
let pl = false;
|
| 250 |
+
try { pl = applyPartLock(dt); } catch (e) { say('PartLock の動きで失敗: ' + e); PL.queue = []; PL.cur = null; }
|
| 251 |
+
if (!pl) {
|
| 252 |
+
const chest = bone('chest') || bone('spine');
|
| 253 |
+
if (chest) chest.rotation.x = 0.02 * Math.sin(t * 1.6);
|
| 254 |
+
applyMotion(dt);
|
| 255 |
+
}
|
| 256 |
+
// まばたき
|
| 257 |
+
blinkT -= dt;
|
| 258 |
+
if (blinkT < 0) { blinkV = 1; if (blinkT < -0.12) { blinkT = 2 + Math.random() * 4; blinkV = 0; } }
|
| 259 |
+
// 口
|
| 260 |
+
if (talking) {
|
| 261 |
+
mouthT -= dt;
|
| 262 |
+
if (mouthT < 0) { mouthT = 0.09 + Math.random() * 0.08; const v = ['aa', 'ih', 'ou', 'ee', 'oh', 'aa']; mouthGoal = v[Math.floor(Math.random() * v.length)]; }
|
| 263 |
+
}
|
| 264 |
+
for (const k in mouth) mouth[k] += ((talking && k === mouthGoal ? 0.8 : 0) - mouth[k]) * Math.min(1, dt * 18);
|
| 265 |
+
const em = vrm.expressionManager;
|
| 266 |
+
if (em) {
|
| 267 |
+
for (const n of ['happy', 'angry', 'sad', 'relaxed', 'surprised']) em.setValue(n, faceNow[n] || 0);
|
| 268 |
+
em.setValue('Surprised', faceNow.surprised || 0); // VRoid の見本は「驚き」が大文字の名前
|
| 269 |
+
em.setValue('blink', Math.max(blinkV, faceNow.blink || 0));
|
| 270 |
+
for (const k in mouth) em.setValue(k, Math.max(mouth[k], k === 'oh' ? (faceNow.oh || 0) : 0));
|
| 271 |
+
}
|
| 272 |
+
vrm.update(dt);
|
| 273 |
+
follow(dt);
|
| 274 |
+
}
|
| 275 |
+
renderer.render(scene, camera);
|
| 276 |
+
});
|
| 277 |
+
|
| 278 |
+
window.addEventListener('resize', () => {
|
| 279 |
+
camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix();
|
| 280 |
+
renderer.setSize(window.innerWidth, window.innerHeight);
|
| 281 |
+
});
|
| 282 |
+
|
| 283 |
+
// ---------------- Kotlin から呼ぶ入口
|
| 284 |
+
window.av = {
|
| 285 |
+
face: (w) => face(w),
|
| 286 |
+
talking: (on) => { talking = !!on; },
|
| 287 |
+
motion: (m) => startMotion(m),
|
| 288 |
+
/** PartLock の動き: frames = [{p: 22 関節 × 位置(世界の向き・腰の高さはそのまま), tr:[x,z] 歩いた分}…](4 コマずつ届く) */
|
| 289 |
+
frames: (f) => {
|
| 290 |
+
if (!f || !f.length) return;
|
| 291 |
+
if (motion) { motion = null; const h = bone('head'); if (h) h.rotation.set(0, 0, 0); vrm.scene.rotation.y = 0; restPose(); }
|
| 292 |
+
if (PL.cur === null && PL.queue.length === 0) say('PartLock の動きを再生します');
|
| 293 |
+
for (const x of f) PL.queue.push(x);
|
| 294 |
+
if (PL.queue.length > 60) PL.queue.splice(0, PL.queue.length - 60); // 遅れすぎたら、古いコマを捨てて追いつく
|
| 295 |
+
},
|
| 296 |
+
/** 試験用: いまの骨の向き(記録に出す) */
|
| 297 |
+
dump: () => { const o = {}; for (const n of ORDER) { const b = bone(n); if (b) o[n] = b.quaternion.toArray().map((v) => +v.toFixed(2)); } say('骨: ' + JSON.stringify(o) + ' 腰 ' + JSON.stringify(bone('hips').position.toArray().map((v) => +v.toFixed(2)))); },
|
| 298 |
+
};
|
| 299 |
+
</script>
|
| 300 |
+
</body>
|
| 301 |
+
</html>
|
source/app/src/main/assets/avatar/jsm/loaders/GLTFLoader.js
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
source/app/src/main/assets/avatar/jsm/utils/BufferGeometryUtils.js
ADDED
|
@@ -0,0 +1,1432 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
} from 'three';
|
| 13 |
+
|
| 14 |
+
/** @module BufferGeometryUtils */
|
| 15 |
+
|
| 16 |
+
/**
|
| 17 |
+
* Computes vertex tangents using the MikkTSpace algorithm. MikkTSpace generates the same tangents consistently,
|
| 18 |
+
* and is used in most modelling tools and normal map bakers. Use MikkTSpace for materials with normal maps,
|
| 19 |
+
* because inconsistent tangents may lead to subtle visual issues in the normal map, particularly around mirrored
|
| 20 |
+
* UV seams.
|
| 21 |
+
*
|
| 22 |
+
* In comparison to this method, {@link BufferGeometry#computeTangents} (a custom algorithm) generates tangents that
|
| 23 |
+
* probably will not match the tangents in other software. The custom algorithm is sufficient for general use with a
|
| 24 |
+
* custom material, and may be faster than MikkTSpace.
|
| 25 |
+
*
|
| 26 |
+
* Returns the original BufferGeometry. Indexed geometries will be de-indexed. Requires position, normal, and uv attributes.
|
| 27 |
+
*
|
| 28 |
+
* @param {BufferGeometry} geometry - The geometry to compute tangents for.
|
| 29 |
+
* @param {Object} MikkTSpace - Instance of `examples/jsm/libs/mikktspace.module.js`, or `mikktspace` npm package.
|
| 30 |
+
* Await `MikkTSpace.ready` before use.
|
| 31 |
+
* @param {boolean} [negateSign=true] - Whether to negate the sign component (.w) of each tangent.
|
| 32 |
+
* Required for normal map conventions in some formats, including glTF.
|
| 33 |
+
* @return {BufferGeometry} The updated geometry.
|
| 34 |
+
*/
|
| 35 |
+
function computeMikkTSpaceTangents( geometry, MikkTSpace, negateSign = true ) {
|
| 36 |
+
|
| 37 |
+
if ( ! MikkTSpace || ! MikkTSpace.isReady ) {
|
| 38 |
+
|
| 39 |
+
throw new Error( 'BufferGeometryUtils: Initialized MikkTSpace library required.' );
|
| 40 |
+
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
if ( ! geometry.hasAttribute( 'position' ) || ! geometry.hasAttribute( 'normal' ) || ! geometry.hasAttribute( 'uv' ) ) {
|
| 44 |
+
|
| 45 |
+
throw new Error( 'BufferGeometryUtils: Tangents require "position", "normal", and "uv" attributes.' );
|
| 46 |
+
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
function getAttributeArray( attribute ) {
|
| 50 |
+
|
| 51 |
+
if ( attribute.normalized || attribute.isInterleavedBufferAttribute ) {
|
| 52 |
+
|
| 53 |
+
const dstArray = new Float32Array( attribute.count * attribute.itemSize );
|
| 54 |
+
|
| 55 |
+
for ( let i = 0, j = 0; i < attribute.count; i ++ ) {
|
| 56 |
+
|
| 57 |
+
dstArray[ j ++ ] = attribute.getX( i );
|
| 58 |
+
dstArray[ j ++ ] = attribute.getY( i );
|
| 59 |
+
|
| 60 |
+
if ( attribute.itemSize > 2 ) {
|
| 61 |
+
|
| 62 |
+
dstArray[ j ++ ] = attribute.getZ( i );
|
| 63 |
+
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
return dstArray;
|
| 69 |
+
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
if ( attribute.array instanceof Float32Array ) {
|
| 73 |
+
|
| 74 |
+
return attribute.array;
|
| 75 |
+
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
return new Float32Array( attribute.array );
|
| 79 |
+
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
// MikkTSpace algorithm requires non-indexed input.
|
| 83 |
+
|
| 84 |
+
const _geometry = geometry.index ? geometry.toNonIndexed() : geometry;
|
| 85 |
+
|
| 86 |
+
// Compute vertex tangents.
|
| 87 |
+
|
| 88 |
+
const tangents = MikkTSpace.generateTangents(
|
| 89 |
+
|
| 90 |
+
getAttributeArray( _geometry.attributes.position ),
|
| 91 |
+
getAttributeArray( _geometry.attributes.normal ),
|
| 92 |
+
getAttributeArray( _geometry.attributes.uv )
|
| 93 |
+
|
| 94 |
+
);
|
| 95 |
+
|
| 96 |
+
// Texture coordinate convention of glTF differs from the apparent
|
| 97 |
+
// default of the MikkTSpace library; .w component must be flipped.
|
| 98 |
+
|
| 99 |
+
if ( negateSign ) {
|
| 100 |
+
|
| 101 |
+
for ( let i = 3; i < tangents.length; i += 4 ) {
|
| 102 |
+
|
| 103 |
+
tangents[ i ] *= - 1;
|
| 104 |
+
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
//
|
| 110 |
+
|
| 111 |
+
_geometry.setAttribute( 'tangent', new BufferAttribute( tangents, 4 ) );
|
| 112 |
+
|
| 113 |
+
if ( geometry !== _geometry ) {
|
| 114 |
+
|
| 115 |
+
geometry.copy( _geometry );
|
| 116 |
+
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
return geometry;
|
| 120 |
+
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
/**
|
| 124 |
+
* Merges a set of geometries into a single instance. All geometries must have compatible attributes.
|
| 125 |
+
*
|
| 126 |
+
* @param {Array<BufferGeometry>} geometries - The geometries to merge.
|
| 127 |
+
* @param {boolean} [useGroups=false] - Whether to use groups or not.
|
| 128 |
+
* @return {?BufferGeometry} The merged geometry. Returns `null` if the merge does not succeed.
|
| 129 |
+
*/
|
| 130 |
+
function mergeGeometries( geometries, useGroups = false ) {
|
| 131 |
+
|
| 132 |
+
const isIndexed = geometries[ 0 ].index !== null;
|
| 133 |
+
|
| 134 |
+
const attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );
|
| 135 |
+
const morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
|
| 136 |
+
|
| 137 |
+
const attributes = {};
|
| 138 |
+
const morphAttributes = {};
|
| 139 |
+
|
| 140 |
+
const morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
|
| 141 |
+
|
| 142 |
+
const mergedGeometry = new BufferGeometry();
|
| 143 |
+
|
| 144 |
+
let offset = 0;
|
| 145 |
+
|
| 146 |
+
for ( let i = 0; i < geometries.length; ++ i ) {
|
| 147 |
+
|
| 148 |
+
const geometry = geometries[ i ];
|
| 149 |
+
let attributesCount = 0;
|
| 150 |
+
|
| 151 |
+
// ensure that all geometries are indexed, or none
|
| 152 |
+
|
| 153 |
+
if ( isIndexed !== ( geometry.index !== null ) ) {
|
| 154 |
+
|
| 155 |
+
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.' );
|
| 156 |
+
return null;
|
| 157 |
+
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
// gather attributes, exit early if they're different
|
| 161 |
+
|
| 162 |
+
for ( const name in geometry.attributes ) {
|
| 163 |
+
|
| 164 |
+
if ( ! attributesUsed.has( name ) ) {
|
| 165 |
+
|
| 166 |
+
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure "' + name + '" attribute exists among all geometries, or in none of them.' );
|
| 167 |
+
return null;
|
| 168 |
+
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
if ( attributes[ name ] === undefined ) attributes[ name ] = [];
|
| 172 |
+
|
| 173 |
+
attributes[ name ].push( geometry.attributes[ name ] );
|
| 174 |
+
|
| 175 |
+
attributesCount ++;
|
| 176 |
+
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
// ensure geometries have the same number of attributes
|
| 180 |
+
|
| 181 |
+
if ( attributesCount !== attributesUsed.size ) {
|
| 182 |
+
|
| 183 |
+
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.' );
|
| 184 |
+
return null;
|
| 185 |
+
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
// gather morph attributes, exit early if they're different
|
| 189 |
+
|
| 190 |
+
if ( morphTargetsRelative !== geometry.morphTargetsRelative ) {
|
| 191 |
+
|
| 192 |
+
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' );
|
| 193 |
+
return null;
|
| 194 |
+
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
for ( const name in geometry.morphAttributes ) {
|
| 198 |
+
|
| 199 |
+
if ( ! morphAttributesUsed.has( name ) ) {
|
| 200 |
+
|
| 201 |
+
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' );
|
| 202 |
+
return null;
|
| 203 |
+
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
|
| 207 |
+
|
| 208 |
+
morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
|
| 209 |
+
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
if ( useGroups ) {
|
| 213 |
+
|
| 214 |
+
let count;
|
| 215 |
+
|
| 216 |
+
if ( isIndexed ) {
|
| 217 |
+
|
| 218 |
+
count = geometry.index.count;
|
| 219 |
+
|
| 220 |
+
} else if ( geometry.attributes.position !== undefined ) {
|
| 221 |
+
|
| 222 |
+
count = geometry.attributes.position.count;
|
| 223 |
+
|
| 224 |
+
} else {
|
| 225 |
+
|
| 226 |
+
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' );
|
| 227 |
+
return null;
|
| 228 |
+
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
mergedGeometry.addGroup( offset, count, i );
|
| 232 |
+
|
| 233 |
+
offset += count;
|
| 234 |
+
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
// merge indices
|
| 240 |
+
|
| 241 |
+
if ( isIndexed ) {
|
| 242 |
+
|
| 243 |
+
let indexOffset = 0;
|
| 244 |
+
const mergedIndex = [];
|
| 245 |
+
|
| 246 |
+
for ( let i = 0; i < geometries.length; ++ i ) {
|
| 247 |
+
|
| 248 |
+
const index = geometries[ i ].index;
|
| 249 |
+
|
| 250 |
+
for ( let j = 0; j < index.count; ++ j ) {
|
| 251 |
+
|
| 252 |
+
mergedIndex.push( index.getX( j ) + indexOffset );
|
| 253 |
+
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
indexOffset += geometries[ i ].attributes.position.count;
|
| 257 |
+
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
mergedGeometry.setIndex( mergedIndex );
|
| 261 |
+
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
// merge attributes
|
| 265 |
+
|
| 266 |
+
for ( const name in attributes ) {
|
| 267 |
+
|
| 268 |
+
const mergedAttribute = mergeAttributes( attributes[ name ] );
|
| 269 |
+
|
| 270 |
+
if ( ! mergedAttribute ) {
|
| 271 |
+
|
| 272 |
+
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the ' + name + ' attribute.' );
|
| 273 |
+
return null;
|
| 274 |
+
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
mergedGeometry.setAttribute( name, mergedAttribute );
|
| 278 |
+
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
// merge morph attributes
|
| 282 |
+
|
| 283 |
+
for ( const name in morphAttributes ) {
|
| 284 |
+
|
| 285 |
+
const numMorphTargets = morphAttributes[ name ][ 0 ].length;
|
| 286 |
+
|
| 287 |
+
if ( numMorphTargets === 0 ) break;
|
| 288 |
+
|
| 289 |
+
mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
|
| 290 |
+
mergedGeometry.morphAttributes[ name ] = [];
|
| 291 |
+
|
| 292 |
+
for ( let i = 0; i < numMorphTargets; ++ i ) {
|
| 293 |
+
|
| 294 |
+
const morphAttributesToMerge = [];
|
| 295 |
+
|
| 296 |
+
for ( let j = 0; j < morphAttributes[ name ].length; ++ j ) {
|
| 297 |
+
|
| 298 |
+
morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
|
| 299 |
+
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
const mergedMorphAttribute = mergeAttributes( morphAttributesToMerge );
|
| 303 |
+
|
| 304 |
+
if ( ! mergedMorphAttribute ) {
|
| 305 |
+
|
| 306 |
+
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the ' + name + ' morphAttribute.' );
|
| 307 |
+
return null;
|
| 308 |
+
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
|
| 312 |
+
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
return mergedGeometry;
|
| 318 |
+
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
/**
|
| 322 |
+
* Merges a set of attributes into a single instance. All attributes must have compatible properties and types.
|
| 323 |
+
* Instances of {@link InterleavedBufferAttribute} are not supported.
|
| 324 |
+
*
|
| 325 |
+
* @param {Array<BufferAttribute>} attributes - The attributes to merge.
|
| 326 |
+
* @return {?BufferAttribute} The merged attribute. Returns `null` if the merge does not succeed.
|
| 327 |
+
*/
|
| 328 |
+
function mergeAttributes( attributes ) {
|
| 329 |
+
|
| 330 |
+
let TypedArray;
|
| 331 |
+
let itemSize;
|
| 332 |
+
let normalized;
|
| 333 |
+
let gpuType = - 1;
|
| 334 |
+
let arrayLength = 0;
|
| 335 |
+
|
| 336 |
+
for ( let i = 0; i < attributes.length; ++ i ) {
|
| 337 |
+
|
| 338 |
+
const attribute = attributes[ i ];
|
| 339 |
+
|
| 340 |
+
if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
|
| 341 |
+
if ( TypedArray !== attribute.array.constructor ) {
|
| 342 |
+
|
| 343 |
+
console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.' );
|
| 344 |
+
return null;
|
| 345 |
+
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
if ( itemSize === undefined ) itemSize = attribute.itemSize;
|
| 349 |
+
if ( itemSize !== attribute.itemSize ) {
|
| 350 |
+
|
| 351 |
+
console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.' );
|
| 352 |
+
return null;
|
| 353 |
+
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
if ( normalized === undefined ) normalized = attribute.normalized;
|
| 357 |
+
if ( normalized !== attribute.normalized ) {
|
| 358 |
+
|
| 359 |
+
console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.' );
|
| 360 |
+
return null;
|
| 361 |
+
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
if ( gpuType === - 1 ) gpuType = attribute.gpuType;
|
| 365 |
+
if ( gpuType !== attribute.gpuType ) {
|
| 366 |
+
|
| 367 |
+
console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes.' );
|
| 368 |
+
return null;
|
| 369 |
+
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
arrayLength += attribute.count * itemSize;
|
| 373 |
+
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
const array = new TypedArray( arrayLength );
|
| 377 |
+
const result = new BufferAttribute( array, itemSize, normalized );
|
| 378 |
+
let offset = 0;
|
| 379 |
+
|
| 380 |
+
for ( let i = 0; i < attributes.length; ++ i ) {
|
| 381 |
+
|
| 382 |
+
const attribute = attributes[ i ];
|
| 383 |
+
if ( attribute.isInterleavedBufferAttribute ) {
|
| 384 |
+
|
| 385 |
+
const tupleOffset = offset / itemSize;
|
| 386 |
+
for ( let j = 0, l = attribute.count; j < l; j ++ ) {
|
| 387 |
+
|
| 388 |
+
for ( let c = 0; c < itemSize; c ++ ) {
|
| 389 |
+
|
| 390 |
+
const value = attribute.getComponent( j, c );
|
| 391 |
+
result.setComponent( j + tupleOffset, c, value );
|
| 392 |
+
|
| 393 |
+
}
|
| 394 |
+
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
} else {
|
| 398 |
+
|
| 399 |
+
array.set( attribute.array, offset );
|
| 400 |
+
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
offset += attribute.count * itemSize;
|
| 404 |
+
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
if ( gpuType !== undefined ) {
|
| 408 |
+
|
| 409 |
+
result.gpuType = gpuType;
|
| 410 |
+
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
return result;
|
| 414 |
+
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
/**
|
| 418 |
+
* Performs a deep clone of the given buffer attribute.
|
| 419 |
+
*
|
| 420 |
+
* @param {BufferAttribute} attribute - The attribute to clone.
|
| 421 |
+
* @return {BufferAttribute} The cloned attribute.
|
| 422 |
+
*/
|
| 423 |
+
function deepCloneAttribute( attribute ) {
|
| 424 |
+
|
| 425 |
+
if ( attribute.isInstancedInterleavedBufferAttribute || attribute.isInterleavedBufferAttribute ) {
|
| 426 |
+
|
| 427 |
+
return deinterleaveAttribute( attribute );
|
| 428 |
+
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
if ( attribute.isInstancedBufferAttribute ) {
|
| 432 |
+
|
| 433 |
+
return new InstancedBufferAttribute().copy( attribute );
|
| 434 |
+
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
return new BufferAttribute().copy( attribute );
|
| 438 |
+
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
/**
|
| 442 |
+
* Interleaves a set of attributes and returns a new array of corresponding attributes that share a
|
| 443 |
+
* single {@link InterleavedBuffer} instance. All attributes must have compatible types.
|
| 444 |
+
*
|
| 445 |
+
* @param {Array<BufferAttribute>} attributes - The attributes to interleave.
|
| 446 |
+
* @return {Array<InterleavedBufferAttribute>} An array of interleaved attributes. If interleave does not succeed, the method returns `null`.
|
| 447 |
+
*/
|
| 448 |
+
function interleaveAttributes( attributes ) {
|
| 449 |
+
|
| 450 |
+
// Interleaves the provided attributes into an InterleavedBuffer and returns
|
| 451 |
+
// a set of InterleavedBufferAttributes for each attribute
|
| 452 |
+
let TypedArray;
|
| 453 |
+
let arrayLength = 0;
|
| 454 |
+
let stride = 0;
|
| 455 |
+
|
| 456 |
+
// calculate the length and type of the interleavedBuffer
|
| 457 |
+
for ( let i = 0, l = attributes.length; i < l; ++ i ) {
|
| 458 |
+
|
| 459 |
+
const attribute = attributes[ i ];
|
| 460 |
+
|
| 461 |
+
if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
|
| 462 |
+
if ( TypedArray !== attribute.array.constructor ) {
|
| 463 |
+
|
| 464 |
+
console.error( 'AttributeBuffers of different types cannot be interleaved' );
|
| 465 |
+
return null;
|
| 466 |
+
|
| 467 |
+
}
|
| 468 |
+
|
| 469 |
+
arrayLength += attribute.array.length;
|
| 470 |
+
stride += attribute.itemSize;
|
| 471 |
+
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
+
// Create the set of buffer attributes
|
| 475 |
+
const interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride );
|
| 476 |
+
let offset = 0;
|
| 477 |
+
const res = [];
|
| 478 |
+
const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
|
| 479 |
+
const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
|
| 480 |
+
|
| 481 |
+
for ( let j = 0, l = attributes.length; j < l; j ++ ) {
|
| 482 |
+
|
| 483 |
+
const attribute = attributes[ j ];
|
| 484 |
+
const itemSize = attribute.itemSize;
|
| 485 |
+
const count = attribute.count;
|
| 486 |
+
const iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
|
| 487 |
+
res.push( iba );
|
| 488 |
+
|
| 489 |
+
offset += itemSize;
|
| 490 |
+
|
| 491 |
+
// Move the data for each attribute into the new interleavedBuffer
|
| 492 |
+
// at the appropriate offset
|
| 493 |
+
for ( let c = 0; c < count; c ++ ) {
|
| 494 |
+
|
| 495 |
+
for ( let k = 0; k < itemSize; k ++ ) {
|
| 496 |
+
|
| 497 |
+
iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
|
| 498 |
+
|
| 499 |
+
}
|
| 500 |
+
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
+
return res;
|
| 506 |
+
|
| 507 |
+
}
|
| 508 |
+
|
| 509 |
+
/**
|
| 510 |
+
* Returns a new, non-interleaved version of the given attribute.
|
| 511 |
+
*
|
| 512 |
+
* @param {InterleavedBufferAttribute} attribute - The interleaved attribute.
|
| 513 |
+
* @return {BufferAttribute} The non-interleaved attribute.
|
| 514 |
+
*/
|
| 515 |
+
function deinterleaveAttribute( attribute ) {
|
| 516 |
+
|
| 517 |
+
const cons = attribute.data.array.constructor;
|
| 518 |
+
const count = attribute.count;
|
| 519 |
+
const itemSize = attribute.itemSize;
|
| 520 |
+
const normalized = attribute.normalized;
|
| 521 |
+
|
| 522 |
+
const array = new cons( count * itemSize );
|
| 523 |
+
let newAttribute;
|
| 524 |
+
if ( attribute.isInstancedInterleavedBufferAttribute ) {
|
| 525 |
+
|
| 526 |
+
newAttribute = new InstancedBufferAttribute( array, itemSize, normalized, attribute.meshPerAttribute );
|
| 527 |
+
|
| 528 |
+
} else {
|
| 529 |
+
|
| 530 |
+
newAttribute = new BufferAttribute( array, itemSize, normalized );
|
| 531 |
+
|
| 532 |
+
}
|
| 533 |
+
|
| 534 |
+
for ( let i = 0; i < count; i ++ ) {
|
| 535 |
+
|
| 536 |
+
newAttribute.setX( i, attribute.getX( i ) );
|
| 537 |
+
|
| 538 |
+
if ( itemSize >= 2 ) {
|
| 539 |
+
|
| 540 |
+
newAttribute.setY( i, attribute.getY( i ) );
|
| 541 |
+
|
| 542 |
+
}
|
| 543 |
+
|
| 544 |
+
if ( itemSize >= 3 ) {
|
| 545 |
+
|
| 546 |
+
newAttribute.setZ( i, attribute.getZ( i ) );
|
| 547 |
+
|
| 548 |
+
}
|
| 549 |
+
|
| 550 |
+
if ( itemSize >= 4 ) {
|
| 551 |
+
|
| 552 |
+
newAttribute.setW( i, attribute.getW( i ) );
|
| 553 |
+
|
| 554 |
+
}
|
| 555 |
+
|
| 556 |
+
}
|
| 557 |
+
|
| 558 |
+
return newAttribute;
|
| 559 |
+
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
/**
|
| 563 |
+
* Deinterleaves all attributes on the given geometry.
|
| 564 |
+
*
|
| 565 |
+
* @param {BufferGeometry} geometry - The geometry to deinterleave.
|
| 566 |
+
*/
|
| 567 |
+
function deinterleaveGeometry( geometry ) {
|
| 568 |
+
|
| 569 |
+
const attributes = geometry.attributes;
|
| 570 |
+
const morphTargets = geometry.morphTargets;
|
| 571 |
+
const attrMap = new Map();
|
| 572 |
+
|
| 573 |
+
for ( const key in attributes ) {
|
| 574 |
+
|
| 575 |
+
const attr = attributes[ key ];
|
| 576 |
+
if ( attr.isInterleavedBufferAttribute ) {
|
| 577 |
+
|
| 578 |
+
if ( ! attrMap.has( attr ) ) {
|
| 579 |
+
|
| 580 |
+
attrMap.set( attr, deinterleaveAttribute( attr ) );
|
| 581 |
+
|
| 582 |
+
}
|
| 583 |
+
|
| 584 |
+
attributes[ key ] = attrMap.get( attr );
|
| 585 |
+
|
| 586 |
+
}
|
| 587 |
+
|
| 588 |
+
}
|
| 589 |
+
|
| 590 |
+
for ( const key in morphTargets ) {
|
| 591 |
+
|
| 592 |
+
const attr = morphTargets[ key ];
|
| 593 |
+
if ( attr.isInterleavedBufferAttribute ) {
|
| 594 |
+
|
| 595 |
+
if ( ! attrMap.has( attr ) ) {
|
| 596 |
+
|
| 597 |
+
attrMap.set( attr, deinterleaveAttribute( attr ) );
|
| 598 |
+
|
| 599 |
+
}
|
| 600 |
+
|
| 601 |
+
morphTargets[ key ] = attrMap.get( attr );
|
| 602 |
+
|
| 603 |
+
}
|
| 604 |
+
|
| 605 |
+
}
|
| 606 |
+
|
| 607 |
+
}
|
| 608 |
+
|
| 609 |
+
/**
|
| 610 |
+
* Returns the amount of bytes used by all attributes to represent the geometry.
|
| 611 |
+
*
|
| 612 |
+
* @param {BufferGeometry} geometry - The geometry.
|
| 613 |
+
* @return {number} The estimate bytes used.
|
| 614 |
+
*/
|
| 615 |
+
function estimateBytesUsed( geometry ) {
|
| 616 |
+
|
| 617 |
+
// Return the estimated memory used by this geometry in bytes
|
| 618 |
+
// Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
|
| 619 |
+
// for InterleavedBufferAttributes.
|
| 620 |
+
let mem = 0;
|
| 621 |
+
for ( const name in geometry.attributes ) {
|
| 622 |
+
|
| 623 |
+
const attr = geometry.getAttribute( name );
|
| 624 |
+
mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
|
| 625 |
+
|
| 626 |
+
}
|
| 627 |
+
|
| 628 |
+
const indices = geometry.getIndex();
|
| 629 |
+
mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
|
| 630 |
+
return mem;
|
| 631 |
+
|
| 632 |
+
}
|
| 633 |
+
|
| 634 |
+
/**
|
| 635 |
+
* Returns a new geometry with vertices for which all similar vertex attributes (within tolerance) are merged.
|
| 636 |
+
*
|
| 637 |
+
* @param {BufferGeometry} geometry - The geometry to merge vertices for.
|
| 638 |
+
* @param {number} [tolerance=1e-4] - The tolerance value.
|
| 639 |
+
* @return {BufferGeometry} - The new geometry with merged vertices.
|
| 640 |
+
*/
|
| 641 |
+
function mergeVertices( geometry, tolerance = 1e-4 ) {
|
| 642 |
+
|
| 643 |
+
tolerance = Math.max( tolerance, Number.EPSILON );
|
| 644 |
+
|
| 645 |
+
// Generate an index buffer if the geometry doesn't have one, or optimize it
|
| 646 |
+
// if it's already available.
|
| 647 |
+
const hashToIndex = {};
|
| 648 |
+
const indices = geometry.getIndex();
|
| 649 |
+
const positions = geometry.getAttribute( 'position' );
|
| 650 |
+
const vertexCount = indices ? indices.count : positions.count;
|
| 651 |
+
|
| 652 |
+
// next value for triangle indices
|
| 653 |
+
let nextIndex = 0;
|
| 654 |
+
|
| 655 |
+
// attributes and new attribute arrays
|
| 656 |
+
const attributeNames = Object.keys( geometry.attributes );
|
| 657 |
+
const tmpAttributes = {};
|
| 658 |
+
const tmpMorphAttributes = {};
|
| 659 |
+
const newIndices = [];
|
| 660 |
+
const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
|
| 661 |
+
const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
|
| 662 |
+
|
| 663 |
+
// Initialize the arrays, allocating space conservatively. Extra
|
| 664 |
+
// space will be trimmed in the last step.
|
| 665 |
+
for ( let i = 0, l = attributeNames.length; i < l; i ++ ) {
|
| 666 |
+
|
| 667 |
+
const name = attributeNames[ i ];
|
| 668 |
+
const attr = geometry.attributes[ name ];
|
| 669 |
+
|
| 670 |
+
tmpAttributes[ name ] = new attr.constructor(
|
| 671 |
+
new attr.array.constructor( attr.count * attr.itemSize ),
|
| 672 |
+
attr.itemSize,
|
| 673 |
+
attr.normalized
|
| 674 |
+
);
|
| 675 |
+
|
| 676 |
+
const morphAttributes = geometry.morphAttributes[ name ];
|
| 677 |
+
if ( morphAttributes ) {
|
| 678 |
+
|
| 679 |
+
if ( ! tmpMorphAttributes[ name ] ) tmpMorphAttributes[ name ] = [];
|
| 680 |
+
morphAttributes.forEach( ( morphAttr, i ) => {
|
| 681 |
+
|
| 682 |
+
const array = new morphAttr.array.constructor( morphAttr.count * morphAttr.itemSize );
|
| 683 |
+
tmpMorphAttributes[ name ][ i ] = new morphAttr.constructor( array, morphAttr.itemSize, morphAttr.normalized );
|
| 684 |
+
|
| 685 |
+
} );
|
| 686 |
+
|
| 687 |
+
}
|
| 688 |
+
|
| 689 |
+
}
|
| 690 |
+
|
| 691 |
+
// convert the error tolerance to an amount of decimal places to truncate to
|
| 692 |
+
const halfTolerance = tolerance * 0.5;
|
| 693 |
+
const exponent = Math.log10( 1 / tolerance );
|
| 694 |
+
const hashMultiplier = Math.pow( 10, exponent );
|
| 695 |
+
const hashAdditive = halfTolerance * hashMultiplier;
|
| 696 |
+
for ( let i = 0; i < vertexCount; i ++ ) {
|
| 697 |
+
|
| 698 |
+
const index = indices ? indices.getX( i ) : i;
|
| 699 |
+
|
| 700 |
+
// Generate a hash for the vertex attributes at the current index 'i'
|
| 701 |
+
let hash = '';
|
| 702 |
+
for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
|
| 703 |
+
|
| 704 |
+
const name = attributeNames[ j ];
|
| 705 |
+
const attribute = geometry.getAttribute( name );
|
| 706 |
+
const itemSize = attribute.itemSize;
|
| 707 |
+
|
| 708 |
+
for ( let k = 0; k < itemSize; k ++ ) {
|
| 709 |
+
|
| 710 |
+
// double tilde truncates the decimal value
|
| 711 |
+
hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * hashMultiplier + hashAdditive ) },`;
|
| 712 |
+
|
| 713 |
+
}
|
| 714 |
+
|
| 715 |
+
}
|
| 716 |
+
|
| 717 |
+
// Add another reference to the vertex if it's already
|
| 718 |
+
// used by another index
|
| 719 |
+
if ( hash in hashToIndex ) {
|
| 720 |
+
|
| 721 |
+
newIndices.push( hashToIndex[ hash ] );
|
| 722 |
+
|
| 723 |
+
} else {
|
| 724 |
+
|
| 725 |
+
// copy data to the new index in the temporary attributes
|
| 726 |
+
for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
|
| 727 |
+
|
| 728 |
+
const name = attributeNames[ j ];
|
| 729 |
+
const attribute = geometry.getAttribute( name );
|
| 730 |
+
const morphAttributes = geometry.morphAttributes[ name ];
|
| 731 |
+
const itemSize = attribute.itemSize;
|
| 732 |
+
const newArray = tmpAttributes[ name ];
|
| 733 |
+
const newMorphArrays = tmpMorphAttributes[ name ];
|
| 734 |
+
|
| 735 |
+
for ( let k = 0; k < itemSize; k ++ ) {
|
| 736 |
+
|
| 737 |
+
const getterFunc = getters[ k ];
|
| 738 |
+
const setterFunc = setters[ k ];
|
| 739 |
+
newArray[ setterFunc ]( nextIndex, attribute[ getterFunc ]( index ) );
|
| 740 |
+
|
| 741 |
+
if ( morphAttributes ) {
|
| 742 |
+
|
| 743 |
+
for ( let m = 0, ml = morphAttributes.length; m < ml; m ++ ) {
|
| 744 |
+
|
| 745 |
+
newMorphArrays[ m ][ setterFunc ]( nextIndex, morphAttributes[ m ][ getterFunc ]( index ) );
|
| 746 |
+
|
| 747 |
+
}
|
| 748 |
+
|
| 749 |
+
}
|
| 750 |
+
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
}
|
| 754 |
+
|
| 755 |
+
hashToIndex[ hash ] = nextIndex;
|
| 756 |
+
newIndices.push( nextIndex );
|
| 757 |
+
nextIndex ++;
|
| 758 |
+
|
| 759 |
+
}
|
| 760 |
+
|
| 761 |
+
}
|
| 762 |
+
|
| 763 |
+
// generate result BufferGeometry
|
| 764 |
+
const result = geometry.clone();
|
| 765 |
+
for ( const name in geometry.attributes ) {
|
| 766 |
+
|
| 767 |
+
const tmpAttribute = tmpAttributes[ name ];
|
| 768 |
+
|
| 769 |
+
result.setAttribute( name, new tmpAttribute.constructor(
|
| 770 |
+
tmpAttribute.array.slice( 0, nextIndex * tmpAttribute.itemSize ),
|
| 771 |
+
tmpAttribute.itemSize,
|
| 772 |
+
tmpAttribute.normalized,
|
| 773 |
+
) );
|
| 774 |
+
|
| 775 |
+
if ( ! ( name in tmpMorphAttributes ) ) continue;
|
| 776 |
+
|
| 777 |
+
for ( let j = 0; j < tmpMorphAttributes[ name ].length; j ++ ) {
|
| 778 |
+
|
| 779 |
+
const tmpMorphAttribute = tmpMorphAttributes[ name ][ j ];
|
| 780 |
+
|
| 781 |
+
result.morphAttributes[ name ][ j ] = new tmpMorphAttribute.constructor(
|
| 782 |
+
tmpMorphAttribute.array.slice( 0, nextIndex * tmpMorphAttribute.itemSize ),
|
| 783 |
+
tmpMorphAttribute.itemSize,
|
| 784 |
+
tmpMorphAttribute.normalized,
|
| 785 |
+
);
|
| 786 |
+
|
| 787 |
+
}
|
| 788 |
+
|
| 789 |
+
}
|
| 790 |
+
|
| 791 |
+
// indices
|
| 792 |
+
|
| 793 |
+
result.setIndex( newIndices );
|
| 794 |
+
|
| 795 |
+
return result;
|
| 796 |
+
|
| 797 |
+
}
|
| 798 |
+
|
| 799 |
+
/**
|
| 800 |
+
* Returns a new indexed geometry based on `TrianglesDrawMode` draw mode.
|
| 801 |
+
* This mode corresponds to the `gl.TRIANGLES` primitive in WebGL.
|
| 802 |
+
*
|
| 803 |
+
* @param {BufferGeometry} geometry - The geometry to convert.
|
| 804 |
+
* @param {number} drawMode - The current draw mode.
|
| 805 |
+
* @return {BufferGeometry} The new geometry using `TrianglesDrawMode`.
|
| 806 |
+
*/
|
| 807 |
+
function toTrianglesDrawMode( geometry, drawMode ) {
|
| 808 |
+
|
| 809 |
+
if ( drawMode === TrianglesDrawMode ) {
|
| 810 |
+
|
| 811 |
+
console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
|
| 812 |
+
return geometry;
|
| 813 |
+
|
| 814 |
+
}
|
| 815 |
+
|
| 816 |
+
if ( drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode ) {
|
| 817 |
+
|
| 818 |
+
let index = geometry.getIndex();
|
| 819 |
+
|
| 820 |
+
// generate index if not present
|
| 821 |
+
|
| 822 |
+
if ( index === null ) {
|
| 823 |
+
|
| 824 |
+
const indices = [];
|
| 825 |
+
|
| 826 |
+
const position = geometry.getAttribute( 'position' );
|
| 827 |
+
|
| 828 |
+
if ( position !== undefined ) {
|
| 829 |
+
|
| 830 |
+
for ( let i = 0; i < position.count; i ++ ) {
|
| 831 |
+
|
| 832 |
+
indices.push( i );
|
| 833 |
+
|
| 834 |
+
}
|
| 835 |
+
|
| 836 |
+
geometry.setIndex( indices );
|
| 837 |
+
index = geometry.getIndex();
|
| 838 |
+
|
| 839 |
+
} else {
|
| 840 |
+
|
| 841 |
+
console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
|
| 842 |
+
return geometry;
|
| 843 |
+
|
| 844 |
+
}
|
| 845 |
+
|
| 846 |
+
}
|
| 847 |
+
|
| 848 |
+
//
|
| 849 |
+
|
| 850 |
+
const numberOfTriangles = index.count - 2;
|
| 851 |
+
const newIndices = [];
|
| 852 |
+
|
| 853 |
+
if ( drawMode === TriangleFanDrawMode ) {
|
| 854 |
+
|
| 855 |
+
// gl.TRIANGLE_FAN
|
| 856 |
+
|
| 857 |
+
for ( let i = 1; i <= numberOfTriangles; i ++ ) {
|
| 858 |
+
|
| 859 |
+
newIndices.push( index.getX( 0 ) );
|
| 860 |
+
newIndices.push( index.getX( i ) );
|
| 861 |
+
newIndices.push( index.getX( i + 1 ) );
|
| 862 |
+
|
| 863 |
+
}
|
| 864 |
+
|
| 865 |
+
} else {
|
| 866 |
+
|
| 867 |
+
// gl.TRIANGLE_STRIP
|
| 868 |
+
|
| 869 |
+
for ( let i = 0; i < numberOfTriangles; i ++ ) {
|
| 870 |
+
|
| 871 |
+
if ( i % 2 === 0 ) {
|
| 872 |
+
|
| 873 |
+
newIndices.push( index.getX( i ) );
|
| 874 |
+
newIndices.push( index.getX( i + 1 ) );
|
| 875 |
+
newIndices.push( index.getX( i + 2 ) );
|
| 876 |
+
|
| 877 |
+
} else {
|
| 878 |
+
|
| 879 |
+
newIndices.push( index.getX( i + 2 ) );
|
| 880 |
+
newIndices.push( index.getX( i + 1 ) );
|
| 881 |
+
newIndices.push( index.getX( i ) );
|
| 882 |
+
|
| 883 |
+
}
|
| 884 |
+
|
| 885 |
+
}
|
| 886 |
+
|
| 887 |
+
}
|
| 888 |
+
|
| 889 |
+
if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
|
| 890 |
+
|
| 891 |
+
console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
|
| 892 |
+
|
| 893 |
+
}
|
| 894 |
+
|
| 895 |
+
// build final geometry
|
| 896 |
+
|
| 897 |
+
const newGeometry = geometry.clone();
|
| 898 |
+
newGeometry.setIndex( newIndices );
|
| 899 |
+
newGeometry.clearGroups();
|
| 900 |
+
|
| 901 |
+
return newGeometry;
|
| 902 |
+
|
| 903 |
+
} else {
|
| 904 |
+
|
| 905 |
+
console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
|
| 906 |
+
return geometry;
|
| 907 |
+
|
| 908 |
+
}
|
| 909 |
+
|
| 910 |
+
}
|
| 911 |
+
|
| 912 |
+
/**
|
| 913 |
+
* Calculates the morphed attributes of a morphed/skinned BufferGeometry.
|
| 914 |
+
*
|
| 915 |
+
* Helpful for Raytracing or Decals (i.e. a `DecalGeometry` applied to a morphed Object with a `BufferGeometry`
|
| 916 |
+
* will use the original `BufferGeometry`, not the morphed/skinned one, generating an incorrect result.
|
| 917 |
+
* Using this function to create a shadow `Object3`D the `DecalGeometry` can be correctly generated).
|
| 918 |
+
*
|
| 919 |
+
* @param {Mesh|Line|Points} object - The 3D object to compute morph attributes for.
|
| 920 |
+
* @return {Object} An object with original position/normal attributes and morphed ones.
|
| 921 |
+
*/
|
| 922 |
+
function computeMorphedAttributes( object ) {
|
| 923 |
+
|
| 924 |
+
const _vA = new Vector3();
|
| 925 |
+
const _vB = new Vector3();
|
| 926 |
+
const _vC = new Vector3();
|
| 927 |
+
|
| 928 |
+
const _tempA = new Vector3();
|
| 929 |
+
const _tempB = new Vector3();
|
| 930 |
+
const _tempC = new Vector3();
|
| 931 |
+
|
| 932 |
+
const _morphA = new Vector3();
|
| 933 |
+
const _morphB = new Vector3();
|
| 934 |
+
const _morphC = new Vector3();
|
| 935 |
+
|
| 936 |
+
function _calculateMorphedAttributeData(
|
| 937 |
+
object,
|
| 938 |
+
attribute,
|
| 939 |
+
morphAttribute,
|
| 940 |
+
morphTargetsRelative,
|
| 941 |
+
a,
|
| 942 |
+
b,
|
| 943 |
+
c,
|
| 944 |
+
modifiedAttributeArray
|
| 945 |
+
) {
|
| 946 |
+
|
| 947 |
+
_vA.fromBufferAttribute( attribute, a );
|
| 948 |
+
_vB.fromBufferAttribute( attribute, b );
|
| 949 |
+
_vC.fromBufferAttribute( attribute, c );
|
| 950 |
+
|
| 951 |
+
const morphInfluences = object.morphTargetInfluences;
|
| 952 |
+
|
| 953 |
+
if ( morphAttribute && morphInfluences ) {
|
| 954 |
+
|
| 955 |
+
_morphA.set( 0, 0, 0 );
|
| 956 |
+
_morphB.set( 0, 0, 0 );
|
| 957 |
+
_morphC.set( 0, 0, 0 );
|
| 958 |
+
|
| 959 |
+
for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
|
| 960 |
+
|
| 961 |
+
const influence = morphInfluences[ i ];
|
| 962 |
+
const morph = morphAttribute[ i ];
|
| 963 |
+
|
| 964 |
+
if ( influence === 0 ) continue;
|
| 965 |
+
|
| 966 |
+
_tempA.fromBufferAttribute( morph, a );
|
| 967 |
+
_tempB.fromBufferAttribute( morph, b );
|
| 968 |
+
_tempC.fromBufferAttribute( morph, c );
|
| 969 |
+
|
| 970 |
+
if ( morphTargetsRelative ) {
|
| 971 |
+
|
| 972 |
+
_morphA.addScaledVector( _tempA, influence );
|
| 973 |
+
_morphB.addScaledVector( _tempB, influence );
|
| 974 |
+
_morphC.addScaledVector( _tempC, influence );
|
| 975 |
+
|
| 976 |
+
} else {
|
| 977 |
+
|
| 978 |
+
_morphA.addScaledVector( _tempA.sub( _vA ), influence );
|
| 979 |
+
_morphB.addScaledVector( _tempB.sub( _vB ), influence );
|
| 980 |
+
_morphC.addScaledVector( _tempC.sub( _vC ), influence );
|
| 981 |
+
|
| 982 |
+
}
|
| 983 |
+
|
| 984 |
+
}
|
| 985 |
+
|
| 986 |
+
_vA.add( _morphA );
|
| 987 |
+
_vB.add( _morphB );
|
| 988 |
+
_vC.add( _morphC );
|
| 989 |
+
|
| 990 |
+
}
|
| 991 |
+
|
| 992 |
+
if ( object.isSkinnedMesh ) {
|
| 993 |
+
|
| 994 |
+
object.applyBoneTransform( a, _vA );
|
| 995 |
+
object.applyBoneTransform( b, _vB );
|
| 996 |
+
object.applyBoneTransform( c, _vC );
|
| 997 |
+
|
| 998 |
+
}
|
| 999 |
+
|
| 1000 |
+
modifiedAttributeArray[ a * 3 + 0 ] = _vA.x;
|
| 1001 |
+
modifiedAttributeArray[ a * 3 + 1 ] = _vA.y;
|
| 1002 |
+
modifiedAttributeArray[ a * 3 + 2 ] = _vA.z;
|
| 1003 |
+
modifiedAttributeArray[ b * 3 + 0 ] = _vB.x;
|
| 1004 |
+
modifiedAttributeArray[ b * 3 + 1 ] = _vB.y;
|
| 1005 |
+
modifiedAttributeArray[ b * 3 + 2 ] = _vB.z;
|
| 1006 |
+
modifiedAttributeArray[ c * 3 + 0 ] = _vC.x;
|
| 1007 |
+
modifiedAttributeArray[ c * 3 + 1 ] = _vC.y;
|
| 1008 |
+
modifiedAttributeArray[ c * 3 + 2 ] = _vC.z;
|
| 1009 |
+
|
| 1010 |
+
}
|
| 1011 |
+
|
| 1012 |
+
const geometry = object.geometry;
|
| 1013 |
+
const material = object.material;
|
| 1014 |
+
|
| 1015 |
+
let a, b, c;
|
| 1016 |
+
const index = geometry.index;
|
| 1017 |
+
const positionAttribute = geometry.attributes.position;
|
| 1018 |
+
const morphPosition = geometry.morphAttributes.position;
|
| 1019 |
+
const morphTargetsRelative = geometry.morphTargetsRelative;
|
| 1020 |
+
const normalAttribute = geometry.attributes.normal;
|
| 1021 |
+
const morphNormal = geometry.morphAttributes.position;
|
| 1022 |
+
|
| 1023 |
+
const groups = geometry.groups;
|
| 1024 |
+
const drawRange = geometry.drawRange;
|
| 1025 |
+
let i, j, il, jl;
|
| 1026 |
+
let group;
|
| 1027 |
+
let start, end;
|
| 1028 |
+
|
| 1029 |
+
const modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize );
|
| 1030 |
+
const modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );
|
| 1031 |
+
|
| 1032 |
+
if ( index !== null ) {
|
| 1033 |
+
|
| 1034 |
+
// indexed buffer geometry
|
| 1035 |
+
|
| 1036 |
+
if ( Array.isArray( material ) ) {
|
| 1037 |
+
|
| 1038 |
+
for ( i = 0, il = groups.length; i < il; i ++ ) {
|
| 1039 |
+
|
| 1040 |
+
group = groups[ i ];
|
| 1041 |
+
|
| 1042 |
+
start = Math.max( group.start, drawRange.start );
|
| 1043 |
+
end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
|
| 1044 |
+
|
| 1045 |
+
for ( j = start, jl = end; j < jl; j += 3 ) {
|
| 1046 |
+
|
| 1047 |
+
a = index.getX( j );
|
| 1048 |
+
b = index.getX( j + 1 );
|
| 1049 |
+
c = index.getX( j + 2 );
|
| 1050 |
+
|
| 1051 |
+
_calculateMorphedAttributeData(
|
| 1052 |
+
object,
|
| 1053 |
+
positionAttribute,
|
| 1054 |
+
morphPosition,
|
| 1055 |
+
morphTargetsRelative,
|
| 1056 |
+
a, b, c,
|
| 1057 |
+
modifiedPosition
|
| 1058 |
+
);
|
| 1059 |
+
|
| 1060 |
+
_calculateMorphedAttributeData(
|
| 1061 |
+
object,
|
| 1062 |
+
normalAttribute,
|
| 1063 |
+
morphNormal,
|
| 1064 |
+
morphTargetsRelative,
|
| 1065 |
+
a, b, c,
|
| 1066 |
+
modifiedNormal
|
| 1067 |
+
);
|
| 1068 |
+
|
| 1069 |
+
}
|
| 1070 |
+
|
| 1071 |
+
}
|
| 1072 |
+
|
| 1073 |
+
} else {
|
| 1074 |
+
|
| 1075 |
+
start = Math.max( 0, drawRange.start );
|
| 1076 |
+
end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
|
| 1077 |
+
|
| 1078 |
+
for ( i = start, il = end; i < il; i += 3 ) {
|
| 1079 |
+
|
| 1080 |
+
a = index.getX( i );
|
| 1081 |
+
b = index.getX( i + 1 );
|
| 1082 |
+
c = index.getX( i + 2 );
|
| 1083 |
+
|
| 1084 |
+
_calculateMorphedAttributeData(
|
| 1085 |
+
object,
|
| 1086 |
+
positionAttribute,
|
| 1087 |
+
morphPosition,
|
| 1088 |
+
morphTargetsRelative,
|
| 1089 |
+
a, b, c,
|
| 1090 |
+
modifiedPosition
|
| 1091 |
+
);
|
| 1092 |
+
|
| 1093 |
+
_calculateMorphedAttributeData(
|
| 1094 |
+
object,
|
| 1095 |
+
normalAttribute,
|
| 1096 |
+
morphNormal,
|
| 1097 |
+
morphTargetsRelative,
|
| 1098 |
+
a, b, c,
|
| 1099 |
+
modifiedNormal
|
| 1100 |
+
);
|
| 1101 |
+
|
| 1102 |
+
}
|
| 1103 |
+
|
| 1104 |
+
}
|
| 1105 |
+
|
| 1106 |
+
} else {
|
| 1107 |
+
|
| 1108 |
+
// non-indexed buffer geometry
|
| 1109 |
+
|
| 1110 |
+
if ( Array.isArray( material ) ) {
|
| 1111 |
+
|
| 1112 |
+
for ( i = 0, il = groups.length; i < il; i ++ ) {
|
| 1113 |
+
|
| 1114 |
+
group = groups[ i ];
|
| 1115 |
+
|
| 1116 |
+
start = Math.max( group.start, drawRange.start );
|
| 1117 |
+
end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
|
| 1118 |
+
|
| 1119 |
+
for ( j = start, jl = end; j < jl; j += 3 ) {
|
| 1120 |
+
|
| 1121 |
+
a = j;
|
| 1122 |
+
b = j + 1;
|
| 1123 |
+
c = j + 2;
|
| 1124 |
+
|
| 1125 |
+
_calculateMorphedAttributeData(
|
| 1126 |
+
object,
|
| 1127 |
+
positionAttribute,
|
| 1128 |
+
morphPosition,
|
| 1129 |
+
morphTargetsRelative,
|
| 1130 |
+
a, b, c,
|
| 1131 |
+
modifiedPosition
|
| 1132 |
+
);
|
| 1133 |
+
|
| 1134 |
+
_calculateMorphedAttributeData(
|
| 1135 |
+
object,
|
| 1136 |
+
normalAttribute,
|
| 1137 |
+
morphNormal,
|
| 1138 |
+
morphTargetsRelative,
|
| 1139 |
+
a, b, c,
|
| 1140 |
+
modifiedNormal
|
| 1141 |
+
);
|
| 1142 |
+
|
| 1143 |
+
}
|
| 1144 |
+
|
| 1145 |
+
}
|
| 1146 |
+
|
| 1147 |
+
} else {
|
| 1148 |
+
|
| 1149 |
+
start = Math.max( 0, drawRange.start );
|
| 1150 |
+
end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
|
| 1151 |
+
|
| 1152 |
+
for ( i = start, il = end; i < il; i += 3 ) {
|
| 1153 |
+
|
| 1154 |
+
a = i;
|
| 1155 |
+
b = i + 1;
|
| 1156 |
+
c = i + 2;
|
| 1157 |
+
|
| 1158 |
+
_calculateMorphedAttributeData(
|
| 1159 |
+
object,
|
| 1160 |
+
positionAttribute,
|
| 1161 |
+
morphPosition,
|
| 1162 |
+
morphTargetsRelative,
|
| 1163 |
+
a, b, c,
|
| 1164 |
+
modifiedPosition
|
| 1165 |
+
);
|
| 1166 |
+
|
| 1167 |
+
_calculateMorphedAttributeData(
|
| 1168 |
+
object,
|
| 1169 |
+
normalAttribute,
|
| 1170 |
+
morphNormal,
|
| 1171 |
+
morphTargetsRelative,
|
| 1172 |
+
a, b, c,
|
| 1173 |
+
modifiedNormal
|
| 1174 |
+
);
|
| 1175 |
+
|
| 1176 |
+
}
|
| 1177 |
+
|
| 1178 |
+
}
|
| 1179 |
+
|
| 1180 |
+
}
|
| 1181 |
+
|
| 1182 |
+
const morphedPositionAttribute = new Float32BufferAttribute( modifiedPosition, 3 );
|
| 1183 |
+
const morphedNormalAttribute = new Float32BufferAttribute( modifiedNormal, 3 );
|
| 1184 |
+
|
| 1185 |
+
return {
|
| 1186 |
+
|
| 1187 |
+
positionAttribute: positionAttribute,
|
| 1188 |
+
normalAttribute: normalAttribute,
|
| 1189 |
+
morphedPositionAttribute: morphedPositionAttribute,
|
| 1190 |
+
morphedNormalAttribute: morphedNormalAttribute
|
| 1191 |
+
|
| 1192 |
+
};
|
| 1193 |
+
|
| 1194 |
+
}
|
| 1195 |
+
|
| 1196 |
+
/**
|
| 1197 |
+
* Merges the {@link BufferGeometry#groups} for the given geometry.
|
| 1198 |
+
*
|
| 1199 |
+
* @param {BufferGeometry} geometry - The geometry to modify.
|
| 1200 |
+
* @return {BufferGeometry} - The updated geometry
|
| 1201 |
+
*/
|
| 1202 |
+
function mergeGroups( geometry ) {
|
| 1203 |
+
|
| 1204 |
+
if ( geometry.groups.length === 0 ) {
|
| 1205 |
+
|
| 1206 |
+
console.warn( 'THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge.' );
|
| 1207 |
+
return geometry;
|
| 1208 |
+
|
| 1209 |
+
}
|
| 1210 |
+
|
| 1211 |
+
let groups = geometry.groups;
|
| 1212 |
+
|
| 1213 |
+
// sort groups by material index
|
| 1214 |
+
|
| 1215 |
+
groups = groups.sort( ( a, b ) => {
|
| 1216 |
+
|
| 1217 |
+
if ( a.materialIndex !== b.materialIndex ) return a.materialIndex - b.materialIndex;
|
| 1218 |
+
|
| 1219 |
+
return a.start - b.start;
|
| 1220 |
+
|
| 1221 |
+
} );
|
| 1222 |
+
|
| 1223 |
+
// create index for non-indexed geometries
|
| 1224 |
+
|
| 1225 |
+
if ( geometry.getIndex() === null ) {
|
| 1226 |
+
|
| 1227 |
+
const positionAttribute = geometry.getAttribute( 'position' );
|
| 1228 |
+
const indices = [];
|
| 1229 |
+
|
| 1230 |
+
for ( let i = 0; i < positionAttribute.count; i += 3 ) {
|
| 1231 |
+
|
| 1232 |
+
indices.push( i, i + 1, i + 2 );
|
| 1233 |
+
|
| 1234 |
+
}
|
| 1235 |
+
|
| 1236 |
+
geometry.setIndex( indices );
|
| 1237 |
+
|
| 1238 |
+
}
|
| 1239 |
+
|
| 1240 |
+
// sort index
|
| 1241 |
+
|
| 1242 |
+
const index = geometry.getIndex();
|
| 1243 |
+
|
| 1244 |
+
const newIndices = [];
|
| 1245 |
+
|
| 1246 |
+
for ( let i = 0; i < groups.length; i ++ ) {
|
| 1247 |
+
|
| 1248 |
+
const group = groups[ i ];
|
| 1249 |
+
|
| 1250 |
+
const groupStart = group.start;
|
| 1251 |
+
const groupLength = groupStart + group.count;
|
| 1252 |
+
|
| 1253 |
+
for ( let j = groupStart; j < groupLength; j ++ ) {
|
| 1254 |
+
|
| 1255 |
+
newIndices.push( index.getX( j ) );
|
| 1256 |
+
|
| 1257 |
+
}
|
| 1258 |
+
|
| 1259 |
+
}
|
| 1260 |
+
|
| 1261 |
+
geometry.dispose(); // Required to force buffer recreation
|
| 1262 |
+
geometry.setIndex( newIndices );
|
| 1263 |
+
|
| 1264 |
+
// update groups indices
|
| 1265 |
+
|
| 1266 |
+
let start = 0;
|
| 1267 |
+
|
| 1268 |
+
for ( let i = 0; i < groups.length; i ++ ) {
|
| 1269 |
+
|
| 1270 |
+
const group = groups[ i ];
|
| 1271 |
+
|
| 1272 |
+
group.start = start;
|
| 1273 |
+
start += group.count;
|
| 1274 |
+
|
| 1275 |
+
}
|
| 1276 |
+
|
| 1277 |
+
// merge groups
|
| 1278 |
+
|
| 1279 |
+
let currentGroup = groups[ 0 ];
|
| 1280 |
+
|
| 1281 |
+
geometry.groups = [ currentGroup ];
|
| 1282 |
+
|
| 1283 |
+
for ( let i = 1; i < groups.length; i ++ ) {
|
| 1284 |
+
|
| 1285 |
+
const group = groups[ i ];
|
| 1286 |
+
|
| 1287 |
+
if ( currentGroup.materialIndex === group.materialIndex ) {
|
| 1288 |
+
|
| 1289 |
+
currentGroup.count += group.count;
|
| 1290 |
+
|
| 1291 |
+
} else {
|
| 1292 |
+
|
| 1293 |
+
currentGroup = group;
|
| 1294 |
+
geometry.groups.push( currentGroup );
|
| 1295 |
+
|
| 1296 |
+
}
|
| 1297 |
+
|
| 1298 |
+
}
|
| 1299 |
+
|
| 1300 |
+
return geometry;
|
| 1301 |
+
|
| 1302 |
+
}
|
| 1303 |
+
|
| 1304 |
+
/**
|
| 1305 |
+
* Modifies the supplied geometry if it is non-indexed, otherwise creates a new,
|
| 1306 |
+
* non-indexed geometry. Returns the geometry with smooth normals everywhere except
|
| 1307 |
+
* faces that meet at an angle greater than the crease angle.
|
| 1308 |
+
*
|
| 1309 |
+
* @param {BufferGeometry} geometry - The geometry to modify.
|
| 1310 |
+
* @param {number} [creaseAngle=Math.PI/3] - The crease angle in radians.
|
| 1311 |
+
* @return {BufferGeometry} - The updated geometry
|
| 1312 |
+
*/
|
| 1313 |
+
function toCreasedNormals( geometry, creaseAngle = Math.PI / 3 /* 60 degrees */ ) {
|
| 1314 |
+
|
| 1315 |
+
const creaseDot = Math.cos( creaseAngle );
|
| 1316 |
+
const hashMultiplier = ( 1 + 1e-10 ) * 1e2;
|
| 1317 |
+
|
| 1318 |
+
// reusable vectors
|
| 1319 |
+
const verts = [ new Vector3(), new Vector3(), new Vector3() ];
|
| 1320 |
+
const tempVec1 = new Vector3();
|
| 1321 |
+
const tempVec2 = new Vector3();
|
| 1322 |
+
const tempNorm = new Vector3();
|
| 1323 |
+
const tempNorm2 = new Vector3();
|
| 1324 |
+
|
| 1325 |
+
// hashes a vector
|
| 1326 |
+
function hashVertex( v ) {
|
| 1327 |
+
|
| 1328 |
+
const x = ~ ~ ( v.x * hashMultiplier );
|
| 1329 |
+
const y = ~ ~ ( v.y * hashMultiplier );
|
| 1330 |
+
const z = ~ ~ ( v.z * hashMultiplier );
|
| 1331 |
+
return `${x},${y},${z}`;
|
| 1332 |
+
|
| 1333 |
+
}
|
| 1334 |
+
|
| 1335 |
+
// BufferGeometry.toNonIndexed() warns if the geometry is non-indexed
|
| 1336 |
+
// and returns the original geometry
|
| 1337 |
+
const resultGeometry = geometry.index ? geometry.toNonIndexed() : geometry;
|
| 1338 |
+
const posAttr = resultGeometry.attributes.position;
|
| 1339 |
+
const vertexMap = {};
|
| 1340 |
+
|
| 1341 |
+
// find all the normals shared by commonly located vertices
|
| 1342 |
+
for ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) {
|
| 1343 |
+
|
| 1344 |
+
const i3 = 3 * i;
|
| 1345 |
+
const a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 );
|
| 1346 |
+
const b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 );
|
| 1347 |
+
const c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 );
|
| 1348 |
+
|
| 1349 |
+
tempVec1.subVectors( c, b );
|
| 1350 |
+
tempVec2.subVectors( a, b );
|
| 1351 |
+
|
| 1352 |
+
// add the normal to the map for all vertices
|
| 1353 |
+
const normal = new Vector3().crossVectors( tempVec1, tempVec2 ).normalize();
|
| 1354 |
+
for ( let n = 0; n < 3; n ++ ) {
|
| 1355 |
+
|
| 1356 |
+
const vert = verts[ n ];
|
| 1357 |
+
const hash = hashVertex( vert );
|
| 1358 |
+
if ( ! ( hash in vertexMap ) ) {
|
| 1359 |
+
|
| 1360 |
+
vertexMap[ hash ] = [];
|
| 1361 |
+
|
| 1362 |
+
}
|
| 1363 |
+
|
| 1364 |
+
vertexMap[ hash ].push( normal );
|
| 1365 |
+
|
| 1366 |
+
}
|
| 1367 |
+
|
| 1368 |
+
}
|
| 1369 |
+
|
| 1370 |
+
// average normals from all vertices that share a common location if they are within the
|
| 1371 |
+
// provided crease threshold
|
| 1372 |
+
const normalArray = new Float32Array( posAttr.count * 3 );
|
| 1373 |
+
const normAttr = new BufferAttribute( normalArray, 3, false );
|
| 1374 |
+
for ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) {
|
| 1375 |
+
|
| 1376 |
+
// get the face normal for this vertex
|
| 1377 |
+
const i3 = 3 * i;
|
| 1378 |
+
const a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 );
|
| 1379 |
+
const b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 );
|
| 1380 |
+
const c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 );
|
| 1381 |
+
|
| 1382 |
+
tempVec1.subVectors( c, b );
|
| 1383 |
+
tempVec2.subVectors( a, b );
|
| 1384 |
+
|
| 1385 |
+
tempNorm.crossVectors( tempVec1, tempVec2 ).normalize();
|
| 1386 |
+
|
| 1387 |
+
// average all normals that meet the threshold and set the normal value
|
| 1388 |
+
for ( let n = 0; n < 3; n ++ ) {
|
| 1389 |
+
|
| 1390 |
+
const vert = verts[ n ];
|
| 1391 |
+
const hash = hashVertex( vert );
|
| 1392 |
+
const otherNormals = vertexMap[ hash ];
|
| 1393 |
+
tempNorm2.set( 0, 0, 0 );
|
| 1394 |
+
|
| 1395 |
+
for ( let k = 0, lk = otherNormals.length; k < lk; k ++ ) {
|
| 1396 |
+
|
| 1397 |
+
const otherNorm = otherNormals[ k ];
|
| 1398 |
+
if ( tempNorm.dot( otherNorm ) > creaseDot ) {
|
| 1399 |
+
|
| 1400 |
+
tempNorm2.add( otherNorm );
|
| 1401 |
+
|
| 1402 |
+
}
|
| 1403 |
+
|
| 1404 |
+
}
|
| 1405 |
+
|
| 1406 |
+
tempNorm2.normalize();
|
| 1407 |
+
normAttr.setXYZ( i3 + n, tempNorm2.x, tempNorm2.y, tempNorm2.z );
|
| 1408 |
+
|
| 1409 |
+
}
|
| 1410 |
+
|
| 1411 |
+
}
|
| 1412 |
+
|
| 1413 |
+
resultGeometry.setAttribute( 'normal', normAttr );
|
| 1414 |
+
return resultGeometry;
|
| 1415 |
+
|
| 1416 |
+
}
|
| 1417 |
+
|
| 1418 |
+
export {
|
| 1419 |
+
computeMikkTSpaceTangents,
|
| 1420 |
+
mergeGeometries,
|
| 1421 |
+
mergeAttributes,
|
| 1422 |
+
deepCloneAttribute,
|
| 1423 |
+
deinterleaveAttribute,
|
| 1424 |
+
deinterleaveGeometry,
|
| 1425 |
+
interleaveAttributes,
|
| 1426 |
+
estimateBytesUsed,
|
| 1427 |
+
mergeVertices,
|
| 1428 |
+
toTrianglesDrawMode,
|
| 1429 |
+
computeMorphedAttributes,
|
| 1430 |
+
mergeGroups,
|
| 1431 |
+
toCreasedNormals
|
| 1432 |
+
};
|
source/app/src/main/assets/avatar/lib/three-vrm.module.min.js
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
source/app/src/main/assets/avatar/lib/three.core.min.js
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
source/app/src/main/assets/avatar/lib/three.module.min.js
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
source/app/src/main/assets/avatar/model.vrm
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1e177c1a7b14f783a9c48395831db8616260d3bddd4154cb2784b779adca49b5
|
| 3 |
+
size 15074328
|
source/app/src/main/assets/models/hann400.f32
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2b66ad855bb20e73e657a4df6d8f4a4c840a18431c35cf323f29143f04796c7e
|
| 3 |
+
size 1600
|
source/app/src/main/assets/models/smart_turn.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ab8dc64b88713f90b571c15b714bd1330e6c883cad8763dacf65c9376dc539be
|
| 3 |
+
size 32411198
|
source/app/src/main/assets/models/vap_ar.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5c63de5ef43e8381e9e61c729ad1e1b9079c4e780029ff2d79f26baebc9b8a90
|
| 3 |
+
size 14580966
|
source/app/src/main/assets/models/vap_enc.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:04e19270e5a95658681c8d1899c063a6c57162398f258a138a5d9405bd7a022f
|
| 3 |
+
size 10053753
|
source/app/src/main/assets/models/whisper_mel_80x201.f32
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2150c30cbbeb6029f52002ffa666c1c72d83dbf53f463cb8462052055806e891
|
| 3 |
+
size 64320
|
source/app/src/main/assets/partlock/clip_text_q8.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fd1b85629f43ff0ff01c52b46e9a85d78c24f2f26bb87f75f096ee9d4e9dc88d
|
| 3 |
+
size 68961289
|
source/app/src/main/assets/partlock/clip_tok/merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
source/app/src/main/assets/partlock/clip_tok/vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
source/app/src/main/assets/partlock/dec2.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7ee092efe86d84703f38c2aef8f3c66caa8ce4e50a6ce9d459fd62d69977aadb
|
| 3 |
+
size 14099195
|
source/app/src/main/assets/partlock/gen_step2_int8.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e1deeba9f4a03657b47f9bc1198eee2ecbb89e38df2f9f646d3c061e54ea0789
|
| 3 |
+
size 38438450
|
source/app/src/main/assets/partlock/meta.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"NV": 4864, "OFF": [0, 4096, 4224, 4352, 4480, 4608, 4736], "VOC": [4096, 128, 128, 128, 128, 128, 128], "S": 64, "M": 449, "NL": 8, "NH": 8, "DH": 64, "PARENTS": [-1, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 12, 13, 14, 16, 17, 18, 19], "DEC_CTX": 32}
|
source/app/src/main/assets/partlock/null.f32
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3cb4f07b85bd8cc62efdda7ff603a27c1b5d083e95b2d17affc2de21ab641281
|
| 3 |
+
size 2048
|
source/app/src/main/cpp/CMakeLists.txt
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ミマモの C++ の組み立て
|
| 2 |
+
# YAKISFULL-DUPLEX の会話の本体(duplex_android/app/src/main/cpp)を、そのまま組み立てて使う。
|
| 3 |
+
# 違いは 1 つだけ: 会話の LLM(llm.cpp)を、写真も受け取れるミマモ版(llm_vision.cpp)に差しかえる。
|
| 4 |
+
# 写真を読む部品は llama.cpp の mtmd(Gemma 4 の目のファイル mmproj を読む)。YAKISFULL のファイルには手を入れない
|
| 5 |
+
cmake_minimum_required(VERSION 3.22.1)
|
| 6 |
+
project(mimamo)
|
| 7 |
+
|
| 8 |
+
# 公開版: YAKISFULL-DUPLEX の C++ は duplex/ に、部品は一番上の third_party/ に入れてある
|
| 9 |
+
set(DUPLEX ${CMAKE_CURRENT_SOURCE_DIR}/duplex)
|
| 10 |
+
set(TP ${CMAKE_CURRENT_SOURCE_DIR}/../../../../third_party)
|
| 11 |
+
set(JNILIBS ${CMAKE_CURRENT_SOURCE_DIR}/../jniLibs/${ANDROID_ABI})
|
| 12 |
+
|
| 13 |
+
# ---- llama.cpp(YAKISFULL と同じ設定)+ 写真を読む部品(mtmd)だけを足す
|
| 14 |
+
set(LLAMA_BUILD_COMMON OFF CACHE BOOL "" FORCE)
|
| 15 |
+
set(LLAMA_BUILD_TESTS OFF CACHE BOOL "" FORCE)
|
| 16 |
+
set(LLAMA_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
|
| 17 |
+
set(LLAMA_BUILD_SERVER OFF CACHE BOOL "" FORCE)
|
| 18 |
+
set(LLAMA_BUILD_TOOLS OFF CACHE BOOL "" FORCE)
|
| 19 |
+
set(LLAMA_BUILD_MTMD ON CACHE BOOL "" FORCE) # 写真を読む部品だけを組み立てる
|
| 20 |
+
set(MTMD_VIDEO OFF CACHE BOOL "" FORCE) # 動画は使わない
|
| 21 |
+
set(LLAMA_CURL OFF CACHE BOOL "" FORCE)
|
| 22 |
+
set(GGML_OPENMP OFF CACHE BOOL "" FORCE)
|
| 23 |
+
set(GGML_NATIVE OFF CACHE BOOL "" FORCE)
|
| 24 |
+
set(GGML_CPU_ARM_ARCH "armv8-a" CACHE STRING "" FORCE)
|
| 25 |
+
set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
|
| 26 |
+
set(GGML_VULKAN ON CACHE BOOL "" FORCE)
|
| 27 |
+
set(Vulkan_INCLUDE_DIR "${TP}/Vulkan-Headers/include" CACHE PATH "")
|
| 28 |
+
add_subdirectory(${TP}/llama.cpp-1.0.0 llama EXCLUDE_FROM_ALL)
|
| 29 |
+
|
| 30 |
+
add_library(onnxruntime SHARED IMPORTED)
|
| 31 |
+
set_target_properties(onnxruntime PROPERTIES IMPORTED_LOCATION ${JNILIBS}/libonnxruntime.so)
|
| 32 |
+
add_library(moonshine SHARED IMPORTED)
|
| 33 |
+
set_target_properties(moonshine PROPERTIES IMPORTED_LOCATION ${JNILIBS}/libmoonshine.so)
|
| 34 |
+
find_package(oboe REQUIRED CONFIG)
|
| 35 |
+
|
| 36 |
+
# ---- 会話の本体。llm.cpp だけミマモ版にする。出来上がりの名前は YAKISFULL と同じ
|
| 37 |
+
add_library(duplex SHARED llm_vision.cpp ${DUPLEX}/models.cpp ${DUPLEX}/moonshine_asr.cpp ${DUPLEX}/tts.cpp ${DUPLEX}/engine.cpp ${DUPLEX}/audio_oboe.cpp)
|
| 38 |
+
target_include_directories(duplex PRIVATE ${DUPLEX} ${TP}/onnxruntime/aar/headers ${TP}/voicevox/include ${TP}/pocketfft)
|
| 39 |
+
target_link_libraries(duplex llama mtmd onnxruntime moonshine oboe::oboe android log dl)
|
source/app/src/main/cpp/duplex/audio_io.h
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// audio_io.h — マイクとスピーカーの決まった形(スマホ版は audio_oboe.cpp、Windows 版は audio_wasapi.cpp が中身を書く)
|
| 2 |
+
//
|
| 3 |
+
// マイク: 16000Hz・1ch・float の音を on_input(音, 個数) で渡す
|
| 4 |
+
// スピーカー: 24000Hz・1ch・float の音を on_output(入れ物, 個数, 24000) で詰めてもらう
|
| 5 |
+
// aec = true のときは、通話用の音声処理(エコー消し)を使う。スピーカーも通話の音として鳴らす
|
| 6 |
+
#pragma once
|
| 7 |
+
#include <functional>
|
| 8 |
+
#include <memory>
|
| 9 |
+
#include <string>
|
| 10 |
+
|
| 11 |
+
struct AudioIO {
|
| 12 |
+
std::function<void(const float *, int)> on_input;
|
| 13 |
+
std::function<void(float *, int, int)> on_output;
|
| 14 |
+
std::string note; // 開けたが、知らせたいこと(例: マイクが無いのでスピーカーだけで始めた)
|
| 15 |
+
|
| 16 |
+
virtual ~AudioIO() = default;
|
| 17 |
+
virtual std::string open(bool aec) = 0; // 戻り値: 失敗の理由(成功は空)
|
| 18 |
+
virtual void start() = 0;
|
| 19 |
+
virtual void stop_input() = 0; // マイクだけ先に止める(会話の流れを止める前)
|
| 20 |
+
virtual void stop() = 0; // 全部止めて閉じる
|
| 21 |
+
virtual int xruns() { return -1; } // スピーカーの音切れの回数(わからなければ -1)
|
| 22 |
+
};
|
| 23 |
+
|
| 24 |
+
std::unique_ptr<AudioIO> make_audio_io();
|
source/app/src/main/cpp/duplex/audio_oboe.cpp
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// audio_oboe.cpp — スマホ版のマイクとスピーカー(Oboe)
|
| 2 |
+
// エコー消しは Android の通話用の音声処理(VoiceCommunication)を使う
|
| 3 |
+
#include "audio_io.h"
|
| 4 |
+
|
| 5 |
+
#include "oboe/Oboe.h"
|
| 6 |
+
|
| 7 |
+
namespace {
|
| 8 |
+
class OboeIO : public AudioIO, public oboe::AudioStreamDataCallback {
|
| 9 |
+
std::shared_ptr<oboe::AudioStream> in, out;
|
| 10 |
+
|
| 11 |
+
public:
|
| 12 |
+
oboe::DataCallbackResult onAudioReady(oboe::AudioStream *s, void *data, int32_t n) override {
|
| 13 |
+
if (s->getDirection() == oboe::Direction::Input) {
|
| 14 |
+
if (on_input) on_input((const float *) data, n);
|
| 15 |
+
} else if (on_output) {
|
| 16 |
+
on_output((float *) data, n, s->getSampleRate());
|
| 17 |
+
}
|
| 18 |
+
return oboe::DataCallbackResult::Continue;
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
std::string open(bool aec) override {
|
| 22 |
+
oboe::AudioStreamBuilder ib;
|
| 23 |
+
ib.setDirection(oboe::Direction::Input)
|
| 24 |
+
->setPerformanceMode(oboe::PerformanceMode::LowLatency)
|
| 25 |
+
->setSharingMode(oboe::SharingMode::Shared)
|
| 26 |
+
->setFormat(oboe::AudioFormat::Float)
|
| 27 |
+
->setChannelCount(1)
|
| 28 |
+
->setSampleRate(16000)
|
| 29 |
+
->setSampleRateConversionQuality(oboe::SampleRateConversionQuality::Medium)
|
| 30 |
+
->setInputPreset(aec ? oboe::InputPreset::VoiceCommunication : oboe::InputPreset::VoiceRecognition) // スマホのエコー消し
|
| 31 |
+
->setDataCallback(this);
|
| 32 |
+
if (ib.openStream(in) != oboe::Result::OK) return "マイクを開けません";
|
| 33 |
+
oboe::AudioStreamBuilder ob;
|
| 34 |
+
ob.setDirection(oboe::Direction::Output)
|
| 35 |
+
->setPerformanceMode(oboe::PerformanceMode::LowLatency)
|
| 36 |
+
->setSharingMode(oboe::SharingMode::Shared)
|
| 37 |
+
->setFormat(oboe::AudioFormat::Float)
|
| 38 |
+
->setChannelCount(1)
|
| 39 |
+
->setSampleRate(24000)
|
| 40 |
+
->setSampleRateConversionQuality(oboe::SampleRateConversionQuality::Medium)
|
| 41 |
+
->setUsage(oboe::Usage::VoiceCommunication) // エコー消しが手本として使えるように、通話の音として鳴らす
|
| 42 |
+
->setContentType(oboe::ContentType::Speech)
|
| 43 |
+
->setDataCallback(this);
|
| 44 |
+
if (ob.openStream(out) != oboe::Result::OK) { in->close(); in.reset(); return "スピーカーを開けません"; }
|
| 45 |
+
return "";
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
void start() override {
|
| 49 |
+
in->requestStart();
|
| 50 |
+
out->requestStart();
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
void stop_input() override {
|
| 54 |
+
if (in) { in->requestStop(); in->close(); in.reset(); }
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
void stop() override {
|
| 58 |
+
stop_input();
|
| 59 |
+
if (out) { out->requestStop(); out->close(); out.reset(); }
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
int xruns() override {
|
| 63 |
+
if (!out) return -1;
|
| 64 |
+
const auto result = out->getXRunCount();
|
| 65 |
+
return result ? result.value() : -1;
|
| 66 |
+
}
|
| 67 |
+
};
|
| 68 |
+
} // namespace
|
| 69 |
+
|
| 70 |
+
std::unique_ptr<AudioIO> make_audio_io() { return std::make_unique<OboeIO>(); }
|
source/app/src/main/cpp/duplex/common.h
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// common.h — どの部品からも使う小道具(時刻、ひらがなの扱い、小さな JSON 読み)
|
| 2 |
+
#pragma once
|
| 3 |
+
#include <android/log.h>
|
| 4 |
+
|
| 5 |
+
#include <algorithm>
|
| 6 |
+
#include <chrono>
|
| 7 |
+
#include <iterator>
|
| 8 |
+
#include <cstdlib>
|
| 9 |
+
#include <map>
|
| 10 |
+
#include <memory>
|
| 11 |
+
#include <string>
|
| 12 |
+
#include <string_view>
|
| 13 |
+
#include <vector>
|
| 14 |
+
|
| 15 |
+
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, "duplex", __VA_ARGS__)
|
| 16 |
+
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, "duplex", __VA_ARGS__)
|
| 17 |
+
|
| 18 |
+
inline double now_sec() {
|
| 19 |
+
using namespace std::chrono;
|
| 20 |
+
return duration<double>(steady_clock::now().time_since_epoch()).count();
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
// ---------------- 文字(UTF-8 ⇔ 1 文字ずつ)
|
| 24 |
+
inline std::u32string to_u32(const std::string &s) {
|
| 25 |
+
std::u32string r;
|
| 26 |
+
for (size_t i = 0; i < s.size();) {
|
| 27 |
+
unsigned char c = s[i];
|
| 28 |
+
char32_t cp;
|
| 29 |
+
int n;
|
| 30 |
+
if (c < 0x80) { cp = c; n = 1; }
|
| 31 |
+
else if ((c >> 5) == 6) { cp = c & 0x1F; n = 2; }
|
| 32 |
+
else if ((c >> 4) == 14) { cp = c & 0x0F; n = 3; }
|
| 33 |
+
else { cp = c & 0x07; n = 4; }
|
| 34 |
+
for (int k = 1; k < n && i + k < s.size(); k++) cp = (cp << 6) | (s[i + k] & 0x3F);
|
| 35 |
+
r.push_back(cp);
|
| 36 |
+
i += n;
|
| 37 |
+
}
|
| 38 |
+
return r;
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
inline std::string to_u8(const std::u32string &s) {
|
| 42 |
+
std::string r;
|
| 43 |
+
for (char32_t c : s) {
|
| 44 |
+
if (c < 0x80) r += (char) c;
|
| 45 |
+
else if (c < 0x800) { r += (char) (0xC0 | (c >> 6)); r += (char) (0x80 | (c & 0x3F)); }
|
| 46 |
+
else if (c < 0x10000) { r += (char) (0xE0 | (c >> 12)); r += (char) (0x80 | ((c >> 6) & 0x3F)); r += (char) (0x80 | (c & 0x3F)); }
|
| 47 |
+
else { r += (char) (0xF0 | (c >> 18)); r += (char) (0x80 | ((c >> 12) & 0x3F)); r += (char) (0x80 | ((c >> 6) & 0x3F)); r += (char) (0x80 | (c & 0x3F)); }
|
| 48 |
+
}
|
| 49 |
+
return r;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
inline char32_t kata2hira(char32_t c) { return (c >= U'ァ' && c <= U'ヴ') ? c - 0x60 : c; }
|
| 53 |
+
|
| 54 |
+
// 伸ばす音の書き方をそろえる: 「ー」を前の文字の母音にする
|
| 55 |
+
inline char32_t vowel_of(char32_t c) {
|
| 56 |
+
static const std::u32string R[5] = {U"あかがさざただなはばぱまやらわぁゃゎ", U"いきぎしじちぢにひびぴみりぃゐ",
|
| 57 |
+
U"うくぐすずつづぬふぶぷむゆるぅゅゔ", U"えけげせぜてでねへべぺめれぇゑ",
|
| 58 |
+
U"おこごそぞとどのほぼぽもよろをぉょ"};
|
| 59 |
+
static const char32_t V[5] = {U'あ', U'い', U'う', U'え', U'お'};
|
| 60 |
+
for (int i = 0; i < 5; i++)
|
| 61 |
+
if (R[i].find(c) != std::u32string::npos) return V[i];
|
| 62 |
+
return U'ー';
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
inline std::u32string norm(const std::u32string &s) {
|
| 66 |
+
std::u32string o;
|
| 67 |
+
for (char32_t c : s) o.push_back(c == U'ー' && !o.empty() ? vowel_of(o.back()) : c);
|
| 68 |
+
return o;
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
// 相づちの言葉の一覧(ひらがな・伸ばす音をそろえた形)。数える用と取り除く用で同じものを使う。前にあるものから先に試す
|
| 72 |
+
inline const std::u32string_view *ack_words(size_t &n) {
|
| 73 |
+
static const std::u32string_view w[] = {
|
| 74 |
+
U"なるほどですね", U"なるほどね", U"なるほど", U"そうですね", U"そうなんですね",
|
| 75 |
+
U"そうなんだ", U"そうなんですか", U"そうですか", U"そうだね", U"そうか", U"そっか",
|
| 76 |
+
U"うんうん", U"はいはい", U"そうそう", U"そおそお", U"ふんふん", U"ふむふむ",
|
| 77 |
+
U"ううん", U"うんん", U"ええっとと", U"ええっと", U"ええと",
|
| 78 |
+
U"ふうん", U"ふうむ", U"はあい", U"ほほう", U"ほんとだ", U"たしかに",
|
| 79 |
+
U"確かに", U"成程", U"うん", U"はい", U"へえ", U"ほお", U"ああ", U"おお",
|
| 80 |
+
U"ええ", U"ふむ", U"そう", U"そお"
|
| 81 |
+
};
|
| 82 |
+
n = sizeof(w) / sizeof(w[0]);
|
| 83 |
+
return w;
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
inline bool ack_punct(char32_t c) { return std::u32string_view(U" 、。!?,.!? …\n\r\t").find(c) != std::u32string_view::npos; }
|
| 87 |
+
|
| 88 |
+
// 相づちの言葉のすぐ後ろが、文を続ける言葉(「けど」「から」「って」「よ」「ね」など)なら、それは相づちではなく話の始まり
|
| 89 |
+
// 例:「そうなんだけど」「そうかもね」は相づちとして取り除かない。「うんうんで、どこで…」の「で」は話の始まりとして続けてよい
|
| 90 |
+
inline bool ack_continues(const std::u32string &view, size_t at) {
|
| 91 |
+
if (at >= view.size()) return false;
|
| 92 |
+
static const std::u32string_view next = U"けかがってよねなのわしもじ";
|
| 93 |
+
return next.find(view[at]) != std::u32string_view::npos;
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
// 相づちの言葉と「ー」を除いた残り(割り込みかどうか、短すぎる発話かどうかを見る)
|
| 97 |
+
inline std::u32string other_chars(std::u32string s) {
|
| 98 |
+
// 句読点は「、」1 つにまとめて残す(言葉の区切りとして使う。相づちのすぐ後ろが区切りなら、相づちで終わっている)
|
| 99 |
+
std::u32string clean;
|
| 100 |
+
for (char32_t c : s) {
|
| 101 |
+
if (ack_punct(c)) { if (!clean.empty() && clean.back() != U'、') clean.push_back(U'、'); }
|
| 102 |
+
else clean.push_back(kata2hira(c));
|
| 103 |
+
}
|
| 104 |
+
clean = norm(clean);
|
| 105 |
+
size_t n;
|
| 106 |
+
const std::u32string_view *acknowledgements = ack_words(n);
|
| 107 |
+
// 先頭の相づちを取る。文の途中にある相づちの言葉は、普通の話として残す
|
| 108 |
+
for (;;) {
|
| 109 |
+
while (!clean.empty() && clean.front() == U'、') clean.erase(0, 1);
|
| 110 |
+
auto match = std::find_if(acknowledgements, acknowledgements + n, [&](auto word) {
|
| 111 |
+
return clean.compare(0, word.size(), word) == 0 && !ack_continues(clean, word.size());
|
| 112 |
+
});
|
| 113 |
+
if (match == acknowledgements + n) break;
|
| 114 |
+
clean.erase(0, match->size());
|
| 115 |
+
}
|
| 116 |
+
clean.erase(std::remove(clean.begin(), clean.end(), U'ー'), clean.end());
|
| 117 |
+
clean.erase(std::remove(clean.begin(), clean.end(), U'、'), clean.end());
|
| 118 |
+
return clean;
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
// 文の先頭にある相づちだけを、元の文から切り取る(LLM に送る文・画面に出す文に使う)
|
| 122 |
+
// 見分け方は other_chars と同じ(ひらがなにそろえ、句読点を飛ばし、「ー」は前の母音にして比べる)
|
| 123 |
+
// 切り取るのは先頭だけ。文の途中の「そうなんだけど」などは普通の言葉として残す。漢字やカタカナの形はそのまま
|
| 124 |
+
inline std::string strip_leading_ack(const std::string &in) {
|
| 125 |
+
std::u32string s = to_u32(in);
|
| 126 |
+
size_t n;
|
| 127 |
+
const std::u32string_view *acks = ack_words(n);
|
| 128 |
+
size_t pos = 0;
|
| 129 |
+
for (;;) {
|
| 130 |
+
while (pos < s.size() && ack_punct(s[pos])) pos++;
|
| 131 |
+
// pos から先を、比べる形にそろえる。idx[k] = そろえた形の k+1 文字目までで、元の文のどこまで進んだか
|
| 132 |
+
std::u32string view;
|
| 133 |
+
std::vector<size_t> idx;
|
| 134 |
+
for (size_t i = pos; i < s.size() && view.size() < 16; i++) {
|
| 135 |
+
if (ack_punct(s[i])) { // 句読点は区切りの印として 1 つだけ残す
|
| 136 |
+
if (!view.empty() && view.back() != U'、') { view.push_back(U'、'); idx.push_back(i + 1); }
|
| 137 |
+
continue;
|
| 138 |
+
}
|
| 139 |
+
char32_t c = kata2hira(s[i]);
|
| 140 |
+
if (c == U'ー' && !view.empty()) c = vowel_of(view.back());
|
| 141 |
+
view.push_back(c);
|
| 142 |
+
idx.push_back(i + 1);
|
| 143 |
+
}
|
| 144 |
+
auto match = std::find_if(acks, acks + n, [&](auto w) {
|
| 145 |
+
return view.compare(0, w.size(), w) == 0 && !ack_continues(view, w.size());
|
| 146 |
+
});
|
| 147 |
+
if (match == acks + n || match->empty()) break;
|
| 148 |
+
pos = idx[match->size() - 1];
|
| 149 |
+
while (pos < s.size() && s[pos] == U'ー') pos++; // 「うんー」の伸ばしも一緒に取る
|
| 150 |
+
}
|
| 151 |
+
while (pos < s.size() && ack_punct(s[pos])) pos++;
|
| 152 |
+
return to_u8(s.substr(pos));
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
// ---------------- 小さな JSON 読み(VOICEVOX の結果を読むだけ)
|
| 157 |
+
struct J {
|
| 158 |
+
enum T { NUL, NUM, STR, BOOL, ARR, OBJ } t = NUL;
|
| 159 |
+
double n = 0;
|
| 160 |
+
bool b = false;
|
| 161 |
+
std::string s;
|
| 162 |
+
std::vector<J> a;
|
| 163 |
+
std::map<std::string, J> o;
|
| 164 |
+
const J &operator[](const std::string &k) const {
|
| 165 |
+
static J none;
|
| 166 |
+
auto it = o.find(k);
|
| 167 |
+
return it == o.end() ? none : it->second;
|
| 168 |
+
}
|
| 169 |
+
};
|
| 170 |
+
|
| 171 |
+
struct JParser {
|
| 172 |
+
const char *p;
|
| 173 |
+
void ws() { while (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') p++; }
|
| 174 |
+
std::string str() {
|
| 175 |
+
std::string r;
|
| 176 |
+
p++;
|
| 177 |
+
while (*p && *p != '"') {
|
| 178 |
+
if (*p == '\\') {
|
| 179 |
+
p++;
|
| 180 |
+
if (*p == 'u') {
|
| 181 |
+
unsigned cp = (unsigned) strtoul(std::string(p + 1, 4).c_str(), nullptr, 16);
|
| 182 |
+
p += 5;
|
| 183 |
+
if (cp >= 0xD800 && cp <= 0xDBFF && p[0] == '\\' && p[1] == 'u') {
|
| 184 |
+
unsigned lo = (unsigned) strtoul(std::string(p + 2, 4).c_str(), nullptr, 16);
|
| 185 |
+
p += 6;
|
| 186 |
+
cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
|
| 187 |
+
}
|
| 188 |
+
r += to_u8(std::u32string(1, (char32_t) cp));
|
| 189 |
+
continue;
|
| 190 |
+
}
|
| 191 |
+
char e = *p++;
|
| 192 |
+
r += e == 'n' ? '\n' : e == 't' ? '\t' : e;
|
| 193 |
+
} else r += *p++;
|
| 194 |
+
}
|
| 195 |
+
p++;
|
| 196 |
+
return r;
|
| 197 |
+
}
|
| 198 |
+
J val() {
|
| 199 |
+
ws();
|
| 200 |
+
J v;
|
| 201 |
+
if (*p == '{') {
|
| 202 |
+
v.t = J::OBJ;
|
| 203 |
+
p++;
|
| 204 |
+
ws();
|
| 205 |
+
while (*p && *p != '}') {
|
| 206 |
+
ws();
|
| 207 |
+
std::string k = str();
|
| 208 |
+
ws(); p++; // ':'
|
| 209 |
+
v.o[k] = val();
|
| 210 |
+
ws();
|
| 211 |
+
if (*p == ',') p++;
|
| 212 |
+
ws();
|
| 213 |
+
}
|
| 214 |
+
p++;
|
| 215 |
+
} else if (*p == '[') {
|
| 216 |
+
v.t = J::ARR;
|
| 217 |
+
p++;
|
| 218 |
+
ws();
|
| 219 |
+
while (*p && *p != ']') {
|
| 220 |
+
v.a.push_back(val());
|
| 221 |
+
ws();
|
| 222 |
+
if (*p == ',') p++;
|
| 223 |
+
ws();
|
| 224 |
+
}
|
| 225 |
+
p++;
|
| 226 |
+
} else if (*p == '"') {
|
| 227 |
+
v.t = J::STR;
|
| 228 |
+
v.s = str();
|
| 229 |
+
} else if (*p == 't' || *p == 'f') {
|
| 230 |
+
v.t = J::BOOL;
|
| 231 |
+
v.b = *p == 't';
|
| 232 |
+
p += v.b ? 4 : 5;
|
| 233 |
+
} else if (*p == 'n') {
|
| 234 |
+
p += 4;
|
| 235 |
+
} else {
|
| 236 |
+
v.t = J::NUM;
|
| 237 |
+
char *e;
|
| 238 |
+
v.n = strtod(p, &e);
|
| 239 |
+
p = e;
|
| 240 |
+
}
|
| 241 |
+
return v;
|
| 242 |
+
}
|
| 243 |
+
};
|
| 244 |
+
|
| 245 |
+
inline J parse_json(const std::string &s) {
|
| 246 |
+
JParser jp{s.c_str()};
|
| 247 |
+
return jp.val();
|
| 248 |
+
}
|
source/app/src/main/cpp/duplex/engine.cpp
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// engine.cpp — スマホ版のつなぎ(Kotlin から呼ばれる入口と、Kotlin への知らせ)
|
| 2 |
+
// 会話の中身は engine_core.h(Windows 版と共通)。マイクとスピーカーは audio_oboe.cpp
|
| 3 |
+
#include <jni.h>
|
| 4 |
+
|
| 5 |
+
#include "engine_core.h"
|
| 6 |
+
|
| 7 |
+
namespace {
|
| 8 |
+
Engine *g_eng = nullptr;
|
| 9 |
+
|
| 10 |
+
// ---------------- Kotlin へ知らせる(会話の中身の emit() からここへ来る)
|
| 11 |
+
JavaVM *g_vm = nullptr;
|
| 12 |
+
jobject g_listener = nullptr;
|
| 13 |
+
jmethodID g_onEvent = nullptr;
|
| 14 |
+
|
| 15 |
+
void to_kotlin(int kind, const std::string &text, double v) {
|
| 16 |
+
if (!g_vm || !g_listener) return;
|
| 17 |
+
JNIEnv *env = nullptr;
|
| 18 |
+
bool attached = false;
|
| 19 |
+
if (g_vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) {
|
| 20 |
+
g_vm->AttachCurrentThread(&env, nullptr);
|
| 21 |
+
attached = true;
|
| 22 |
+
}
|
| 23 |
+
jbyteArray b = env->NewByteArray((jsize) text.size());
|
| 24 |
+
env->SetByteArrayRegion(b, 0, (jsize) text.size(), (const jbyte *) text.data());
|
| 25 |
+
env->CallVoidMethod(g_listener, g_onEvent, (jint) kind, b, (jdouble) v);
|
| 26 |
+
env->DeleteLocalRef(b);
|
| 27 |
+
if (attached) g_vm->DetachCurrentThread();
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
std::string jstr(JNIEnv *env, jstring s) {
|
| 31 |
+
const char *c = env->GetStringUTFChars(s, nullptr);
|
| 32 |
+
std::string r(c);
|
| 33 |
+
env->ReleaseStringUTFChars(s, c);
|
| 34 |
+
return r;
|
| 35 |
+
}
|
| 36 |
+
} // namespace
|
| 37 |
+
|
| 38 |
+
extern "C" {
|
| 39 |
+
|
| 40 |
+
JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *) {
|
| 41 |
+
g_vm = vm;
|
| 42 |
+
set_event_sink(to_kotlin);
|
| 43 |
+
return JNI_VERSION_1_6;
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
JNIEXPORT jstring JNICALL Java_jp_duplex_app_Engine_nativeInit(JNIEnv *env, jobject, jstring mdir, jstring asr_dir, jobject listener) {
|
| 47 |
+
if (g_listener) env->DeleteGlobalRef(g_listener);
|
| 48 |
+
g_listener = env->NewGlobalRef(listener);
|
| 49 |
+
g_onEvent = env->GetMethodID(env->GetObjectClass(listener), "onEvent", "(I[BD)V");
|
| 50 |
+
if (!g_eng) g_eng = new Engine();
|
| 51 |
+
return env->NewStringUTF(g_eng->init(jstr(env, mdir), jstr(env, asr_dir)).c_str());
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
JNIEXPORT jstring JNICALL Java_jp_duplex_app_Engine_nativeVoice(JNIEnv *env, jobject, jstring core, jstring ort, jstring vvm, jstring dic, jint threads) {
|
| 55 |
+
if (!g_eng) return env->NewStringUTF("まだ準備できていません");
|
| 56 |
+
return env->NewStringUTF(g_eng->init_voice(jstr(env, core), jstr(env, ort), jstr(env, vvm), jstr(env, dic), threads).c_str());
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
// 取り込んだ声のファイルに入っている声の一覧(VOICEVOX の JSON。UTF-8 のバイトで渡す)
|
| 60 |
+
JNIEXPORT jbyteArray JNICALL Java_jp_duplex_app_Engine_nativeVoiceMetas(JNIEnv *env, jobject) {
|
| 61 |
+
std::string m = g_eng ? g_eng->tts.metas : "";
|
| 62 |
+
jbyteArray b = env->NewByteArray((jsize) m.size());
|
| 63 |
+
env->SetByteArrayRegion(b, 0, (jsize) m.size(), (const jbyte *) m.data());
|
| 64 |
+
return b;
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
JNIEXPORT void JNICALL Java_jp_duplex_app_Engine_nativeParams(JNIEnv *env, jobject, jfloat th, jfloat fb, jint ms, jboolean az, jint voice, jboolean aec, jboolean thinking, jstring sys) {
|
| 68 |
+
if (g_eng) g_eng->set_params(Params{th, fb, ms, voice, (bool) az, (bool) aec, (bool) thinking, jstr(env, sys)});
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
JNIEXPORT jstring JNICALL Java_jp_duplex_app_Engine_nativeStart(JNIEnv *env, jobject) {
|
| 72 |
+
return env->NewStringUTF(g_eng ? g_eng->start().c_str() : "まだ準備できていません");
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
JNIEXPORT void JNICALL Java_jp_duplex_app_Engine_nativeStop(JNIEnv *, jobject) { if (g_eng) g_eng->stop(); }
|
| 76 |
+
|
| 77 |
+
JNIEXPORT void JNICALL Java_jp_duplex_app_Engine_nativeSay(JNIEnv *env, jobject, jstring t) { if (g_eng) g_eng->say(jstr(env, t)); }
|
| 78 |
+
|
| 79 |
+
// 計測の値(並び順は Engine::stats() の説明のとおり)
|
| 80 |
+
JNIEXPORT jdoubleArray JNICALL Java_jp_duplex_app_Engine_nativeStats(JNIEnv *env, jobject) {
|
| 81 |
+
std::vector<double> v = g_eng ? g_eng->stats() : std::vector<double>(21, 0.0);
|
| 82 |
+
jdoubleArray r = env->NewDoubleArray((jsize) v.size());
|
| 83 |
+
env->SetDoubleArrayRegion(r, 0, (jsize) v.size(), v.data());
|
| 84 |
+
return r;
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
JNIEXPORT jdouble JNICALL Java_jp_duplex_app_Engine_soloRtf(JNIEnv *, jobject) { return g_eng ? g_eng->solo_rtf() : -1; }
|
| 88 |
+
|
| 89 |
+
JNIEXPORT void JNICALL Java_jp_duplex_app_Engine_nativeResetStats(JNIEnv *, jobject) { if (g_eng) g_eng->reset_stats(); }
|
| 90 |
+
}
|
source/app/src/main/cpp/duplex/engine_core.h
ADDED
|
@@ -0,0 +1,711 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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OX)→ スピーカー
|
| 4 |
+
// ・うなづき AI(VAP)… 相手ターンの時だけ相づちを鳴らす
|
| 5 |
+
// ・途中の認識結果を更新し、終話と割り込みを判断する
|
| 6 |
+
// マイクとスピーカーは audio_io.h の形で、スマホ(Oboe)と Windows(WASAPI)が用意する
|
| 7 |
+
// 画面への知らせは set_event_sink() で受け取り先を決める(スマホは Kotlin、Windows は画面)
|
| 8 |
+
// この見出しは 1 つのファイルからだけ読み込む(中身を無名の名前空間に置いているため)
|
| 9 |
+
#pragma once
|
| 10 |
+
|
| 11 |
+
#include <algorithm>
|
| 12 |
+
#include <atomic>
|
| 13 |
+
#include <cmath>
|
| 14 |
+
#include <condition_variable>
|
| 15 |
+
#include <deque>
|
| 16 |
+
#include <fstream>
|
| 17 |
+
#include <functional>
|
| 18 |
+
#include <memory>
|
| 19 |
+
#include <mutex>
|
| 20 |
+
#include <thread>
|
| 21 |
+
|
| 22 |
+
#include "audio_io.h"
|
| 23 |
+
#include "common.h"
|
| 24 |
+
#include "llm.h"
|
| 25 |
+
#include "models.h"
|
| 26 |
+
#include "moonshine_asr.h"
|
| 27 |
+
#include "tts.h"
|
| 28 |
+
|
| 29 |
+
namespace {
|
| 30 |
+
|
| 31 |
+
// ---- 決まりの数(PC 版と同じ)
|
| 32 |
+
constexpr int MIN_UTT = 3; // 相づちの言葉を除いてこの文字数より短い発話には返事をしない
|
| 33 |
+
constexpr float GATE = 0.002f; // 直前 0.4 秒の音がこれより小さいときに出た文字は捨てる
|
| 34 |
+
constexpr double OTHER_GAP = 0.6;
|
| 35 |
+
constexpr int INTERRUPTION_CHARS = 5;
|
| 36 |
+
constexpr int ST_WAIT = 5; // 相手の最後の文字から 0.2 秒黙ったら Smart Turn に聞く
|
| 37 |
+
constexpr float BC_TH = 0.5f;
|
| 38 |
+
constexpr double BC_COOL = 2.5;
|
| 39 |
+
|
| 40 |
+
struct InterruptionHold {
|
| 41 |
+
double since = -1;
|
| 42 |
+
|
| 43 |
+
bool observe(size_t chars, double now) {
|
| 44 |
+
if (chars < INTERRUPTION_CHARS) {
|
| 45 |
+
since = -1;
|
| 46 |
+
return false;
|
| 47 |
+
}
|
| 48 |
+
if (since < 0) since = now;
|
| 49 |
+
return now >= since + 0.4;
|
| 50 |
+
}
|
| 51 |
+
};
|
| 52 |
+
struct Params {
|
| 53 |
+
float end_th = 0.7f, fallback = 1.5f;
|
| 54 |
+
int max_sent = 2, voice = 3;
|
| 55 |
+
bool aizuchi = true, aec = true, thinking = false;
|
| 56 |
+
std::string system;
|
| 57 |
+
};
|
| 58 |
+
|
| 59 |
+
// ---------------- スピーカー(鳴らした音の表を覚えておく = 自分の声を見分けるため)
|
| 60 |
+
struct Player {
|
| 61 |
+
std::mutex mu;
|
| 62 |
+
std::deque<std::shared_ptr<Speech>> q;
|
| 63 |
+
std::shared_ptr<Speech> cur;
|
| 64 |
+
size_t pos = 0;
|
| 65 |
+
std::vector<std::pair<double, std::shared_ptr<Speech>>> spoken; // (鳴らし始めた時刻, 音)
|
| 66 |
+
std::function<void(const Speech &)> on_start;
|
| 67 |
+
|
| 68 |
+
std::atomic<uint64_t> gap_count{0}, gap_frames{0};
|
| 69 |
+
std::atomic<int> output_xruns{-1};
|
| 70 |
+
|
| 71 |
+
uint64_t pending_silence = 0;
|
| 72 |
+
bool tracking = false;
|
| 73 |
+
std::atomic<uint64_t> text_wait{0}, audio_wait{0}, worst_gap{0};
|
| 74 |
+
|
| 75 |
+
void add(std::shared_ptr<Speech> s) { std::lock_guard<std::mutex> lk(mu); q.push_back(std::move(s)); }
|
| 76 |
+
bool busy() { std::lock_guard<std::mutex> lk(mu); return cur || !q.empty(); }
|
| 77 |
+
void kill() { std::lock_guard<std::mutex> lk(mu); q.clear(); cur.reset(); tracking = false; pending_silence = 0; }
|
| 78 |
+
void clear_spoken() { std::lock_guard<std::mutex> lk(mu); spoken.clear(); pending_silence = 0; tracking = false; }
|
| 79 |
+
|
| 80 |
+
bool is_recent_echo(const std::string &text, double now) {
|
| 81 |
+
auto normalize = [](const std::string &value) {
|
| 82 |
+
std::u32string output;
|
| 83 |
+
for (char32_t c : to_u32(value))
|
| 84 |
+
if (std::u32string_view(U" 、。!?,.!? \r\n\t").find(c) == std::u32string_view::npos)
|
| 85 |
+
output.push_back(kata2hira(c));
|
| 86 |
+
return norm(output);
|
| 87 |
+
};
|
| 88 |
+
const auto candidate = normalize(text);
|
| 89 |
+
if (candidate.size() < 2) return false;
|
| 90 |
+
decltype(spoken) recent;
|
| 91 |
+
recent.reserve(64);
|
| 92 |
+
{
|
| 93 |
+
std::lock_guard<std::mutex> lock(mu);
|
| 94 |
+
recent.assign(spoken.begin(), spoken.end());
|
| 95 |
+
}
|
| 96 |
+
for (const auto &[start, speech] : recent) {
|
| 97 |
+
const double duration = (double)speech->pcm.size() / speech->sr;
|
| 98 |
+
if (now >= start && now <= start + duration + 1.5 &&
|
| 99 |
+
normalize(speech->text).find(candidate) != std::u32string::npos) return true;
|
| 100 |
+
}
|
| 101 |
+
return false;
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
void fill(float *out, int n, int sr) {
|
| 105 |
+
std::shared_ptr<Speech> started;
|
| 106 |
+
{
|
| 107 |
+
std::lock_guard<std::mutex> lk(mu);
|
| 108 |
+
int i = 0;
|
| 109 |
+
while (i < n) {
|
| 110 |
+
if (!cur) {
|
| 111 |
+
if (q.empty()) break;
|
| 112 |
+
cur = q.front();
|
| 113 |
+
q.pop_front();
|
| 114 |
+
if (tracking && pending_silence && !cur->aizuchi) {
|
| 115 |
+
const double now = now_sec() + double(i) / sr;
|
| 116 |
+
const double gap_start = now - double(pending_silence) / sr;
|
| 117 |
+
const auto text_frames = static_cast<uint64_t>(std::clamp(
|
| 118 |
+
(cur->clause_ready - gap_start) * sr, 0.0, double(pending_silence)));
|
| 119 |
+
++gap_count;
|
| 120 |
+
gap_frames += pending_silence;
|
| 121 |
+
text_wait += text_frames;
|
| 122 |
+
audio_wait += pending_silence - text_frames;
|
| 123 |
+
worst_gap.store(std::max(worst_gap.load(), pending_silence));
|
| 124 |
+
}
|
| 125 |
+
pending_silence = 0;
|
| 126 |
+
tracking = !cur->aizuchi;
|
| 127 |
+
pos = 0;
|
| 128 |
+
spoken.emplace_back(now_sec() + (double) i / sr, cur);
|
| 129 |
+
if (spoken.size() > 64) spoken.erase(spoken.begin());
|
| 130 |
+
if (!cur->continuation) started = cur;
|
| 131 |
+
}
|
| 132 |
+
size_t m = std::min<size_t>(n - i, cur->pcm.size() - pos);
|
| 133 |
+
std::copy(cur->pcm.begin() + pos, cur->pcm.begin() + pos + m, out + i);
|
| 134 |
+
i += (int) m;
|
| 135 |
+
pos += m;
|
| 136 |
+
if (pos >= cur->pcm.size()) cur.reset();
|
| 137 |
+
}
|
| 138 |
+
if (tracking) pending_silence += n - i;
|
| 139 |
+
std::fill(out + i, out + n, 0.0f);
|
| 140 |
+
}
|
| 141 |
+
if (started && on_start) on_start(*started);
|
| 142 |
+
}
|
| 143 |
+
};
|
| 144 |
+
|
| 145 |
+
// ---------------- 画面へ知らせる(受け取り先はスマホ版・Windows 版それぞれが決める)
|
| 146 |
+
enum Ev { EV_STATE = 0, EV_USER_PARTIAL = 1, EV_USER_FINAL = 2, EV_AI_SENTENCE = 3, EV_AI_DONE = 4, EV_AIZUCHI = 5, EV_KILL = 6, EV_INFO = 7 };
|
| 147 |
+
|
| 148 |
+
using EventSink = std::function<void(int kind, const std::string &text, double v)>;
|
| 149 |
+
EventSink g_sink;
|
| 150 |
+
void set_event_sink(EventSink sink) { g_sink = std::move(sink); }
|
| 151 |
+
|
| 152 |
+
void emit(int kind, const std::string &text, double v = 0) {
|
| 153 |
+
if (kind == EV_INFO) LOGI("知らせ: %s", text.c_str()); // 画面ではすぐ消えるので記録にも残す
|
| 154 |
+
if (g_sink) g_sink(kind, text, v);
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
// ---------------- 声の文として読めるように整える(PC 版の on_sentence と同じ決まり)
|
| 158 |
+
bool is_jp(char32_t c) { return (c >= 0x3040 && c <= 0x30FF) || (c >= 0x4E00 && c <= 0x9FFF) || c == U'々'; }
|
| 159 |
+
bool is_ascii_alpha(char32_t c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); }
|
| 160 |
+
|
| 161 |
+
bool clean_sentence(const std::string &in, std::string &out) {
|
| 162 |
+
std::u32string s = to_u32(in), r;
|
| 163 |
+
static const std::u32string keep = U"、。!?!?ー〜…";
|
| 164 |
+
bool hangul = false;
|
| 165 |
+
for (char32_t c : s) {
|
| 166 |
+
if (c >= 0xAC00 && c <= 0xD7AF) hangul = true;
|
| 167 |
+
bool word = is_jp(c) || (c >= '0' && c <= '9') || is_ascii_alpha(c) || (c >= U'0' && c <= U'9') || c == '_';
|
| 168 |
+
if (word || keep.find(c) != std::u32string::npos) r.push_back(c);
|
| 169 |
+
}
|
| 170 |
+
if (hangul) return false;
|
| 171 |
+
bool any = false;
|
| 172 |
+
for (char32_t c : r) if (is_jp(c) || (c >= '0' && c <= '9') || is_ascii_alpha(c)) any = true;
|
| 173 |
+
if (!any) return false;
|
| 174 |
+
bool eng = false;
|
| 175 |
+
for (char32_t c : r) if (is_ascii_alpha(c)) eng = true;
|
| 176 |
+
if (eng) {
|
| 177 |
+
std::u32string r2;
|
| 178 |
+
for (char32_t c : r) if (!is_ascii_alpha(c)) r2.push_back(c);
|
| 179 |
+
int jp = 0;
|
| 180 |
+
for (char32_t c : r2) if (is_jp(c)) jp++;
|
| 181 |
+
if (jp < 3) return false;
|
| 182 |
+
r = r2;
|
| 183 |
+
}
|
| 184 |
+
out = to_u8(r);
|
| 185 |
+
return true;
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
// ======================================== 会話の中身
|
| 189 |
+
class Engine {
|
| 190 |
+
public:
|
| 191 |
+
std::unique_ptr<Ort::Env> env;
|
| 192 |
+
std::unique_ptr<MoonshineAsr> asr;
|
| 193 |
+
std::unique_ptr<SmartTurn> turn;
|
| 194 |
+
std::unique_ptr<Vap> vap;
|
| 195 |
+
Tts tts;
|
| 196 |
+
Player player;
|
| 197 |
+
Params prm;
|
| 198 |
+
std::mutex prm_mu;
|
| 199 |
+
std::map<std::string, std::shared_ptr<Speech>> aiz;
|
| 200 |
+
|
| 201 |
+
// 統計(Kotlin の計測画面へ)
|
| 202 |
+
std::mutex stat_mu;
|
| 203 |
+
std::vector<double> end_to_voice, barge_stop;
|
| 204 |
+
std::string measured_clause;
|
| 205 |
+
int measured_style = 3;
|
| 206 |
+
double clause_rtf = -1;
|
| 207 |
+
double last_judge = 0, last_llm = 0, last_voice = 0, llm_tps = 0;
|
| 208 |
+
int n_un = 0, n_hee = 0, n_turns = 0;
|
| 209 |
+
|
| 210 |
+
std::string init(const std::string &mdir, const std::string &asr_dir) {
|
| 211 |
+
try {
|
| 212 |
+
env = std::make_unique<Ort::Env>(ORT_LOGGING_LEVEL_WARNING, "duplex");
|
| 213 |
+
asr = std::make_unique<MoonshineAsr>(asr_dir);
|
| 214 |
+
turn = std::make_unique<SmartTurn>(*env, mdir, 2);
|
| 215 |
+
vap.reset();
|
| 216 |
+
if (std::ifstream(mdir + "/vap_enc.onnx") && std::ifstream(mdir + "/vap_ar.onnx"))
|
| 217 |
+
vap = std::make_unique<Vap>(*env, mdir, 1);
|
| 218 |
+
} catch (const std::exception &e) {
|
| 219 |
+
return std::string("部品を読み込めません: ") + e.what();
|
| 220 |
+
}
|
| 221 |
+
player.on_start = [this](const Speech &s) { on_play_start(s); };
|
| 222 |
+
return "";
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
// 声(VOICEVOX)は使う人が選んだものを読み込む。なければ返事は文字だけで出す
|
| 226 |
+
std::string init_voice(const std::string &core, const std::string &ort, const std::string &vvm, const std::string &dic, int threads) {
|
| 227 |
+
std::string err;
|
| 228 |
+
if (!tts.init(core, ort, vvm, dic, threads, err)) return err;
|
| 229 |
+
prepare_aizuchi();
|
| 230 |
+
return "";
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
// ---------------- マイクとスピーカー(形は audio_io.h。中身はスマホ版・Windows 版それぞれ)
|
| 234 |
+
std::unique_ptr<AudioIO> audio;
|
| 235 |
+
std::mutex amu;
|
| 236 |
+
std::condition_variable acv;
|
| 237 |
+
std::vector<float> abuf;
|
| 238 |
+
std::atomic<bool> running{false};
|
| 239 |
+
std::thread proc;
|
| 240 |
+
|
| 241 |
+
std::string start() {
|
| 242 |
+
if (running) return "";
|
| 243 |
+
bool aec;
|
| 244 |
+
{ std::lock_guard<std::mutex> lk(prm_mu); aec = prm.aec; }
|
| 245 |
+
audio = make_audio_io();
|
| 246 |
+
audio->on_input = [this](const float *data, int n) { // マイク: 16kHz・1ch の音をためる
|
| 247 |
+
std::lock_guard<std::mutex> lk(amu);
|
| 248 |
+
abuf.insert(abuf.end(), data, data + n);
|
| 249 |
+
acv.notify_one();
|
| 250 |
+
};
|
| 251 |
+
audio->on_output = [this](float *data, int n, int sr) { player.fill(data, n, sr); }; // スピーカー: 24kHz・1ch
|
| 252 |
+
const std::string opened = audio->open(aec);
|
| 253 |
+
if (!opened.empty()) { audio.reset(); return opened; }
|
| 254 |
+
if (!audio->note.empty()) emit(EV_INFO, audio->note);
|
| 255 |
+
reset_turn();
|
| 256 |
+
player.gap_count = 0;
|
| 257 |
+
player.gap_frames = 0;
|
| 258 |
+
player.text_wait = 0; player.audio_wait = 0; player.worst_gap = 0;
|
| 259 |
+
player.output_xruns = -1;
|
| 260 |
+
running = true;
|
| 261 |
+
proc = std::thread([this] { loop(); });
|
| 262 |
+
audio->start();
|
| 263 |
+
set_state("聞いています", "相手のターン");
|
| 264 |
+
return "";
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
void stop() {
|
| 268 |
+
if (!running) return;
|
| 269 |
+
running = false;
|
| 270 |
+
acv.notify_all();
|
| 271 |
+
if (audio) audio->stop_input();
|
| 272 |
+
if (proc.joinable()) proc.join();
|
| 273 |
+
if (audio) { audio->stop(); audio.reset(); }
|
| 274 |
+
{
|
| 275 |
+
std::lock_guard<std::mutex> lock(mmu);
|
| 276 |
+
kill(false);
|
| 277 |
+
}
|
| 278 |
+
set_state("止まっています", "");
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
// ---------------- 会話の状態
|
| 282 |
+
enum Mode { LISTEN, THINK, SPEAK } mode = LISTEN;
|
| 283 |
+
std::mutex mmu; // mode と下の値を守る
|
| 284 |
+
InterruptionHold interruption;
|
| 285 |
+
std::string heard;
|
| 286 |
+
bool asked = false;
|
| 287 |
+
bool rejected_echo = false;
|
| 288 |
+
double last_bc = 0, last_heard = 0, last_user_char = 0;
|
| 289 |
+
double speech_start = 0;
|
| 290 |
+
int silent_frames = 0;
|
| 291 |
+
|
| 292 |
+
std::vector<std::pair<std::string, std::string>> history;
|
| 293 |
+
std::shared_ptr<std::atomic<bool>> reply_stop;
|
| 294 |
+
std::shared_ptr<std::atomic<bool>> reply_done;
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
// 返事の時間を測る
|
| 298 |
+
double t_end = 0, t_fire = 0, t_first_sentence = 0;
|
| 299 |
+
bool waiting_first_voice = false;
|
| 300 |
+
|
| 301 |
+
void reset_input() {
|
| 302 |
+
interruption = {};
|
| 303 |
+
asr->reset();
|
| 304 |
+
heard.clear();
|
| 305 |
+
asked = false;
|
| 306 |
+
rejected_echo = false;
|
| 307 |
+
speech_start = 0;
|
| 308 |
+
silent_frames = 0;
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
void reset_turn() {
|
| 312 |
+
std::lock_guard<std::mutex> lk(mmu);
|
| 313 |
+
mode = LISTEN;
|
| 314 |
+
turn->reset();
|
| 315 |
+
reset_input();
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
void set_state(const std::string &s, const std::string &turn_label) { emit(EV_STATE, s + "\n" + turn_label); }
|
| 319 |
+
|
| 320 |
+
// 音の流れ(すぐ返さないといけない所)から呼ばれるので、ここでは書き留めるだけ。画面への知らせは loop() で出す
|
| 321 |
+
std::mutex pend_mu;
|
| 322 |
+
std::vector<std::string> pend_sentences;
|
| 323 |
+
|
| 324 |
+
void on_play_start(const Speech &s) {
|
| 325 |
+
if (s.aizuchi || s.continuation) return;
|
| 326 |
+
{ std::lock_guard<std::mutex> pl(pend_mu); pend_sentences.push_back(s.text); }
|
| 327 |
+
std::lock_guard<std::mutex> lk(stat_mu);
|
| 328 |
+
if (waiting_first_voice) {
|
| 329 |
+
waiting_first_voice = false;
|
| 330 |
+
double tv = now_sec();
|
| 331 |
+
end_to_voice.push_back(tv - t_end);
|
| 332 |
+
last_judge = t_fire - t_end;
|
| 333 |
+
last_llm = t_first_sentence - t_fire;
|
| 334 |
+
last_voice = tv - t_first_sentence;
|
| 335 |
+
}
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
void kill(bool log_it = true) {
|
| 339 |
+
if (reply_stop) *reply_stop = true;
|
| 340 |
+
llm_stop();
|
| 341 |
+
player.kill();
|
| 342 |
+
last_bc = now_sec();
|
| 343 |
+
if (log_it) emit(EV_KILL, "会話ぶっ殺し機: 相手が話し始めたので止めた");
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
// ---------------- 返事を作る(別の流れで動かす)
|
| 347 |
+
void start_reply(const std::string &user_text) {
|
| 348 |
+
Params p;
|
| 349 |
+
{ std::lock_guard<std::mutex> lk(prm_mu); p = prm; }
|
| 350 |
+
history.emplace_back("user", user_text);
|
| 351 |
+
mode = THINK;
|
| 352 |
+
last_bc = now_sec();
|
| 353 |
+
player.clear_spoken();
|
| 354 |
+
auto stop = std::make_shared<std::atomic<bool>>(false);
|
| 355 |
+
auto done = std::make_shared<std::atomic<bool>>(false);
|
| 356 |
+
reply_stop = stop;
|
| 357 |
+
reply_done = done;
|
| 358 |
+
set_state("考えています", "AI のターン");
|
| 359 |
+
std::vector<std::pair<std::string, std::string>> turns;
|
| 360 |
+
turns.emplace_back("system", p.system);
|
| 361 |
+
turns.insert(turns.end(), history.begin(), history.end());
|
| 362 |
+
std::thread([this, turns, stop, done, p] {
|
| 363 |
+
std::string buf, said;
|
| 364 |
+
int sentences = 0;
|
| 365 |
+
bool sentence_has_content = false;
|
| 366 |
+
bool queued_voice = false;
|
| 367 |
+
const bool split_at_comma = tts.ready();
|
| 368 |
+
double t0 = now_sec();
|
| 369 |
+
int pieces = 0;
|
| 370 |
+
std::mutex queue_mu;
|
| 371 |
+
std::condition_variable queue_changed;
|
| 372 |
+
struct Clause { std::string text; double ready; };
|
| 373 |
+
std::deque<Clause> clauses;
|
| 374 |
+
bool generation_finished = false;
|
| 375 |
+
|
| 376 |
+
auto submit = [&](const std::string &raw) -> bool {
|
| 377 |
+
std::string text;
|
| 378 |
+
if (*stop || !clean_sentence(raw, text)) return false;
|
| 379 |
+
{
|
| 380 |
+
std::lock_guard<std::mutex> lock(queue_mu);
|
| 381 |
+
clauses.push_back({std::move(text), now_sec()});
|
| 382 |
+
}
|
| 383 |
+
queue_changed.notify_one();
|
| 384 |
+
return true;
|
| 385 |
+
};
|
| 386 |
+
|
| 387 |
+
auto speak = [&](const Clause &clause) {
|
| 388 |
+
const auto &text = clause.text;
|
| 389 |
+
if (*stop) return;
|
| 390 |
+
Speech audio;
|
| 391 |
+
std::string err;
|
| 392 |
+
const double synthesis_started = now_sec();
|
| 393 |
+
size_t samples = 0;
|
| 394 |
+
size_t block_index = 0;
|
| 395 |
+
auto publish = [&](Speech &&block) {
|
| 396 |
+
block.clause_ready = clause.ready;
|
| 397 |
+
samples += block.pcm.size();
|
| 398 |
+
std::lock_guard<std::mutex> mode_lock(mmu);
|
| 399 |
+
if (*stop) return false;
|
| 400 |
+
if (!queued_voice) {
|
| 401 |
+
std::lock_guard<std::mutex> lock(stat_mu);
|
| 402 |
+
t_first_sentence = synthesis_started;
|
| 403 |
+
queued_voice = true;
|
| 404 |
+
}
|
| 405 |
+
const size_t frames = block.pcm.size();
|
| 406 |
+
player.add(std::make_shared<Speech>(std::move(block)));
|
| 407 |
+
LOGI("VoiceBlock clause=%.6f synth_start=%.6f queued=%.6f index=%zu frames=%zu", clause.ready, synthesis_started, now_sec(), block_index++, frames);
|
| 408 |
+
if (mode == THINK) { mode = SPEAK; set_state("話しています", "AI のターン"); }
|
| 409 |
+
return true;
|
| 410 |
+
};
|
| 411 |
+
|
| 412 |
+
const auto cancelled = [&] { return stop->load(); };
|
| 413 |
+
const bool synthesized = tts.ready() &&
|
| 414 |
+
tts.speak(text, p.voice, audio, err, publish, cancelled);
|
| 415 |
+
|
| 416 |
+
if (*stop) return;
|
| 417 |
+
if (!err.empty()) emit(EV_INFO, "声を作れません: " + err);
|
| 418 |
+
if (synthesized && err.empty() && samples) {
|
| 419 |
+
std::lock_guard<std::mutex> lock(stat_mu);
|
| 420 |
+
measured_clause = text;
|
| 421 |
+
measured_style = p.voice;
|
| 422 |
+
clause_rtf = (now_sec() - synthesis_started) * 24000 / samples;
|
| 423 |
+
}
|
| 424 |
+
if (!synthesized) emit(EV_AI_SENTENCE, text);
|
| 425 |
+
said += text;
|
| 426 |
+
};
|
| 427 |
+
|
| 428 |
+
std::thread voice_worker([&] {
|
| 429 |
+
for (;;) {
|
| 430 |
+
Clause clause;
|
| 431 |
+
{
|
| 432 |
+
std::unique_lock<std::mutex> lock(queue_mu);
|
| 433 |
+
queue_changed.wait(lock, [&] { return *stop || generation_finished || !clauses.empty(); });
|
| 434 |
+
if (*stop || clauses.empty()) return;
|
| 435 |
+
clause = std::move(clauses.front());
|
| 436 |
+
clauses.pop_front();
|
| 437 |
+
}
|
| 438 |
+
speak(clause);
|
| 439 |
+
}
|
| 440 |
+
});
|
| 441 |
+
|
| 442 |
+
int blank_run = 0;
|
| 443 |
+
const std::u32string_view sentence_ends = U"。!?!?\n";
|
| 444 |
+
std::string full = llm_reply(turns, 120, 0.7f, [&](const std::string &piece) {
|
| 445 |
+
if (*stop) return false;
|
| 446 |
+
pieces++;
|
| 447 |
+
if (piece.find_first_not_of(" \n\r\t") == std::string::npos) {
|
| 448 |
+
if (sentences > 0 && ++blank_run >= 3) return false;
|
| 449 |
+
} else blank_run = 0;
|
| 450 |
+
buf += piece;
|
| 451 |
+
while (sentences < p.max_sent) {
|
| 452 |
+
std::u32string text = to_u32(buf);
|
| 453 |
+
const size_t end = text.find_first_of(sentence_ends);
|
| 454 |
+
const size_t comma = split_at_comma ? text.find(U'、') : std::u32string::npos;
|
| 455 |
+
const size_t cut = std::min(end, comma);
|
| 456 |
+
if (cut == std::u32string::npos) break;
|
| 457 |
+
const bool submitted = submit(to_u8(text.substr(0, cut + 1)));
|
| 458 |
+
buf = to_u8(text.substr(cut + 1));
|
| 459 |
+
if (submitted && cut == comma) LOGI("VOICEVOX clause submitted at Japanese comma");
|
| 460 |
+
sentence_has_content = sentence_has_content || submitted;
|
| 461 |
+
if (cut == end) {
|
| 462 |
+
if (sentence_has_content) sentences++;
|
| 463 |
+
sentence_has_content = false;
|
| 464 |
+
}
|
| 465 |
+
if (*stop) return false;
|
| 466 |
+
}
|
| 467 |
+
return sentences < p.max_sent;
|
| 468 |
+
}, p.thinking, /*japanese_only=*/true); // 英語の返事は声にできず捨てられるので、最初から日本語で作らせる
|
| 469 |
+
double dt = now_sec() - t0;
|
| 470 |
+
LOGI("LLM の返事(%.2f 秒): %s", now_sec() - t0, full.c_str());
|
| 471 |
+
if (sentences < p.max_sent && !*stop) submit(buf);
|
| 472 |
+
{
|
| 473 |
+
std::lock_guard<std::mutex> lock(queue_mu);
|
| 474 |
+
generation_finished = true;
|
| 475 |
+
}
|
| 476 |
+
queue_changed.notify_one();
|
| 477 |
+
voice_worker.join();
|
| 478 |
+
|
| 479 |
+
{
|
| 480 |
+
std::lock_guard<std::mutex> lk(stat_mu);
|
| 481 |
+
if (dt > 0 && pieces > 1) llm_tps = pieces / dt;
|
| 482 |
+
n_turns++;
|
| 483 |
+
}
|
| 484 |
+
{
|
| 485 |
+
std::lock_guard<std::mutex> lk(mmu);
|
| 486 |
+
if (reply_stop == stop && !said.empty()) history.emplace_back("assistant", said);
|
| 487 |
+
if (history.size() > 12) history.erase(history.begin(), history.end() - 12); // 直近 6 往復だけ覚えておく
|
| 488 |
+
}
|
| 489 |
+
if (said.empty() && !*stop) emit(EV_INFO, "LLM の返事が声になりませんでした: " + full.substr(0, 200));
|
| 490 |
+
if (!*stop) emit(EV_AI_DONE, "");
|
| 491 |
+
*done = true;
|
| 492 |
+
}).detach();
|
| 493 |
+
}
|
| 494 |
+
|
| 495 |
+
// Moonshine returns a revisable transcript, not a stream of committed characters.
|
| 496 |
+
void frame(const float *x) {
|
| 497 |
+
const double t = now_sec();
|
| 498 |
+
float power = 0;
|
| 499 |
+
for (int i = 0; i < 640; i++) power += x[i] * x[i];
|
| 500 |
+
const bool audible = sqrtf(power / 640) >= GATE;
|
| 501 |
+
turn->push(x, 640);
|
| 502 |
+
if (vap) {
|
| 503 |
+
bool listening, enabled;
|
| 504 |
+
{ std::lock_guard<std::mutex> lock(mmu); listening = mode == LISTEN; }
|
| 505 |
+
{ std::lock_guard<std::mutex> lock(prm_mu); enabled = prm.aizuchi; }
|
| 506 |
+
vap->push(x, 640, listening && enabled);
|
| 507 |
+
}
|
| 508 |
+
std::lock_guard<std::mutex> lock(mmu);
|
| 509 |
+
auto update = asr->push(x);
|
| 510 |
+
if (audible) {
|
| 511 |
+
if (speech_start == 0) speech_start = t;
|
| 512 |
+
last_user_char = t;
|
| 513 |
+
silent_frames = 0;
|
| 514 |
+
asked = false;
|
| 515 |
+
} else {
|
| 516 |
+
++silent_frames;
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
Params p;
|
| 520 |
+
{ std::lock_guard<std::mutex> pl(prm_mu); p = prm; }
|
| 521 |
+
if (update && speech_start > 0 && *update != heard) {
|
| 522 |
+
rejected_echo = player.is_recent_echo(*update, t);
|
| 523 |
+
heard = std::move(*update);
|
| 524 |
+
if (!rejected_echo && !heard.empty()) last_heard = t;
|
| 525 |
+
if (mode == LISTEN) emit(EV_USER_PARTIAL, rejected_echo ? "" : heard);
|
| 526 |
+
}
|
| 527 |
+
const auto words = rejected_echo ? std::u32string{} : other_chars(to_u32(heard));
|
| 528 |
+
const size_t chars = words.size();
|
| 529 |
+
|
| 530 |
+
if (mode != LISTEN) {
|
| 531 |
+
if (update && speech_start > 0 && interruption.observe(chars, t)) {
|
| 532 |
+
LOGI("Interruption confirmed: heard=%s", heard.c_str());
|
| 533 |
+
{
|
| 534 |
+
std::lock_guard<std::mutex> sl(stat_mu);
|
| 535 |
+
if (speech_start > 0) barge_stop.push_back(t - speech_start);
|
| 536 |
+
waiting_first_voice = false;
|
| 537 |
+
}
|
| 538 |
+
kill();
|
| 539 |
+
mode = LISTEN;
|
| 540 |
+
set_state("聞いています", "相手のターン");
|
| 541 |
+
emit(EV_USER_PARTIAL, heard);
|
| 542 |
+
} else if (reply_done && *reply_done && !player.busy()) {
|
| 543 |
+
mode = LISTEN;
|
| 544 |
+
if (chars == 0 || t - last_user_char >= OTHER_GAP) {
|
| 545 |
+
reset_input();
|
| 546 |
+
turn->reset();
|
| 547 |
+
} else {
|
| 548 |
+
emit(EV_USER_PARTIAL, heard);
|
| 549 |
+
}
|
| 550 |
+
set_state("聞いています", "相手のターン");
|
| 551 |
+
}
|
| 552 |
+
return;
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
if (chars >= MIN_UTT) {
|
| 556 |
+
bool end = silent_frames >= (int)(p.fallback / 0.04f);
|
| 557 |
+
if (!end && silent_frames >= ST_WAIT && !asked) {
|
| 558 |
+
asked = true;
|
| 559 |
+
end = turn->predict() > p.end_th;
|
| 560 |
+
}
|
| 561 |
+
if (end) {
|
| 562 |
+
// 先頭の相づち(「うんうん、」など)は取り除いてから LLM に送る・画面に出す(数えるときに除いていたものと同じ言葉)
|
| 563 |
+
std::string text = strip_leading_ack(heard);
|
| 564 |
+
if (text.empty()) text = heard;
|
| 565 |
+
reset_input();
|
| 566 |
+
turn->reset();
|
| 567 |
+
{
|
| 568 |
+
std::lock_guard<std::mutex> sl(stat_mu);
|
| 569 |
+
t_end = last_user_char;
|
| 570 |
+
t_fire = t;
|
| 571 |
+
waiting_first_voice = true;
|
| 572 |
+
}
|
| 573 |
+
emit(EV_USER_FINAL, text, t - last_user_char);
|
| 574 |
+
start_reply(text);
|
| 575 |
+
return;
|
| 576 |
+
}
|
| 577 |
+
} else if (speech_start > 0 && silent_frames >= (int)(p.fallback / 0.04f)) {
|
| 578 |
+
reset_input();
|
| 579 |
+
emit(EV_USER_PARTIAL, "");
|
| 580 |
+
}
|
| 581 |
+
|
| 582 |
+
if (vap && p.aizuchi && !player.busy() && t - last_bc > BC_COOL && t - last_heard < 3.0) {
|
| 583 |
+
const char *kind = vap->emo > BC_TH ? "へー" : (vap->react > BC_TH ? "うん" : nullptr);
|
| 584 |
+
if (kind && aiz.count(kind)) {
|
| 585 |
+
player.add(aiz[kind]);
|
| 586 |
+
last_bc = t;
|
| 587 |
+
std::lock_guard<std::mutex> sl(stat_mu);
|
| 588 |
+
(std::string(kind) == "へー" ? n_hee : n_un)++;
|
| 589 |
+
emit(EV_AIZUCHI, kind);
|
| 590 |
+
}
|
| 591 |
+
}
|
| 592 |
+
}
|
| 593 |
+
|
| 594 |
+
void loop() {
|
| 595 |
+
uint64_t last_gaps = 0, last_frames = 0;
|
| 596 |
+
int last_xruns = -1;
|
| 597 |
+
double next_report = now_sec();
|
| 598 |
+
while (running) {
|
| 599 |
+
std::vector<float> got;
|
| 600 |
+
{
|
| 601 |
+
std::unique_lock<std::mutex> lk(amu);
|
| 602 |
+
acv.wait_for(lk, std::chrono::milliseconds(200), [this] { return abuf.size() >= 640 || !running; });
|
| 603 |
+
size_t n = abuf.size() / 640 * 640;
|
| 604 |
+
got.assign(abuf.begin(), abuf.begin() + n);
|
| 605 |
+
abuf.erase(abuf.begin(), abuf.begin() + n);
|
| 606 |
+
}
|
| 607 |
+
for (size_t i = 0; i + 640 <= got.size() && running; i += 640) frame(got.data() + i); // たまっていてもまとめて取り返す
|
| 608 |
+
const double now = now_sec();
|
| 609 |
+
if (now >= next_report) {
|
| 610 |
+
next_report = now + 1.0;
|
| 611 |
+
const uint64_t gaps = player.gap_count.load();
|
| 612 |
+
const uint64_t frames = player.gap_frames.load();
|
| 613 |
+
const int xruns = audio ? audio->xruns() : -1;
|
| 614 |
+
player.output_xruns = xruns;
|
| 615 |
+
if (gaps != last_gaps || frames != last_frames || xruns != last_xruns) {
|
| 616 |
+
LOGI("Playback: queue gaps=%llu, missing frames=%llu, output xruns=%d (-1 unavailable)",
|
| 617 |
+
(unsigned long long) gaps, (unsigned long long) frames, xruns);
|
| 618 |
+
last_gaps = gaps;
|
| 619 |
+
last_frames = frames;
|
| 620 |
+
last_xruns = xruns;
|
| 621 |
+
}
|
| 622 |
+
}
|
| 623 |
+
std::vector<std::string> ps;
|
| 624 |
+
{ std::lock_guard<std::mutex> pl(pend_mu); ps.swap(pend_sentences); }
|
| 625 |
+
for (auto &s : ps) emit(EV_AI_SENTENCE, s);
|
| 626 |
+
}
|
| 627 |
+
}
|
| 628 |
+
|
| 629 |
+
// 「文字で試す」: 聞き取りの代わりに文字を入れる
|
| 630 |
+
void say(const std::string &text) {
|
| 631 |
+
std::lock_guard<std::mutex> lk(mmu);
|
| 632 |
+
if (mode != LISTEN) kill();
|
| 633 |
+
reset_input();
|
| 634 |
+
turn->reset();
|
| 635 |
+
{
|
| 636 |
+
std::lock_guard<std::mutex> sl(stat_mu);
|
| 637 |
+
t_end = t_fire = now_sec();
|
| 638 |
+
waiting_first_voice = true;
|
| 639 |
+
}
|
| 640 |
+
emit(EV_USER_FINAL, text, 0);
|
| 641 |
+
start_reply(text);
|
| 642 |
+
}
|
| 643 |
+
|
| 644 |
+
void prepare_aizuchi() {
|
| 645 |
+
Params p;
|
| 646 |
+
{ std::lock_guard<std::mutex> lk(prm_mu); p = prm; }
|
| 647 |
+
// 声を作る間は鍵を持たない(時間がかかるため)。できた声を一覧に入れるときだけ、会話の流れ(frame)と同じ鍵を持つ
|
| 648 |
+
for (const char *k : {"うん", "へー"}) {
|
| 649 |
+
auto s = std::make_shared<Speech>();
|
| 650 |
+
std::string err;
|
| 651 |
+
if (!tts.speak(k, p.voice, *s, err)) continue;
|
| 652 |
+
s->aizuchi = true;
|
| 653 |
+
std::lock_guard<std::mutex> lock(mmu);
|
| 654 |
+
aiz[k] = s;
|
| 655 |
+
}
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
// 設定を受け取る。声が変わったら相づちの声も作り直す(スマホ版・Windows 版で共通)
|
| 659 |
+
void set_params(const Params &next) {
|
| 660 |
+
bool voice_changed;
|
| 661 |
+
{
|
| 662 |
+
std::lock_guard<std::mutex> lk(prm_mu);
|
| 663 |
+
voice_changed = prm.voice != next.voice;
|
| 664 |
+
prm = next;
|
| 665 |
+
}
|
| 666 |
+
if (voice_changed) prepare_aizuchi();
|
| 667 |
+
}
|
| 668 |
+
|
| 669 |
+
// 計測: [話し終わり→声の真ん中, その回数, 割り込み→止まるの真ん中, その回数, 判断, LLM, 声, 聞き取りms, 判断ms, 相づちms,
|
| 670 |
+
// トークン/秒, うん, へー, 往復, 再生キュー切れ, 切れた量, 音切れ, 合成の速さ, 文章待ち, 文章確定後, 最長の途切れ]
|
| 671 |
+
std::vector<double> stats() {
|
| 672 |
+
std::lock_guard<std::mutex> lk(stat_mu);
|
| 673 |
+
auto med = [](std::vector<double> x) { if (x.empty()) return -1.0; std::sort(x.begin(), x.end()); return x[x.size() / 2]; };
|
| 674 |
+
return {med(end_to_voice), (double) end_to_voice.size(), med(barge_stop), (double) barge_stop.size(),
|
| 675 |
+
last_judge, last_llm, last_voice,
|
| 676 |
+
asr ? asr->last_ms.load() : 0, turn ? turn->last_ms : 0, vap ? vap->last_ms : 0,
|
| 677 |
+
llm_tps, (double) n_un, (double) n_hee, (double) n_turns,
|
| 678 |
+
(double) player.gap_count.load(), (double) player.gap_frames.load(), (double) player.output_xruns.load(), clause_rtf,
|
| 679 |
+
double(player.text_wait.load()), double(player.audio_wait.load()), double(player.worst_gap.load())};
|
| 680 |
+
}
|
| 681 |
+
|
| 682 |
+
// 会話していないときに、最後に話した文をもう一度だけ声にして、声を作る速さ(音声 1 秒あたりの秒数)を測る
|
| 683 |
+
double solo_rtf() {
|
| 684 |
+
if (running || !tts.ready()) return -1;
|
| 685 |
+
std::string text, error;
|
| 686 |
+
int style;
|
| 687 |
+
{
|
| 688 |
+
std::lock_guard<std::mutex> lock(stat_mu);
|
| 689 |
+
text = measured_clause;
|
| 690 |
+
style = measured_style;
|
| 691 |
+
}
|
| 692 |
+
if (text.empty()) return -1;
|
| 693 |
+
Speech fallback;
|
| 694 |
+
size_t samples = 0;
|
| 695 |
+
const double started = now_sec();
|
| 696 |
+
const bool ok = tts.speak(text, style, fallback, error, [&](Speech &&block) {
|
| 697 |
+
samples += block.pcm.size();
|
| 698 |
+
return !running;
|
| 699 |
+
});
|
| 700 |
+
return ok && error.empty() && samples ? (now_sec() - started) * 24000 / samples : -1;
|
| 701 |
+
}
|
| 702 |
+
|
| 703 |
+
void reset_stats() {
|
| 704 |
+
std::lock_guard<std::mutex> lk(stat_mu);
|
| 705 |
+
end_to_voice.clear(); barge_stop.clear();
|
| 706 |
+
last_judge = last_llm = last_voice = 0;
|
| 707 |
+
n_un = n_hee = n_turns = 0;
|
| 708 |
+
}
|
| 709 |
+
};
|
| 710 |
+
|
| 711 |
+
} // namespace
|
source/app/src/main/cpp/duplex/llm.h
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// llm.h — 会話の中身(C++)から LLM を使う
|
| 2 |
+
#pragma once
|
| 3 |
+
#include <functional>
|
| 4 |
+
#include <string>
|
| 5 |
+
#include <utility>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
#include <cstdio>
|
| 9 |
+
std::string llm_load(const std::string &path, int n_ctx, int n_threads);
|
| 10 |
+
// 開いたファイルから読む(Windows で日本語のフォルダ名を扱うため。読み込みが終わればファイルは閉じてよい)
|
| 11 |
+
std::string llm_load_file(FILE *file, int n_ctx, int n_threads);
|
| 12 |
+
bool llm_ready();
|
| 13 |
+
// turns: (役割, 中身)。on(文字) が false を返すと止める。戻り値: 作った返事全体(UTF-8)
|
| 14 |
+
// japanese_only: アルファベットを含む言葉を選べなくする(声で話す会話用。英語の返事は声にできず捨てられてしまうため)
|
| 15 |
+
std::string llm_reply(const std::vector<std::pair<std::string, std::string>> &turns, int max_tokens, float temp,
|
| 16 |
+
const std::function<bool(const std::string &)> &on, bool thinking = true,
|
| 17 |
+
bool japanese_only = false);
|
| 18 |
+
void llm_stop();
|
source/app/src/main/cpp/duplex/models.cpp
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// models.cpp — 話し終わり Smart Turn と相づち VAP
|
| 2 |
+
// 速くする工夫: FFT(pocketfft)/ メルの重みは 0 でない所だけ / 覚えは 2 組を交互に使って写さない / 入れ物は使い回す
|
| 3 |
+
#include "models.h"
|
| 4 |
+
|
| 5 |
+
#include <algorithm>
|
| 6 |
+
#include <cmath>
|
| 7 |
+
#include <complex>
|
| 8 |
+
#include <cstdio>
|
| 9 |
+
#include <numeric>
|
| 10 |
+
|
| 11 |
+
#include "common.h"
|
| 12 |
+
#include "pocketfft_hdronly.h"
|
| 13 |
+
#ifdef _WIN32
|
| 14 |
+
#define WIN32_LEAN_AND_MEAN
|
| 15 |
+
#define NOMINMAX
|
| 16 |
+
#include <windows.h>
|
| 17 |
+
#endif
|
| 18 |
+
|
| 19 |
+
namespace {
|
| 20 |
+
std::vector<float> read_f32(const std::string &path, size_t n) {
|
| 21 |
+
std::vector<float> v(n);
|
| 22 |
+
FILE *f = fopen(path.c_str(), "rb");
|
| 23 |
+
if (f) {
|
| 24 |
+
size_t got = fread(v.data(), 4, n, f);
|
| 25 |
+
fclose(f);
|
| 26 |
+
if (got != n) LOGE("表の大きさが違う: %s", path.c_str());
|
| 27 |
+
} else LOGE("表が開けない: %s", path.c_str());
|
| 28 |
+
return v;
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
Ort::MemoryInfo &mem() {
|
| 32 |
+
static Ort::MemoryInfo m = Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault);
|
| 33 |
+
return m;
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
Ort::Value tensor(std::vector<float> &v, std::vector<int64_t> shape) {
|
| 37 |
+
return Ort::Value::CreateTensor<float>(mem(), v.data(), v.size(), shape.data(), shape.size());
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
Ort::Value tensor_i64(int64_t *p) {
|
| 41 |
+
int64_t one = 1;
|
| 42 |
+
return Ort::Value::CreateTensor<int64_t>(mem(), p, 1, &one, 1);
|
| 43 |
+
}
|
| 44 |
+
} // namespace
|
| 45 |
+
|
| 46 |
+
std::unique_ptr<Ort::Session> open_session(Ort::Env &env, const std::string &path, int threads) {
|
| 47 |
+
Ort::SessionOptions so;
|
| 48 |
+
so.SetIntraOpNumThreads(threads);
|
| 49 |
+
so.SetInterOpNumThreads(1);
|
| 50 |
+
so.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL);
|
| 51 |
+
so.AddConfigEntry("session.intra_op.allow_spinning", "0"); // 待つ間に CPU を空回りさせない(LLM と取り合わない)
|
| 52 |
+
so.AddConfigEntry("session.inter_op.allow_spinning", "0");
|
| 53 |
+
#ifdef _WIN32
|
| 54 |
+
// Windows: ファイルの場所(UTF-8)を Windows の文字(wchar_t)に正しく直す。1 バイトずつ広げると日本語のフォルダ名が化ける
|
| 55 |
+
const int n = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
|
| 56 |
+
std::wstring wp(n > 0 ? n - 1 : 0, L'\0');
|
| 57 |
+
if (n > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wp.data(), n);
|
| 58 |
+
return std::make_unique<Ort::Session>(env, wp.c_str(), so);
|
| 59 |
+
#else
|
| 60 |
+
return std::make_unique<Ort::Session>(env, path.c_str(), so);
|
| 61 |
+
#endif
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
// ======================= FFT とメル
|
| 65 |
+
void PowerDft::power(const float *f, float *out) const { power_many(f, 1, out); }
|
| 66 |
+
|
| 67 |
+
void PowerDft::power_many(const float *frames, int n, float *out) const {
|
| 68 |
+
thread_local std::vector<std::complex<float>> spec;
|
| 69 |
+
spec.resize((size_t) n * 201);
|
| 70 |
+
pocketfft::shape_t shape{(size_t) n, 400};
|
| 71 |
+
pocketfft::stride_t sin_{(ptrdiff_t) (400 * sizeof(float)), (ptrdiff_t) sizeof(float)};
|
| 72 |
+
pocketfft::stride_t sout{(ptrdiff_t) (201 * sizeof(std::complex<float>)), (ptrdiff_t) sizeof(std::complex<float>)};
|
| 73 |
+
pocketfft::r2c(shape, sin_, sout, 1, pocketfft::FORWARD, frames, spec.data(), 1.0f);
|
| 74 |
+
for (size_t i = 0; i < (size_t) n * 201; i++) out[i] = std::norm(spec[i]);
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
void MelBank::set(std::vector<float> full) {
|
| 78 |
+
w = std::move(full);
|
| 79 |
+
lo.assign(80, 0);
|
| 80 |
+
hi.assign(80, 0);
|
| 81 |
+
for (int b = 0; b < 80; b++) {
|
| 82 |
+
int a = 201, z = 0;
|
| 83 |
+
for (int k = 0; k < 201; k++) if (w[b * 201 + k] != 0.0f) { a = std::min(a, k); z = k + 1; }
|
| 84 |
+
lo[b] = a < 201 ? a : 0;
|
| 85 |
+
hi[b] = z;
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
// ======================= 話し終わりの判断(Smart Turn)
|
| 90 |
+
static constexpr int N8 = 8 * 16000;
|
| 91 |
+
|
| 92 |
+
SmartTurn::SmartTurn(Ort::Env &env, const std::string &dir, int threads) {
|
| 93 |
+
s = open_session(env, dir + "/smart_turn.onnx", threads);
|
| 94 |
+
Ort::AllocatorWithDefaultOptions al;
|
| 95 |
+
out_name = s->GetOutputNameAllocated(0, al).get(); // 出口の名前は、ファイルから読む
|
| 96 |
+
mel.set(read_f32(dir + "/whisper_mel_80x201.f32", 80 * 201));
|
| 97 |
+
win = read_f32(dir + "/hann400.f32", 400);
|
| 98 |
+
ring.assign(N8, 0.0f);
|
| 99 |
+
a.resize(N8);
|
| 100 |
+
p.resize(N8 + 400);
|
| 101 |
+
frames.resize(800 * 400);
|
| 102 |
+
pw.resize(800 * 201);
|
| 103 |
+
feat.resize(80 * 800);
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
void SmartTurn::push(const float *x, int n) {
|
| 107 |
+
for (int i = 0; i < n; i++) {
|
| 108 |
+
ring[head] = x[i];
|
| 109 |
+
head = (head + 1) % N8;
|
| 110 |
+
}
|
| 111 |
+
len = std::min<size_t>(N8, len + n);
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
float SmartTurn::predict() {
|
| 115 |
+
double t0 = now_sec();
|
| 116 |
+
// 直前 8 秒を古い順に並べる。足りない分は前を 0 でうめる(公式と同じ)
|
| 117 |
+
std::fill(a.begin(), a.end(), 0.0f);
|
| 118 |
+
size_t start = (head + N8 - len) % N8;
|
| 119 |
+
for (size_t i = 0; i < len; i++) a[N8 - len + i] = ring[(start + i) % N8];
|
| 120 |
+
double mean = std::accumulate(a.begin(), a.end(), 0.0) / N8, var = 0;
|
| 121 |
+
for (float v : a) var += (v - mean) * (v - mean);
|
| 122 |
+
float sd = (float) sqrt(var / N8 + 1e-7);
|
| 123 |
+
for (int i = 0; i < N8; i++) p[200 + i] = (float) ((a[i] - mean) / sd);
|
| 124 |
+
for (int i = 0; i < 200; i++) { p[199 - i] = p[201 + i]; p[200 + N8 + i] = p[200 + N8 - 2 - i]; } // 両端を反射
|
| 125 |
+
for (int j = 0; j < 800; j++) // 801 コマのうち最後は捨てる
|
| 126 |
+
for (int i = 0; i < 400; i++) frames[(size_t) j * 400 + i] = p[(size_t) j * 160 + i] * win[i];
|
| 127 |
+
dft.power_many(frames.data(), 800, pw.data()); // 800 コマまとめて FFT
|
| 128 |
+
float mx = -1e30f;
|
| 129 |
+
for (int j = 0; j < 800; j++)
|
| 130 |
+
for (int b = 0; b < 80; b++) {
|
| 131 |
+
float lg = log10f(std::max(mel.apply(b, &pw[(size_t) j * 201]), 1e-10f));
|
| 132 |
+
feat[(size_t) b * 800 + j] = lg;
|
| 133 |
+
mx = std::max(mx, lg);
|
| 134 |
+
}
|
| 135 |
+
for (float &v : feat) v = (std::max(v, mx - 8.0f) + 4.0f) / 4.0f;
|
| 136 |
+
Ort::Value in[] = {tensor(feat, {1, 80, 800})};
|
| 137 |
+
const char *inn[] = {"input_features"};
|
| 138 |
+
const char *outn[] = {out_name.c_str()};
|
| 139 |
+
auto out = s->Run(Ort::RunOptions{nullptr}, inn, in, 1, outn, 1);
|
| 140 |
+
float r = out[0].GetTensorData<float>()[0];
|
| 141 |
+
last_ms = (now_sec() - t0) * 1000;
|
| 142 |
+
return r;
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
// ======================= 相づち AI(VAP)
|
| 146 |
+
Vap::Vap(Ort::Env &env, const std::string &dir, int threads) {
|
| 147 |
+
enc = open_session(env, dir + "/vap_enc.onnx", threads);
|
| 148 |
+
ar = open_session(env, dir + "/vap_ar.onnx", threads);
|
| 149 |
+
h1.assign(256, 0); c1.assign(256, 0); h2.assign(256, 0); c2.assign(256, 0);
|
| 150 |
+
b1.assign(320, 0);
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
void Vap::push(const float *x, int n, bool predict) {
|
| 154 |
+
pend.insert(pend.end(), x, x + n);
|
| 155 |
+
while (pend.size() >= 1600) {
|
| 156 |
+
double t0 = now_sec();
|
| 157 |
+
std::vector<float> a1(b1);
|
| 158 |
+
a1.insert(a1.end(), pend.begin(), pend.begin() + 1600);
|
| 159 |
+
pend.erase(pend.begin(), pend.begin() + 1600);
|
| 160 |
+
b1.assign(a1.end() - 320, a1.end());
|
| 161 |
+
thread_local std::vector<float> a2(1920, 0.0f); // AI 側の音(今はずっと 0、PC 版と同じ)
|
| 162 |
+
Ort::Value in[] = {tensor(a1, {1, 1, 1920}), tensor(a2, {1, 1, 1920}), tensor(h1, {1, 1, 256}),
|
| 163 |
+
tensor(c1, {1, 1, 256}), tensor(h2, {1, 1, 256}), tensor(c2, {1, 1, 256})};
|
| 164 |
+
static const char *inn[] = {"a1", "a2", "h1", "c1", "h2", "c2"};
|
| 165 |
+
static const char *outn[] = {"e1", "e2", "h1_out", "c1_out", "h2_out", "c2_out"};
|
| 166 |
+
auto o = enc->Run(Ort::RunOptions{nullptr}, inn, in, 6, outn, 6);
|
| 167 |
+
auto take = [](Ort::Value &v, size_t n) { const float *q = v.GetTensorData<float>(); return std::vector<float>(q, q + n); };
|
| 168 |
+
e1s.push_back(take(o[0], dim));
|
| 169 |
+
e2s.push_back(take(o[1], dim));
|
| 170 |
+
h1 = take(o[2], 256); c1 = take(o[3], 256); h2 = take(o[4], 256); c2 = take(o[5], 256);
|
| 171 |
+
while (e1s.size() > 50) { e1s.pop_front(); e2s.pop_front(); }
|
| 172 |
+
if (!predict) { react = emo = 0; continue; }
|
| 173 |
+
int Tn = (int) e1s.size();
|
| 174 |
+
thread_local std::vector<float> E1, E2;
|
| 175 |
+
E1.clear(); E2.clear();
|
| 176 |
+
for (int i = 0; i < Tn; i++) { E1.insert(E1.end(), e1s[i].begin(), e1s[i].end()); E2.insert(E2.end(), e2s[i].begin(), e2s[i].end()); }
|
| 177 |
+
Ort::Value ain[] = {tensor(E1, {1, Tn, dim}), tensor(E2, {1, Tn, dim})};
|
| 178 |
+
static const char *ainn[] = {"e1", "e2"};
|
| 179 |
+
static const char *aoutn[] = {"p_react", "p_emo"};
|
| 180 |
+
auto r = ar->Run(Ort::RunOptions{nullptr}, ainn, ain, 2, aoutn, 2);
|
| 181 |
+
react = r[0].GetTensorData<float>()[0];
|
| 182 |
+
emo = r[1].GetTensorData<float>()[0];
|
| 183 |
+
count++;
|
| 184 |
+
last_ms = (now_sec() - t0) * 1000;
|
| 185 |
+
}
|
| 186 |
+
}
|
source/app/src/main/cpp/duplex/models.h
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// models.h — 話し終わり Smart Turn と相づち VAP
|
| 2 |
+
#pragma once
|
| 3 |
+
#include <array>
|
| 4 |
+
#include <deque>
|
| 5 |
+
#include <memory>
|
| 6 |
+
#include <string>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
#include "onnxruntime_cxx_api.h"
|
| 10 |
+
|
| 11 |
+
// 400 点の FFT(パワー)を速く計算する(pocketfft)
|
| 12 |
+
struct PowerDft {
|
| 13 |
+
void power(const float *frame400, float *out201) const; // 窓をかけた 400 点 → 201 点のパワー
|
| 14 |
+
void power_many(const float *frames, int n, float *out) const; // n コマまとめて(n×400 → n×201)
|
| 15 |
+
};
|
| 16 |
+
|
| 17 |
+
// メルの重み(80×201)。ほとんどが 0 なので、0 でない所だけ掛ける
|
| 18 |
+
struct MelBank {
|
| 19 |
+
std::vector<float> w;
|
| 20 |
+
std::vector<int> lo, hi; // 各メルで 0 でない範囲 [lo, hi)
|
| 21 |
+
void set(std::vector<float> full);
|
| 22 |
+
float apply(int b, const float *pw) const {
|
| 23 |
+
float acc = 0;
|
| 24 |
+
const float *r = &w[b * 201];
|
| 25 |
+
for (int k = lo[b]; k < hi[b]; k++) acc += r[k] * pw[k];
|
| 26 |
+
return acc;
|
| 27 |
+
}
|
| 28 |
+
};
|
| 29 |
+
|
| 30 |
+
// ONNX の読み込み(計算の係が空回りしない設定。LLM と CPU を取り合わないため)
|
| 31 |
+
std::unique_ptr<Ort::Session> open_session(Ort::Env &env, const std::string &path, int threads);
|
| 32 |
+
|
| 33 |
+
// ---------------- 話し終わりの判断(Smart Turn v3.2、声だけを見る)
|
| 34 |
+
struct SmartTurn {
|
| 35 |
+
SmartTurn(Ort::Env &env, const std::string &dir, int threads);
|
| 36 |
+
void push(const float *x, int n); // 直前 8 秒の声をためる
|
| 37 |
+
float predict(); // 言い終わった確率
|
| 38 |
+
void reset() { len = 0; head = 0; }
|
| 39 |
+
const std::vector<float> &features() const { return feat; } // 確かめる用(直前に計算したログメル 80×800)
|
| 40 |
+
double last_ms = 0;
|
| 41 |
+
|
| 42 |
+
private:
|
| 43 |
+
std::unique_ptr<Ort::Session> s;
|
| 44 |
+
MelBank mel;
|
| 45 |
+
std::vector<float> win; // (400)
|
| 46 |
+
PowerDft dft;
|
| 47 |
+
std::vector<float> ring; // 直前 8 秒(輪のように上書きする)
|
| 48 |
+
size_t head = 0, len = 0;
|
| 49 |
+
std::string out_name;
|
| 50 |
+
std::vector<float> a, p, frames, pw, feat; // 計算用(毎回作り直さない)
|
| 51 |
+
};
|
| 52 |
+
|
| 53 |
+
// ---------------- 相づち AI(MaAI VAP、100ms ごと)
|
| 54 |
+
struct Vap {
|
| 55 |
+
Vap(Ort::Env &env, const std::string &dir, int threads);
|
| 56 |
+
// 100ms(1600 点)ごとに呼ぶ → 新しい確率を react / emo に入れる
|
| 57 |
+
void push(const float *x, int n, bool predict = true);
|
| 58 |
+
float react = 0, emo = 0;
|
| 59 |
+
double last_ms = 0;
|
| 60 |
+
int count = 0; // 計算した回数(新しい確率が出たかを見る)
|
| 61 |
+
|
| 62 |
+
private:
|
| 63 |
+
std::unique_ptr<Ort::Session> enc, ar;
|
| 64 |
+
std::vector<float> h1, c1, h2, c2;
|
| 65 |
+
std::vector<float> b1, pend; // 前の 320 点、たまった新しい音
|
| 66 |
+
std::deque<std::vector<float>> e1s, e2s;
|
| 67 |
+
int dim = 256;
|
| 68 |
+
};
|
source/app/src/main/cpp/duplex/moonshine-c-api.h
ADDED
|
@@ -0,0 +1,1433 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#ifndef MOONSHINE_C_API_H
|
| 2 |
+
#define MOONSHINE_C_API_H
|
| 3 |
+
|
| 4 |
+
/* Moonshine is a library for building interactive voice applications. It
|
| 5 |
+
provides a high-level API for building voice interfaces, including
|
| 6 |
+
voice-activity detection, diarization, transcription, speech understanding,
|
| 7 |
+
and text-to-speech. It is designed to be fast, easy to use and to provide a
|
| 8 |
+
high level of accuracy. It is also designed to be easy to integrate into your
|
| 9 |
+
existing codebase across all major platforms.
|
| 10 |
+
|
| 11 |
+
It uses the Moonshine family of speech to text models, which:
|
| 12 |
+
|
| 13 |
+
- Understand multiple major languages, including English, Japanese,
|
| 14 |
+
Korean, Chinese, Arabic, and more.
|
| 15 |
+
|
| 16 |
+
- Are designed to be lightweight and fast for mobile and edge devices,
|
| 17 |
+
and can be used in the cloud where latency and compute costs matter.
|
| 18 |
+
|
| 19 |
+
- Support streaming transcription to reduce latency on real-time
|
| 20 |
+
applications.
|
| 21 |
+
|
| 22 |
+
- Are trained from scratch on a large, unique dataset of audio data,
|
| 23 |
+
allowing our team to quickly train custom models for jargon or dialects.
|
| 24 |
+
|
| 25 |
+
- Are available under permissive licenses, with English fully MIT
|
| 26 |
+
licensed and other languages under a non-commercial agreement.
|
| 27 |
+
|
| 28 |
+
You'll most likely want to use the specific bindings for your language of
|
| 29 |
+
choice, since this is a low-level C API to the underlying implementation.
|
| 30 |
+
This is the interface that those bindings all use though, so if you're
|
| 31 |
+
interested in porting to a new environment or language, the inline notes
|
| 32 |
+
here may be useful.
|
| 33 |
+
|
| 34 |
+
Here's an example of how to use the transcriber:
|
| 35 |
+
```c
|
| 36 |
+
#include "moonshine-c-api.h"
|
| 37 |
+
|
| 38 |
+
int main(int argc, char *argv[]) {
|
| 39 |
+
int32_t transcriber_handle = moonshine_load_transcriber_from_files(
|
| 40 |
+
"path/to/models", MOONSHINE_MODEL_ARCH_BASE, NULL, 0,
|
| 41 |
+
MOONSHINE_HEADER_VERSION);
|
| 42 |
+
if (transcriber_handle < 0) {
|
| 43 |
+
fprintf(stderr, "Failed to load transcriber\n");
|
| 44 |
+
return 1;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
float audio_data[32000] = {};
|
| 48 |
+
size_t audio_length = 32000;
|
| 49 |
+
int32_t sample_rate = 16000;
|
| 50 |
+
transcript_t *transcript = NULL;
|
| 51 |
+
int32_t error = moonshine_transcribe_without_streaming(transcriber_handle,
|
| 52 |
+
audio_data, audio_length, sample_rate, 0, &transcript); if (error != 0) {
|
| 53 |
+
fprintf(stderr, "Failed to transcribe\n");
|
| 54 |
+
return 1;
|
| 55 |
+
}
|
| 56 |
+
for (size_t i = 0; i < transcript->line_count; i++) {
|
| 57 |
+
printf( "Line %zu at %f seconds: %s\n", i, transcript->lines[i].start,
|
| 58 |
+
transcript->lines[i].text);
|
| 59 |
+
}
|
| 60 |
+
moonshine_free_transcriber(transcriber_handle);
|
| 61 |
+
return 0;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
All API calls are thread-safe, so you can call them from multiple threads
|
| 65 |
+
concurrently. Calculations on a single transcriber will be serialized
|
| 66 |
+
however, so latency will be affected for calls from other threads while
|
| 67 |
+
the transcriber is busy.
|
| 68 |
+
```
|
| 69 |
+
*/
|
| 70 |
+
|
| 71 |
+
#if defined(ANDROID)
|
| 72 |
+
#include <android/asset_manager.h>
|
| 73 |
+
#endif
|
| 74 |
+
#include <stddef.h>
|
| 75 |
+
#include <stdint.h>
|
| 76 |
+
|
| 77 |
+
#ifdef _WIN32
|
| 78 |
+
#define MOONSHINE_EXPORT __declspec(dllexport)
|
| 79 |
+
#else
|
| 80 |
+
#define MOONSHINE_EXPORT __attribute__((visibility("default")))
|
| 81 |
+
#endif
|
| 82 |
+
|
| 83 |
+
#ifdef __cplusplus
|
| 84 |
+
extern "C" {
|
| 85 |
+
#endif
|
| 86 |
+
|
| 87 |
+
/* ------------------------------ CONSTANTS -------------------------------- */
|
| 88 |
+
|
| 89 |
+
/* What version of the Moonshine library the header file is associated with.
|
| 90 |
+
You should pass this version to moonshine_load_transcriber so that newer
|
| 91 |
+
versions of the library can emulate any older behavior that has changed.
|
| 92 |
+
The format is MAJOR * 10000 + MINOR * 100 + PATCH.
|
| 93 |
+
For example, version 3.0.0 would be 30000.
|
| 94 |
+
For example, version 3.2.7 would be 30207. */
|
| 95 |
+
#define MOONSHINE_HEADER_VERSION (30000)
|
| 96 |
+
|
| 97 |
+
/* The first header version that no longer supports
|
| 98 |
+
moonshine_load_transcriber_from_memory. A client passing this version or
|
| 99 |
+
newer gets MOONSHINE_ERROR_INVALID_ARGUMENT back from that call, along with
|
| 100 |
+
a logged explanation, and should use
|
| 101 |
+
moonshine_load_transcriber_from_memory_files instead. Clients built against
|
| 102 |
+
an earlier header keep the old behavior, so existing binaries are
|
| 103 |
+
unaffected. */
|
| 104 |
+
#define MOONSHINE_FROM_MEMORY_REMOVED_VERSION (30000)
|
| 105 |
+
|
| 106 |
+
/* Supported model architectures. */
|
| 107 |
+
#define MOONSHINE_MODEL_ARCH_TINY (0)
|
| 108 |
+
#define MOONSHINE_MODEL_ARCH_BASE (1)
|
| 109 |
+
#define MOONSHINE_MODEL_ARCH_TINY_STREAMING (2)
|
| 110 |
+
/* Note: BASE_STREAMING is defined for future use but is not currently
|
| 111 |
+
published in the model catalog. */
|
| 112 |
+
#define MOONSHINE_MODEL_ARCH_BASE_STREAMING (3)
|
| 113 |
+
#define MOONSHINE_MODEL_ARCH_SMALL_STREAMING (4)
|
| 114 |
+
#define MOONSHINE_MODEL_ARCH_MEDIUM_STREAMING (5)
|
| 115 |
+
|
| 116 |
+
/* Error codes. */
|
| 117 |
+
#define MOONSHINE_ERROR_NONE (0)
|
| 118 |
+
#define MOONSHINE_ERROR_UNKNOWN (-1)
|
| 119 |
+
#define MOONSHINE_ERROR_INVALID_HANDLE (-2)
|
| 120 |
+
#define MOONSHINE_ERROR_INVALID_ARGUMENT (-3)
|
| 121 |
+
/* A streaming generation is in flight and the call would have competed with it
|
| 122 |
+
for the model. Finish it, or call moonshine_tts_cancel. */
|
| 123 |
+
#define MOONSHINE_ERROR_BUSY (-4)
|
| 124 |
+
|
| 125 |
+
/* Statuses from moonshine_tts_next_chunk. All are positive, so the usual
|
| 126 |
+
"negative means failure" test still separates them from real errors, and
|
| 127 |
+
all convert with moonshine_error_to_string. */
|
| 128 |
+
/* No complete sentence is buffered yet. Push more text, or flush. */
|
| 129 |
+
#define MOONSHINE_TTS_NEED_TEXT (1)
|
| 130 |
+
/* Input ended and every queued utterance has been synthesized. */
|
| 131 |
+
#define MOONSHINE_TTS_END_OF_STREAM (2)
|
| 132 |
+
/* moonshine_tts_cancel discarded the reply that was being generated. Sent
|
| 133 |
+
once, and only when there was something to discard, so a consumer pulling
|
| 134 |
+
chunks on a worker thread can tell an interruption from running out of
|
| 135 |
+
text. */
|
| 136 |
+
#define MOONSHINE_TTS_CANCELLED (3)
|
| 137 |
+
|
| 138 |
+
/* Flags. */
|
| 139 |
+
#define MOONSHINE_FLAG_FORCE_UPDATE (1 << 0)
|
| 140 |
+
/* Apply alphanumeric-spelling fusion to every completed line in the
|
| 141 |
+
returned transcript. The transcriber must have been constructed with
|
| 142 |
+
a spelling model (either ``spelling_model_path`` in
|
| 143 |
+
moonshine_load_transcriber_from_files or a non-null
|
| 144 |
+
``spelling_model_data`` buffer in
|
| 145 |
+
moonshine_load_transcriber_from_memory) for this flag to have any
|
| 146 |
+
effect; if no spelling model is loaded, the flag is ignored.
|
| 147 |
+
|
| 148 |
+
When fusion fires for a line, the line's ``text`` field is *replaced*
|
| 149 |
+
with the resolved single character (e.g. ``"a"`` or ``"$"``). Speech
|
| 150 |
+
that does not resolve to a character is left unchanged so command
|
| 151 |
+
words like "stop" / "clear" / "delete" can still be classified by
|
| 152 |
+
higher-level Python code. */
|
| 153 |
+
#define MOONSHINE_FLAG_SPELLING_MODE (1 << 1)
|
| 154 |
+
|
| 155 |
+
/* --------------------------- DATA STRUCTURES ----------------------------- */
|
| 156 |
+
|
| 157 |
+
/* Values passed to moonshine_load_transcriber,
|
| 158 |
+
moonshine_create_text_to_speech_synthesizer or
|
| 159 |
+
moonshine_create_graph_to_phonemizer at creation time that control
|
| 160 |
+
the behavior of the transcriber. A typical use case would be to specify
|
| 161 |
+
model configuration options like layer names that vary by language. The
|
| 162 |
+
value is a string. You don't normally need to care about these, this is just
|
| 163 |
+
for advanced customizations. */
|
| 164 |
+
struct moonshine_option_t {
|
| 165 |
+
const char *name;
|
| 166 |
+
const char *value;
|
| 167 |
+
};
|
| 168 |
+
|
| 169 |
+
/* All transcription calls return a list of "lines". These line objects
|
| 170 |
+
represent a piece of speech, something like a sentence or phrase. For
|
| 171 |
+
non-streaming calls, you get back a finalized list of these lines, with all
|
| 172 |
+
their states set to “complete”. Each streaming call returns a similar list, but
|
| 173 |
+
if there isn’t a pause at the end of the current audio - if the user still
|
| 174 |
+
seems to be speaking but cut off - the final line will be marked as being
|
| 175 |
+
incomplete.
|
| 176 |
+
|
| 177 |
+
All memory referenced by the line objects is owned by the transcriber and is
|
| 178 |
+
valid until the next call to that transcriber, or until the transcriber is
|
| 179 |
+
freed.
|
| 180 |
+
|
| 181 |
+
The audio data is 16KHz float PCM, between -1.0 and 1.0.
|
| 182 |
+
|
| 183 |
+
To make the streaming results easier to work with we offer some guarantees:
|
| 184 |
+
|
| 185 |
+
- Lines are never removed from the results, only added.
|
| 186 |
+
|
| 187 |
+
- Only the last line in the list may potentially be incomplete.
|
| 188 |
+
|
| 189 |
+
- If speech is detected by the VAD, but no transcription can be produced, the
|
| 190 |
+
line will be an empty string, "".
|
| 191 |
+
|
| 192 |
+
- Line indexes can be used as stable references when repeatedly calling
|
| 193 |
+
streaming transcription. This means a client can remember the length of the
|
| 194 |
+
last results returned, and when it calls again it can figure out the updates
|
| 195 |
+
by iterating the results starting at that line index.
|
| 196 |
+
|
| 197 |
+
- The line id is a stable identifier for the line. This is set to a 64-bit
|
| 198 |
+
randomly-generated number, with the goal of minimizing the chances of a
|
| 199 |
+
collision. Currently these IDs are in ascending order in any one transcript,
|
| 200 |
+
but this is not guaranteed and should not be relied on.
|
| 201 |
+
|
| 202 |
+
- When speaker identification is enabled (the opt-in ``identify_speakers``
|
| 203 |
+
option), each line carries an array of speaker spans describing who was
|
| 204 |
+
talking during which parts of the line, including UTF-8 character ranges
|
| 205 |
+
into the line text. Word timestamps are enabled automatically in this mode.
|
| 206 |
+
Speaker IDs are 64-bit
|
| 207 |
+
randomly-generated numbers that are stable for a given speaker within a
|
| 208 |
+
stream, and speaker indices count speakers in order of first appearance.
|
| 209 |
+
Unlike the text and timing of a line, speaker spans for recent audio are
|
| 210 |
+
*mutable*: streaming diarization re-clusters a sliding window
|
| 211 |
+
(``diarization_cluster_window_sec``, default 120s) as more speech arrives;
|
| 212 |
+
assignments for older audio are frozen. The ``have_speakers_changed`` flag is
|
| 213 |
+
set on a line whenever its spans changed since the previous call.
|
| 214 |
+
|
| 215 |
+
See the stream transcription examples below for more details on what this
|
| 216 |
+
means in practice.
|
| 217 |
+
*/
|
| 218 |
+
|
| 219 |
+
/* A single word with timing information.
|
| 220 |
+
Only populated when word_timestamps option is enabled. */
|
| 221 |
+
struct transcript_word_t {
|
| 222 |
+
/* UTF-8-encoded word text. */
|
| 223 |
+
const char *text;
|
| 224 |
+
/* Start time in seconds (absolute, from start of audio/stream). */
|
| 225 |
+
float start;
|
| 226 |
+
/* End time in seconds. */
|
| 227 |
+
float end;
|
| 228 |
+
/* Model confidence score, 0.0 to 1.0. */
|
| 229 |
+
float confidence;
|
| 230 |
+
};
|
| 231 |
+
|
| 232 |
+
/* One contiguous span of speech within a line attributed to a single
|
| 233 |
+
speaker. Only populated when the identify_speakers option is enabled.
|
| 234 |
+
Spans can be revised on any transcription call, even for lines that are
|
| 235 |
+
already complete; see the have_speakers_changed flag on
|
| 236 |
+
transcript_line_t. Character ranges use UTF-8 byte offsets into the line
|
| 237 |
+
text; word_timestamps are enabled automatically when identify_speakers is
|
| 238 |
+
on. */
|
| 239 |
+
struct speaker_span_t {
|
| 240 |
+
/* Time offset from the start of the array or stream in seconds. */
|
| 241 |
+
float start_time;
|
| 242 |
+
/* Length of the span in seconds. */
|
| 243 |
+
float duration;
|
| 244 |
+
/* Stable identifier for the speaker within this stream. */
|
| 245 |
+
uint64_t speaker_id;
|
| 246 |
+
/* The order the speaker first appeared in the transcript, starting at 0. */
|
| 247 |
+
uint32_t speaker_index;
|
| 248 |
+
/* UTF-8 byte offset into the line's text where this span begins (inclusive).
|
| 249 |
+
Only meaningful when identify_speakers is enabled; word_timestamps are
|
| 250 |
+
turned on automatically in that case. Both zero when unknown. */
|
| 251 |
+
uint64_t start_char;
|
| 252 |
+
/* UTF-8 byte offset into the line's text where this span ends (exclusive).
|
| 253 |
+
Both zero when unknown. */
|
| 254 |
+
uint64_t end_char;
|
| 255 |
+
};
|
| 256 |
+
|
| 257 |
+
/* Information about a single “line” of a transcript. */
|
| 258 |
+
struct transcript_line_t {
|
| 259 |
+
/* UTF-8-encoded transcription. */
|
| 260 |
+
const char *text;
|
| 261 |
+
/* The audio data for the current phrase. */
|
| 262 |
+
const float *audio_data;
|
| 263 |
+
/* The number of elements in the audio data array. */
|
| 264 |
+
size_t audio_data_count;
|
| 265 |
+
/* Time offset from the start of the array or stream in seconds. */
|
| 266 |
+
float start_time;
|
| 267 |
+
/* How long the segment currently is in seconds. */
|
| 268 |
+
float duration;
|
| 269 |
+
/* Stable identifier for the line. */
|
| 270 |
+
uint64_t id;
|
| 271 |
+
/* Streaming-only: Zero means the speaker hasn't finished talking in this
|
| 272 |
+
* segment, non-zero means they have. */
|
| 273 |
+
int8_t is_complete;
|
| 274 |
+
/* Streaming-only: Whether the line has been updated since the previous call
|
| 275 |
+
* to moonshine_transcribe_stream. */
|
| 276 |
+
int8_t is_updated;
|
| 277 |
+
/* Streaming-only: Whether the line was newly added since the previous call to
|
| 278 |
+
* moonshine_transcribe_stream. */
|
| 279 |
+
int8_t is_new;
|
| 280 |
+
/* Streaming-only: Whether the text of the line has changed since the previous
|
| 281 |
+
* call to moonshine_transcribe_stream. */
|
| 282 |
+
int8_t has_text_changed;
|
| 283 |
+
/* Whether the speaker spans of the line have changed since the previous
|
| 284 |
+
* call to moonshine_transcribe_stream. Unlike the other change flags, this
|
| 285 |
+
* can fire for lines that are already complete, since diarization refines
|
| 286 |
+
* speaker assignments retroactively as more audio arrives. */
|
| 287 |
+
int8_t have_speakers_changed;
|
| 288 |
+
/* Speaker spans covering this line, ordered by start time and clipped to
|
| 289 |
+
* the line's time range. NULL unless the identify_speakers option is
|
| 290 |
+
* enabled and speech has been attributed to a speaker. */
|
| 291 |
+
const struct speaker_span_t *speaker_spans;
|
| 292 |
+
/* Number of entries in the speaker_spans array. */
|
| 293 |
+
uint64_t speaker_span_count;
|
| 294 |
+
/* Streaming-only: The latency of the last transcription in milliseconds. */
|
| 295 |
+
uint32_t last_transcription_latency_ms;
|
| 296 |
+
/* Word-level timestamps. NULL if word_timestamps option is not enabled. */
|
| 297 |
+
const struct transcript_word_t *words;
|
| 298 |
+
/* Number of words in the words array. 0 if not enabled. */
|
| 299 |
+
uint64_t word_count;
|
| 300 |
+
};
|
| 301 |
+
|
| 302 |
+
/* An entire transcription of an audio data array or stream. */
|
| 303 |
+
struct transcript_t {
|
| 304 |
+
struct transcript_line_t *lines; /* All lines of the transcript. */
|
| 305 |
+
uint64_t line_count; /* Number of lines in the transcript. */
|
| 306 |
+
};
|
| 307 |
+
|
| 308 |
+
/* ------------------------------ FUNCTIONS -------------------------------- */
|
| 309 |
+
|
| 310 |
+
/* Returns the loaded moonshine library version. This may be different from
|
| 311 |
+
the header version if a newer shared library is loaded.
|
| 312 |
+
*/
|
| 313 |
+
MOONSHINE_EXPORT int32_t moonshine_get_version(void);
|
| 314 |
+
|
| 315 |
+
/* Converts an error code number returned from an API call into a
|
| 316 |
+
human-readable string. */
|
| 317 |
+
MOONSHINE_EXPORT const char *moonshine_error_to_string(int32_t error);
|
| 318 |
+
|
| 319 |
+
/* Frees a buffer that a moonshine_* function documented as "allocated with
|
| 320 |
+
malloc; release with free" returned to the caller. This covers, for
|
| 321 |
+
example, ``out_audio_data`` from moonshine_text_to_speech /
|
| 322 |
+
moonshine_phonemes_to_speech, the JSON / comma-separated strings from
|
| 323 |
+
moonshine_get_tts_dependencies / moonshine_get_g2p_dependencies /
|
| 324 |
+
moonshine_get_tts_voices, and ``out_phonemes`` from
|
| 325 |
+
moonshine_text_to_phonemes.
|
| 326 |
+
|
| 327 |
+
Always use this instead of the C runtime ``free`` directly. On Windows the
|
| 328 |
+
library and its host (e.g. a Python binding) can be linked against
|
| 329 |
+
different C runtimes with independent heaps, so freeing a library-allocated
|
| 330 |
+
pointer with the host's ``free`` corrupts the heap. Routing the free back
|
| 331 |
+
through the library guarantees the allocation and deallocation happen in
|
| 332 |
+
the same runtime. Safe to call on NULL. */
|
| 333 |
+
MOONSHINE_EXPORT void moonshine_free_buffer(void *ptr);
|
| 334 |
+
|
| 335 |
+
/* Replaces the contextual-biasing key terms on an existing transcriber, so a
|
| 336 |
+
caller can follow whatever context the user is in - the contact list on
|
| 337 |
+
screen, the vocabulary of the document being dictated into - without
|
| 338 |
+
reloading the model. ``keyterms`` is a comma-separated list using the same
|
| 339 |
+
syntax as the ``keyterms`` load option; pass NULL or an empty string to turn
|
| 340 |
+
biasing off.
|
| 341 |
+
|
| 342 |
+
Safe to call between transcribe calls on a live stream. Takes effect on the
|
| 343 |
+
next transcribe call: it does not retroactively change text already emitted.
|
| 344 |
+
|
| 345 |
+
Returns ``MOONSHINE_ERROR_NONE`` on success, or a non-zero error code if the
|
| 346 |
+
handle is invalid or the loaded model is not a streaming architecture (only
|
| 347 |
+
those decode through a path that can apply the bias). */
|
| 348 |
+
MOONSHINE_EXPORT int32_t moonshine_transcriber_set_keyterms(
|
| 349 |
+
int32_t transcriber_handle, const char *keyterms);
|
| 350 |
+
|
| 351 |
+
/* Picks the key terms out of a passage of free-form text and biases towards
|
| 352 |
+
them, replacing any previous list. Where
|
| 353 |
+
``moonshine_transcriber_set_keyterms`` wants a list, this wants context: hand
|
| 354 |
+
over the document on screen, the agenda for the meeting, the last few
|
| 355 |
+
messages in the thread, and the unusual words in it are found for you.
|
| 356 |
+
|
| 357 |
+
A word is judged unusual by how the model's own tokenizer spells it. That
|
| 358 |
+
vocabulary is ordered by frequency, so an everyday word has a token to itself
|
| 359 |
+
while jargon and proper nouns have to be built out of several subwords, and
|
| 360 |
+
needing more than one is the signal used here. It follows the language of the
|
| 361 |
+
loaded model, and the capitalization in the passage is what gets asked for in
|
| 362 |
+
the transcript.
|
| 363 |
+
|
| 364 |
+
``max_terms`` caps the list; pass 0 for the default of 200. The cap matters:
|
| 365 |
+
a long list costs accuracy on the words you did not ask for (see
|
| 366 |
+
docs/models/domain-customization.md), so the terms the passage leans on
|
| 367 |
+
hardest are kept and the rest of its long tail is dropped. Pass NULL or an
|
| 368 |
+
empty string to turn biasing off.
|
| 369 |
+
|
| 370 |
+
Safe to call between transcribe calls on a live stream. Takes effect on the
|
| 371 |
+
next transcribe call: it does not retroactively change text already emitted.
|
| 372 |
+
|
| 373 |
+
Returns ``MOONSHINE_ERROR_NONE`` on success, or a non-zero error code if the
|
| 374 |
+
handle is invalid or the loaded model is not a streaming architecture (only
|
| 375 |
+
those decode through a path that can apply the bias). */
|
| 376 |
+
MOONSHINE_EXPORT int32_t moonshine_transcriber_set_context(
|
| 377 |
+
int32_t transcriber_handle, const char *context, int32_t max_terms);
|
| 378 |
+
|
| 379 |
+
/* Converts a transcript_t struct into a human-readable string for debugging
|
| 380 |
+
* purposes. The string is owned by the library, and is valid until the next
|
| 381 |
+
* call to moonshine_transcript_to_string. */
|
| 382 |
+
MOONSHINE_EXPORT const char *moonshine_transcript_to_string(
|
| 383 |
+
const struct transcript_t *transcript);
|
| 384 |
+
|
| 385 |
+
/* Loads models from the file system, using `path` as the root directory. The
|
| 386 |
+
implementation expects the following files to be present in the directory:
|
| 387 |
+
- encoder_model.ort
|
| 388 |
+
- decoder_model_merged.ort
|
| 389 |
+
- tokenizer.bin
|
| 390 |
+
The .ort files are quantized activation ONNX models that have been converted
|
| 391 |
+
to ORT format using the onnxruntime tools. The simplest way to obtain these
|
| 392 |
+
files is to run the `scripts/download-moonshine-model.py` script, for
|
| 393 |
+
example `python scripts/download-moonshine-model.py --model-type base
|
| 394 |
+
--model-language en`.
|
| 395 |
+
The source weights are available on the Hugging Face Model Hub at
|
| 396 |
+
https://huggingface.co/moonshine-ai/, and the download and conversion to
|
| 397 |
+
ONNX script is available in this repository at
|
| 398 |
+
`scripts/convert-moonshine-model.sh`.
|
| 399 |
+
The tokenizer.bin contains the token to character mapping for the model,
|
| 400 |
+
in a compact binary format. The `scripts/json-to-bin-vocab.py` can be used
|
| 401 |
+
to convert common tokenizer.json files to tokenizer.bin files.
|
| 402 |
+
|
| 403 |
+
The `model_arch` parameter is used to select the model architecture, for
|
| 404 |
+
example MOONSHINE_MODEL_ARCH_BASE or MOONSHINE_MODEL_ARCH_TINY_STREAMING.
|
| 405 |
+
|
| 406 |
+
The `options` parameter is used to set any custom options for the
|
| 407 |
+
transcriber. Recognized options include ``log_ort_run`` (bool),
|
| 408 |
+
``ort_providers`` (comma-separated execution provider names such as
|
| 409 |
+
``CoreML,CPU`` on macOS; default and recommendation is CPU-only, and the
|
| 410 |
+
iOS and Android libraries ship with no other choice — see
|
| 411 |
+
docs/execution-providers.md), and ``coreml_cache_dir`` (directory for the
|
| 412 |
+
CoreML compiled model cache on macOS).
|
| 413 |
+
Pass ``use_speculative_decoding`` (bool, default true) to control
|
| 414 |
+
speculative re-decode of the previous hypothesis on streaming updates
|
| 415 |
+
(set false to fall back to greedy redecode from BOS).
|
| 416 |
+
Pass ``decode_incomplete_lines`` (bool, default true) to run the
|
| 417 |
+
decoder on in-progress lines so the transcript can update while someone
|
| 418 |
+
is still talking. Set false to encode (and diarize) as audio arrives
|
| 419 |
+
but wait until the line is complete before decoding.
|
| 420 |
+
Pass ``keyterms`` (comma-separated terms, e.g.
|
| 421 |
+
``Kubernetes,Anushka Sharma,ANSI/ISO``) to bias the decoder towards words it
|
| 422 |
+
would otherwise be unlikely to produce - jargon, product names, contact
|
| 423 |
+
names. No retraining is involved: each term is compiled into a subword trie
|
| 424 |
+
and used to nudge the decoder's logits, so the terms can be different on
|
| 425 |
+
every transcriber and can be replaced mid-stream with
|
| 426 |
+
``moonshine_transcriber_set_keyterms``. Match the capitalization and
|
| 427 |
+
spelling you want to see in the output. Only the streaming architectures
|
| 428 |
+
apply this. Pass ``context`` instead (or as well) to hand over a passage of
|
| 429 |
+
free-form text and have the terms picked out of it, as
|
| 430 |
+
``moonshine_transcriber_set_context`` does, with ``context_max_terms``
|
| 431 |
+
(int, default 200) capping how many are taken.
|
| 432 |
+
``keyterm_boost`` (float, default 2.0) sets the strength. The
|
| 433 |
+
default is where the terms come out most accurately; going higher recovers no
|
| 434 |
+
more of them and starts putting them where they were not said, so lower it if
|
| 435 |
+
general accuracy matters more than the list does, rather than raising it.
|
| 436 |
+
Pass ``identify_speakers`` (bool, default false) to enable speaker
|
| 437 |
+
diarization: each line then carries a ``speaker_spans`` array describing
|
| 438 |
+
who spoke when, including UTF-8 character ranges into the line text.
|
| 439 |
+
This also enables word timestamps automatically. This runs the cpp-annote
|
| 440 |
+
diarization pipeline (a port of
|
| 441 |
+
pyannote community-1) inline inside transcription calls, which adds
|
| 442 |
+
significant compute, and re-clustering cost grows with session length unless
|
| 443 |
+
bounded by ``diarization_cluster_window_sec``.
|
| 444 |
+
``diarization_cluster_cadence`` (float seconds, default 2.0) sets the
|
| 445 |
+
minimum interval between re-clustering passes - raise it to reduce cost on
|
| 446 |
+
long sessions - ``diarization_analyze_cadence`` (float seconds,
|
| 447 |
+
default 0 = model default of 1.0) sets the sliding-window step between
|
| 448 |
+
segmentation/embedding model runs (live ``add_audio`` / transcribe runs at
|
| 449 |
+
most one window per call; Stop drains the rest; silent speaker classes skip
|
| 450 |
+
embedding inference), and ``diarization_cluster_window_sec``
|
| 451 |
+
(float seconds, default 120.0) limits how much audio history VBx
|
| 452 |
+
re-clustering considers on each refresh (0 = unlimited full history).
|
| 453 |
+
Pass ``"spelling_model_path"`` with a path to a
|
| 454 |
+
spelling-CNN ``.ort`` file (e.g.
|
| 455 |
+
``https://download.moonshine.ai/model/spelling-en/spelling_cnn.ort``)
|
| 456 |
+
to enable alphanumeric spelling fusion via
|
| 457 |
+
``MOONSHINE_FLAG_SPELLING_MODE``; if not set, the spelling model is
|
| 458 |
+
not loaded and the flag is a no-op.
|
| 459 |
+
|
| 460 |
+
The `options_count` parameter is the number of options in the options array.
|
| 461 |
+
|
| 462 |
+
The `moonshine_version` parameter should be set to MOONSHINE_HEADER_VERSION
|
| 463 |
+
to ensure that if a newer version of the library is loaded, it emulates the
|
| 464 |
+
behavior of the older version to ensure compatibility.
|
| 465 |
+
|
| 466 |
+
The return value is a handle to a transcriber, which can be used to identify
|
| 467 |
+
the transcriber in subsequent calls. If there was an error, a negative value
|
| 468 |
+
is returned. This code can be converted to a human-readable string using
|
| 469 |
+
moonshine_error_to_string.
|
| 470 |
+
*/
|
| 471 |
+
MOONSHINE_EXPORT int32_t moonshine_load_transcriber_from_files(
|
| 472 |
+
const char *path, uint32_t model_arch,
|
| 473 |
+
const struct moonshine_option_t *options, uint64_t options_count,
|
| 474 |
+
int32_t moonshine_version);
|
| 475 |
+
|
| 476 |
+
/* **DEPRECATED** Use moonshine_load_transcriber_from_memory_files instead.
|
| 477 |
+
This function is deprecated and will be removed in a future version.
|
| 478 |
+
|
| 479 |
+
Callers that pass a `moonshine_version` of
|
| 480 |
+
MOONSHINE_FROM_MEMORY_REMOVED_VERSION or newer are refused: the call logs an
|
| 481 |
+
explanation and returns MOONSHINE_ERROR_INVALID_ARGUMENT without loading
|
| 482 |
+
anything. Only clients built against an earlier header, which pass that
|
| 483 |
+
earlier version here, can still use it.
|
| 484 |
+
|
| 485 |
+
Loads models from memory. The `encoder_model_data`, `decoder_model_data` and
|
| 486 |
+
`tokenizer_data` parameters are the data arrays for the models in binary
|
| 487 |
+
format, and are expected to be in the same format as the files disk.
|
| 488 |
+
|
| 489 |
+
`spelling_model_data` and `spelling_model_data_size` are an optional
|
| 490 |
+
in-memory ``.ort`` payload for the alphanumeric spelling-CNN. Pass
|
| 491 |
+
``NULL`` and ``0`` if you don't want spelling fusion. When provided,
|
| 492 |
+
the buffer must outlive the transcriber (it is *not* copied) and the
|
| 493 |
+
transcriber will run spelling fusion whenever
|
| 494 |
+
``MOONSHINE_FLAG_SPELLING_MODE`` is passed to
|
| 495 |
+
``moonshine_transcribe_stream`` or
|
| 496 |
+
``moonshine_transcribe_without_streaming``.
|
| 497 |
+
|
| 498 |
+
All of the other parameters are the same as for
|
| 499 |
+
moonshine_load_transcriber_from_files. */
|
| 500 |
+
MOONSHINE_EXPORT int32_t moonshine_load_transcriber_from_memory(
|
| 501 |
+
const uint8_t *encoder_model_data, size_t encoder_model_data_size,
|
| 502 |
+
const uint8_t *decoder_model_data, size_t decoder_model_data_size,
|
| 503 |
+
const uint8_t *tokenizer_data, size_t tokenizer_data_size,
|
| 504 |
+
const uint8_t *spelling_model_data, size_t spelling_model_data_size,
|
| 505 |
+
uint32_t model_arch, const struct moonshine_option_t *options,
|
| 506 |
+
uint64_t options_count, int32_t moonshine_version);
|
| 507 |
+
|
| 508 |
+
/* Loads a transcriber from a set of in-memory model assets keyed by their
|
| 509 |
+
canonical filename. This is the in-memory counterpart that reaches full
|
| 510 |
+
parity with moonshine_load_transcriber_from_files: unlike
|
| 511 |
+
moonshine_load_transcriber_from_memory (which only accepts a fixed
|
| 512 |
+
encoder/decoder/tokenizer/spelling set and rejects streaming models), this
|
| 513 |
+
entry point accepts whatever files the chosen architecture needs, resolved
|
| 514 |
+
by name.
|
| 515 |
+
|
| 516 |
+
``filenames[i]`` is the canonical filename as it would appear on disk under
|
| 517 |
+
a model directory. Recognized keys depend on ``model_arch``:
|
| 518 |
+
- Non-streaming (TINY, BASE): ``encoder_model.ort``,
|
| 519 |
+
``decoder_model_merged.ort``, ``tokenizer.bin`` (all required), plus the
|
| 520 |
+
optional word-timestamp decoder ``decoder_with_attention.ort`` (or the
|
| 521 |
+
two-pass ``alignment_model.ort``) when the ``word_timestamps`` option is
|
| 522 |
+
set.
|
| 523 |
+
- Streaming (``*_STREAMING``): ``frontend.ort`` (or the split pair
|
| 524 |
+
``frontend.model.ort`` + ``frontend.weights.ort``), ``encoder.ort``,
|
| 525 |
+
``adapter.ort``, ``cross_kv.ort``, ``decoder_kv.ort``,
|
| 526 |
+
``streaming_config.json``, ``tokenizer.bin`` (all required), plus the
|
| 527 |
+
optional ``decoder_kv_with_attention.ort`` when ``word_timestamps`` is
|
| 528 |
+
set.
|
| 529 |
+
- Either kind also accepts ``spelling_cnn.ort``, and the two diarization
|
| 530 |
+
models ``segmentation.ort`` and ``embedding.ort``, which are required
|
| 531 |
+
when the ``identify_speakers`` option is set. Fetch those two with
|
| 532 |
+
moonshine_get_diarization_dependencies.
|
| 533 |
+
Unrecognized keys are rejected with MOONSHINE_ERROR_INVALID_ARGUMENT, and
|
| 534 |
+
missing required keys cause the load to fail. The recognized set is the
|
| 535 |
+
union of the names above across every architecture, so passing an asset
|
| 536 |
+
this architecture or option set has no use for is fine - handing over a
|
| 537 |
+
whole downloaded model directory works - but a misspelled name is reported
|
| 538 |
+
against the key you passed instead of surfacing later as a missing-asset
|
| 539 |
+
failure.
|
| 540 |
+
|
| 541 |
+
When ``memory[i]`` is non-NULL and ``memory_sizes[i]`` > 0, that buffer is
|
| 542 |
+
used as the asset bytes. The library does not copy the model buffers (the
|
| 543 |
+
ONNX Runtime sessions read them directly), so the buffers must outlive the
|
| 544 |
+
transcriber, exactly as for moonshine_load_transcriber_from_memory. When
|
| 545 |
+
``memory[i]`` is NULL or ``memory_sizes[i]`` is zero, ``filenames[i]`` is
|
| 546 |
+
also used as a filesystem path (relative to the current working directory
|
| 547 |
+
unless absolute), so callers can mix in-memory and on-disk assets.
|
| 548 |
+
|
| 549 |
+
All other parameters behave as in the other transcriber loaders. Returns a
|
| 550 |
+
non-negative handle on success, or a negative error code on failure. */
|
| 551 |
+
MOONSHINE_EXPORT int32_t moonshine_load_transcriber_from_memory_files(
|
| 552 |
+
const char **filenames, const uint8_t **memory,
|
| 553 |
+
const uint64_t *memory_sizes, uint64_t file_count, uint32_t model_arch,
|
| 554 |
+
const struct moonshine_option_t *options, uint64_t options_count,
|
| 555 |
+
int32_t moonshine_version);
|
| 556 |
+
|
| 557 |
+
/* Releases all resources used by the transcriber. Subsequent transcriber
|
| 558 |
+
creation calls may reuse this transcriber's ID, so ensure you remove
|
| 559 |
+
all references to it in your client code after freeing it.*/
|
| 560 |
+
MOONSHINE_EXPORT void moonshine_free_transcriber(int32_t transcriber_handle);
|
| 561 |
+
|
| 562 |
+
/* Given an array of PCM audio data, identifies sections of speech and
|
| 563 |
+
transcribes them into text. This is the call to use if you're analyzing audio
|
| 564 |
+
from a file or other static source where you have all the audio data at once.
|
| 565 |
+
If you are transcribing audio from a live microphone or other real-time
|
| 566 |
+
source, you should use the streaming API instead, since it offers lower
|
| 567 |
+
latency for those use cases.
|
| 568 |
+
|
| 569 |
+
`transcriber_handle` should be a handle to a transcriber returned by
|
| 570 |
+
moonshine_load_transcriber_from_files or
|
| 571 |
+
moonshine_load_transcriber_from_memory.
|
| 572 |
+
|
| 573 |
+
`audio_data` should be a pointer to an array of PCM audio data, between -1.0
|
| 574 |
+
and 1.0, at a sample rate of `sample_rate` Hz. Internally the library uses
|
| 575 |
+
16,000 Hz, so to avoid resampling you should capture audio at this rate if
|
| 576 |
+
possible.
|
| 577 |
+
|
| 578 |
+
`audio_length` should be the number of samples in the audio data array.
|
| 579 |
+
|
| 580 |
+
`sample_rate` should be the sample rate of the audio data, in Hz.
|
| 581 |
+
`flags` should be a bitwise OR of flags. Currently the only supported flag
|
| 582 |
+
is MOONSHINE_FLAG_SPELLING_MODE, which applies alphanumeric-spelling fusion
|
| 583 |
+
to completed lines (requires the transcriber to have been loaded with a
|
| 584 |
+
spelling model; otherwise the flag is a no-op). Pass zero for the default
|
| 585 |
+
behavior.
|
| 586 |
+
|
| 587 |
+
`out_transcript` should be a pointer to a pointer to a transcript_t struct.
|
| 588 |
+
The transcript_t struct will be populated with the transcript data, which
|
| 589 |
+
consists of a list of lines, each with text, audio data, and timestamps.
|
| 590 |
+
This data is owned by the transcriber and is valid until the next call to
|
| 591 |
+
that transcriber, or until the transcriber is freed.
|
| 592 |
+
|
| 593 |
+
The return value is zero on success, or a non-zero error code on failure.
|
| 594 |
+
The error code can be converted to a human-readable string using
|
| 595 |
+
moonshine_error_to_string.
|
| 596 |
+
*/
|
| 597 |
+
MOONSHINE_EXPORT int32_t moonshine_transcribe_without_streaming(
|
| 598 |
+
int32_t transcriber_handle, float *audio_data, uint64_t audio_length,
|
| 599 |
+
int32_t sample_rate, uint32_t flags, struct transcript_t **out_transcript);
|
| 600 |
+
|
| 601 |
+
/* Streaming allows the library to incrementally return updated results as
|
| 602 |
+
new audio data becomes available in real-time. This approach allows us to
|
| 603 |
+
produce results with lower latency than non-streaming approaches, by
|
| 604 |
+
reusing calculations done on earlier audio data.
|
| 605 |
+
|
| 606 |
+
The `transcriber_handle` should be a handle to a transcriber returned by
|
| 607 |
+
moonshine_load_transcriber_from_files or
|
| 608 |
+
moonshine_load_transcriber_from_memory. A single transcriber can have
|
| 609 |
+
multiple streams associated with it, and each stream can be used to
|
| 610 |
+
transcribe a separate audio stream.
|
| 611 |
+
|
| 612 |
+
The `flags` should be a bitwise OR of flags. None are currently supported so
|
| 613 |
+
this should always be zero.
|
| 614 |
+
|
| 615 |
+
The return value is a handle to a stream, which can be used to identify the
|
| 616 |
+
stream in subsequent calls. If there was an error, a negative value is
|
| 617 |
+
returned. The error code can be converted to a human-readable string using
|
| 618 |
+
moonshine_error_to_string.
|
| 619 |
+
|
| 620 |
+
Below is some pseudocode showing an example of how to use streaming. In a
|
| 621 |
+
real application you'll want to check the return value of the functions and
|
| 622 |
+
handle errors appropriately. `get_audio_from_microphone` stands in for your
|
| 623 |
+
capture loop: feed each chunk to
|
| 624 |
+
moonshine_transcribe_add_audio_to_stream (safe from an audio callback),
|
| 625 |
+
then call moonshine_transcribe_stream on another thread when you want an
|
| 626 |
+
updated transcript. A more complete example is the streaming test in
|
| 627 |
+
core/moonshine-c-api-test.cpp.
|
| 628 |
+
|
| 629 |
+
```c
|
| 630 |
+
int32_t transcriber_handle = moonshine_load_transcriber_from_files(
|
| 631 |
+
"path/to/models", MOONSHINE_MODEL_ARCH_BASE, NULL, 0,
|
| 632 |
+
MOONSHINE_HEADER_VERSION);
|
| 633 |
+
int32_t stream_handle = moonshine_create_stream(transcriber_handle, 0);
|
| 634 |
+
moonshine_start_stream(transcriber_handle, stream_handle);
|
| 635 |
+
|
| 636 |
+
float* latest_audio_data;
|
| 637 |
+
size_t latest_audio_data_length;
|
| 638 |
+
while (get_audio_from_microphone(&latest_audio_data,
|
| 639 |
+
&latest_audio_data_length)) {
|
| 640 |
+
moonshine_transcribe_add_audio_to_stream(transcriber_handle,
|
| 641 |
+
stream_handle, latest_audio_data, latest_audio_data_length,
|
| 642 |
+
microphone_sample_rate, 0);
|
| 643 |
+
if (time_since_last_transcription < min_time_between_transcriptions) {
|
| 644 |
+
continue;
|
| 645 |
+
}
|
| 646 |
+
transcript_t *partial_transcript = NULL;
|
| 647 |
+
moonshine_transcribe_stream(transcriber_handle,
|
| 648 |
+
stream_handle, 0, &partial_transcript);
|
| 649 |
+
printf("%s\n", moonshine_transcript_to_string(partial_transcript));
|
| 650 |
+
}
|
| 651 |
+
moonshine_stop_stream(transcriber_handle, stream_handle);
|
| 652 |
+
|
| 653 |
+
transcript_t *final_transcript = NULL;
|
| 654 |
+
moonshine_transcribe_stream(transcriber_handle, stream_handle, 0,
|
| 655 |
+
&final_transcript);
|
| 656 |
+
printf("%s\n", moonshine_transcript_to_string(final_transcript));
|
| 657 |
+
|
| 658 |
+
moonshine_free_stream(transcriber_handle, stream_handle);
|
| 659 |
+
moonshine_free_transcriber(transcriber_handle);
|
| 660 |
+
```
|
| 661 |
+
|
| 662 |
+
The transcripts that are returned consist of a list of lines, each with
|
| 663 |
+
text, audio data, timestamp, duration, and other metadata. This metadata
|
| 664 |
+
includes an `is_updated` flag, which is set to 1 if the line has been updated
|
| 665 |
+
since the last call to moonshine_transcribe_stream. You can use this as a
|
| 666 |
+
"dirty flag" to determine how to update your UI in a minimal way, touching
|
| 667 |
+
only the elements that have changed. Updated lines only appear at the end of
|
| 668 |
+
the list of lines, and once the `is_complete` flag is set to 1 for a line,
|
| 669 |
+
its text and timing will never change again.
|
| 670 |
+
|
| 671 |
+
The one exception is speaker information: when the `identify_speakers`
|
| 672 |
+
option is enabled, speaker spans for recent audio can be revised on any call
|
| 673 |
+
to moonshine_transcribe_stream, since diarization re-clusters a sliding
|
| 674 |
+
window of recent speech. Older assignments are frozen. Watch the
|
| 675 |
+
`have_speakers_changed` flag to detect these revisions.
|
| 676 |
+
*/
|
| 677 |
+
|
| 678 |
+
/* Creates a stream. This function returns a handle to the stream, which can be
|
| 679 |
+
used to identify the stream in subsequent calls. If there was an error, a
|
| 680 |
+
negative value is returned. The error code can be converted to a
|
| 681 |
+
human-readable string using moonshine_error_to_string.
|
| 682 |
+
*/
|
| 683 |
+
MOONSHINE_EXPORT int32_t moonshine_create_stream(int32_t transcriber_handle,
|
| 684 |
+
uint32_t flags);
|
| 685 |
+
|
| 686 |
+
/* Releases the resources used by a stream.
|
| 687 |
+
Subsequent stream creation calls may reuse this stream's ID, so ensure you
|
| 688 |
+
remove all references to it in your client code after freeing it.*/
|
| 689 |
+
MOONSHINE_EXPORT int32_t moonshine_free_stream(int32_t transcriber_handle,
|
| 690 |
+
int32_t stream_handle);
|
| 691 |
+
|
| 692 |
+
/* Starts a stream. This should be called before adding audio or calling
|
| 693 |
+
moonshine_transcribe_stream. Start/stop are supported because there may
|
| 694 |
+
sometimes be a discontinuity in the audio input, for example when the user
|
| 695 |
+
mutes their input, so we need a way to start fresh after a break like this.
|
| 696 |
+
This function returns zero on success, or a non-zero error code on failure.
|
| 697 |
+
The error code can be converted to a human-readable string using
|
| 698 |
+
moonshine_error_to_string.
|
| 699 |
+
*/
|
| 700 |
+
MOONSHINE_EXPORT int32_t moonshine_start_stream(int32_t transcriber_handle,
|
| 701 |
+
int32_t stream_handle);
|
| 702 |
+
|
| 703 |
+
/* Stops a stream. Further moonshine_transcribe_add_audio_to_stream calls are
|
| 704 |
+
rejected, but audio that has not yet been analyzed is kept. Call
|
| 705 |
+
moonshine_transcribe_stream afterwards to drain that leftover audio and get
|
| 706 |
+
the final transcript, with all lines marked complete. This function returns
|
| 707 |
+
zero on success, or a non-zero error code on failure. The error code can be
|
| 708 |
+
converted to a human-readable string using moonshine_error_to_string.
|
| 709 |
+
*/
|
| 710 |
+
MOONSHINE_EXPORT int32_t moonshine_stop_stream(int32_t transcriber_handle,
|
| 711 |
+
int32_t stream_handle);
|
| 712 |
+
|
| 713 |
+
/* Call this when new audio data becomes available from your microphone or other
|
| 714 |
+
audio source. This function will add the audio data to the stream's buffer,
|
| 715 |
+
but it will not transcribe it or do any other processing, so this should be
|
| 716 |
+
safe to call frequently even from time-critical threads. The size of the
|
| 717 |
+
input audio doesn't have any impact on performance, so you should call this
|
| 718 |
+
with whatever the natural chunk size is for your audio source. It is up to
|
| 719 |
+
you to call moonshine_transcribe_stream when you want an updated transcript,
|
| 720 |
+
the frequency of which should be determined by your application's latency and
|
| 721 |
+
compute budgets.
|
| 722 |
+
|
| 723 |
+
`transcriber_handle` should be a handle to a transcriber returned by
|
| 724 |
+
moonshine_load_transcriber_from_files or
|
| 725 |
+
moonshine_load_transcriber_from_memory.
|
| 726 |
+
|
| 727 |
+
`stream_handle` should be a handle to a stream returned by
|
| 728 |
+
moonshine_create_stream.
|
| 729 |
+
|
| 730 |
+
`new_audio_data` should be a pointer to an array of PCM audio data, between
|
| 731 |
+
-1.0 and 1.0, at a sample rate of `sample_rate` Hz. `audio_length` should be
|
| 732 |
+
the number of samples in the audio data array.
|
| 733 |
+
|
| 734 |
+
`sample_rate` should be the sample rate of the audio data, in Hz.
|
| 735 |
+
|
| 736 |
+
`flags` should be a bitwise OR of flags. None are currently supported so
|
| 737 |
+
this should always be zero.
|
| 738 |
+
|
| 739 |
+
The return value is zero on success, or a non-zero error code on failure.
|
| 740 |
+
The error code can be converted to a human-readable string using
|
| 741 |
+
moonshine_error_to_string.
|
| 742 |
+
*/
|
| 743 |
+
MOONSHINE_EXPORT int32_t moonshine_transcribe_add_audio_to_stream(
|
| 744 |
+
int32_t transcriber_handle, int32_t stream_handle,
|
| 745 |
+
const float *new_audio_data, uint64_t audio_length, int32_t sample_rate,
|
| 746 |
+
uint32_t flags);
|
| 747 |
+
|
| 748 |
+
/* Analyzes all the audio data in the stream and returns an updated transcript
|
| 749 |
+
of all the speech segments found. By default this function will only perform
|
| 750 |
+
full analysis on the audio data if there has been more than 200ms of new
|
| 751 |
+
samples since the last complete analysis. This is to ensure that too-frequent
|
| 752 |
+
calls to this function don't result in poor performance. This can be
|
| 753 |
+
overridden by setting the MOONSHINE_FLAG_FORCE_UPDATE flag.
|
| 754 |
+
|
| 755 |
+
After moonshine_stop_stream, leftover audio is analyzed even if it is
|
| 756 |
+
shorter than that interval, so the stop-then-transcribe_stream sequence in
|
| 757 |
+
the example above produces a complete transcript. You do not need
|
| 758 |
+
MOONSHINE_FLAG_FORCE_UPDATE for that final call, and you do not need to
|
| 759 |
+
have pulled partial transcripts first.
|
| 760 |
+
|
| 761 |
+
`transcriber_handle` should be a handle to a transcriber returned by
|
| 762 |
+
moonshine_load_transcriber_from_files or
|
| 763 |
+
moonshine_load_transcriber_from_memory.
|
| 764 |
+
|
| 765 |
+
`stream_handle` should be a handle to a stream returned by
|
| 766 |
+
moonshine_create_stream.
|
| 767 |
+
|
| 768 |
+
`flags` should be a bitwise OR of flags. Currently the only supported flag is
|
| 769 |
+
MOONSHINE_FLAG_FORCE_UPDATE, which ignores the time-based caching logic to
|
| 770 |
+
ensure the stream is fully analyzed by the models.
|
| 771 |
+
|
| 772 |
+
`out_transcript` should be a pointer to a pointer to a transcript_t struct.
|
| 773 |
+
The transcript_t struct will be populated with the transcript data, which
|
| 774 |
+
consists of a list of lines, each with text, audio data, and timestamps.
|
| 775 |
+
This data is owned by the transcriber and is valid until the next call to
|
| 776 |
+
that transcriber, or until the transcriber is freed.
|
| 777 |
+
|
| 778 |
+
The return value is zero on success, or a non-zero error code on failure.
|
| 779 |
+
The error code can be converted to a human-readable string using
|
| 780 |
+
moonshine_error_to_string.
|
| 781 |
+
*/
|
| 782 |
+
MOONSHINE_EXPORT int32_t moonshine_transcribe_stream(
|
| 783 |
+
int32_t transcriber_handle, int32_t stream_handle, uint32_t flags,
|
| 784 |
+
struct transcript_t **out_transcript);
|
| 785 |
+
|
| 786 |
+
/* ------------------------------ EMBEDDING MODEL --------------------------- */
|
| 787 |
+
|
| 788 |
+
/* Supported embedding model architectures. */
|
| 789 |
+
#define MOONSHINE_EMBEDDING_MODEL_ARCH_GEMMA_300M (0)
|
| 790 |
+
|
| 791 |
+
/* Creates an embedding model from files on disk.
|
| 792 |
+
|
| 793 |
+
`model_path` should be the path to the directory containing the embedding
|
| 794 |
+
model files (ONNX model and tokenizer.bin).
|
| 795 |
+
|
| 796 |
+
`model_arch` should be one of the MOONSHINE_EMBEDDING_MODEL_ARCH_* constants.
|
| 797 |
+
Currently only MOONSHINE_EMBEDDING_MODEL_ARCH_GEMMA_300M is supported.
|
| 798 |
+
|
| 799 |
+
`model_variant` specifies which model variant to load: "q4" or "q8".
|
| 800 |
+
Pass NULL to use the default "q4" variant. "fp32", "fp16", and "q4f16"
|
| 801 |
+
are no longer supported and return an error.
|
| 802 |
+
|
| 803 |
+
Returns a non-negative handle on success, or a negative error code on
|
| 804 |
+
failure. The error code can be converted to a human-readable string using
|
| 805 |
+
moonshine_error_to_string.
|
| 806 |
+
*/
|
| 807 |
+
MOONSHINE_EXPORT int32_t moonshine_create_embedding_model(
|
| 808 |
+
const char *model_path, uint32_t model_arch, const char *model_variant);
|
| 809 |
+
|
| 810 |
+
/* Creates an embedding model from in-memory model buffers.
|
| 811 |
+
|
| 812 |
+
This mirrors moonshine_load_transcriber_from_memory_files and
|
| 813 |
+
moonshine_create_tts_synthesizer_from_memory: `filenames[i]` is the canonical
|
| 814 |
+
asset filename (as listed by moonshine_get_embedding_dependencies, e.g.
|
| 815 |
+
`model_q4.ort` and `tokenizer.bin`) and `memory[i]` / `memory_sizes[i]` are
|
| 816 |
+
the corresponding bytes. The embedding model must be a single self-contained
|
| 817 |
+
all-in-one `.ort` file (no external-data sidecar); the tokenizer is
|
| 818 |
+
`tokenizer.bin`. The library copies the bytes it needs, so the buffers only
|
| 819 |
+
need to remain valid for the duration of this call.
|
| 820 |
+
|
| 821 |
+
`model_arch` should be one of the MOONSHINE_EMBEDDING_MODEL_ARCH_* constants.
|
| 822 |
+
`model_variant` selects the variant ("q4", "q8";
|
| 823 |
+
NULL defaults to "q4") and is only used to pick the model file when the
|
| 824 |
+
filename keys do not make it unambiguous. "fp32", "fp16", and "q4f16" are
|
| 825 |
+
no longer supported.
|
| 826 |
+
|
| 827 |
+
Returns a non-negative handle on success, or a negative error code on
|
| 828 |
+
failure.
|
| 829 |
+
*/
|
| 830 |
+
MOONSHINE_EXPORT int32_t moonshine_create_embedding_model_from_memory(
|
| 831 |
+
uint32_t model_arch, const char *model_variant, const char **filenames,
|
| 832 |
+
uint64_t filenames_count, const uint8_t **memory,
|
| 833 |
+
const uint64_t *memory_sizes, const struct moonshine_option_t *options,
|
| 834 |
+
uint64_t options_count, int32_t moonshine_version);
|
| 835 |
+
|
| 836 |
+
/* Frees an embedding model and all its resources. */
|
| 837 |
+
MOONSHINE_EXPORT void moonshine_free_embedding_model(
|
| 838 |
+
int32_t embedding_model_handle);
|
| 839 |
+
|
| 840 |
+
/* Calculates the embedding for a given sentence.
|
| 841 |
+
|
| 842 |
+
On success, ``*out_embedding`` is set to a heap-allocated array of floats and
|
| 843 |
+
``*out_embedding_size`` is set to the number of elements. Release the array
|
| 844 |
+
with ``moonshine_free_embedding``.
|
| 845 |
+
|
| 846 |
+
Returns zero on success, or a non-zero error code on failure.
|
| 847 |
+
*/
|
| 848 |
+
MOONSHINE_EXPORT int32_t moonshine_calculate_embedding(
|
| 849 |
+
int32_t embedding_model_handle, const char *sentence, float **out_embedding,
|
| 850 |
+
uint64_t *out_embedding_size, const char *model_name);
|
| 851 |
+
|
| 852 |
+
/* Frees an embedding returned by moonshine_calculate_embedding. */
|
| 853 |
+
MOONSHINE_EXPORT void moonshine_free_embedding(float *embedding);
|
| 854 |
+
|
| 855 |
+
/* Calculates the cosine similarity between two embedding vectors.
|
| 856 |
+
|
| 857 |
+
Both ``embedding_a`` and ``embedding_b`` must have ``embedding_size``
|
| 858 |
+
elements. The result is written to ``*out_similarity`` and is in the
|
| 859 |
+
range [-1, 1] (1 = identical, 0 = orthogonal, -1 = opposite).
|
| 860 |
+
|
| 861 |
+
Returns zero on success, or a non-zero error code on failure.
|
| 862 |
+
*/
|
| 863 |
+
MOONSHINE_EXPORT int32_t moonshine_calculate_embedding_distance(
|
| 864 |
+
int32_t embedding_model_handle, const float *embedding_a,
|
| 865 |
+
const float *embedding_b, uint64_t embedding_size, float *out_similarity);
|
| 866 |
+
|
| 867 |
+
/* ------------------------------ SPEECH CLIPS --------------------------- */
|
| 868 |
+
|
| 869 |
+
/* A short window of mostly-speech audio pulled out of a longer recording,
|
| 870 |
+
returned by moonshine_extract_speech_clip. */
|
| 871 |
+
struct moonshine_speech_clip_t {
|
| 872 |
+
/* 16 kHz mono PCM. NULL unless ``is_complete`` is non-zero. Allocated with
|
| 873 |
+
malloc; release with moonshine_free_buffer. */
|
| 874 |
+
float *audio_data;
|
| 875 |
+
uint64_t audio_length;
|
| 876 |
+
/* Where the window starts in the input recording, in seconds. */
|
| 877 |
+
float start_time;
|
| 878 |
+
/* How much of the window is speech, in seconds. Useful for showing progress
|
| 879 |
+
while the caller is still recording. */
|
| 880 |
+
float speech_duration;
|
| 881 |
+
/* Non-zero once a window with enough speech in it was found. */
|
| 882 |
+
int32_t is_complete;
|
| 883 |
+
/* UTF-8 transcript of the clip when the TTS synthesizer owns a clone ASR
|
| 884 |
+
and the window was complete enough to refine. NULL otherwise. Allocated
|
| 885 |
+
with malloc; release with moonshine_free_buffer. */
|
| 886 |
+
char *transcript;
|
| 887 |
+
};
|
| 888 |
+
|
| 889 |
+
/* Finds the best short window of speech in a recording, for use as the
|
| 890 |
+
reference clip in zero-shot voice cloning.
|
| 891 |
+
|
| 892 |
+
``tts_synthesizer_handle`` must be a valid synthesizer from
|
| 893 |
+
``moonshine_create_tts_synthesizer_*``. The call always runs the built-in
|
| 894 |
+
voice-activity detector (no download) over ``audio_data``, slides a window
|
| 895 |
+
of ``clip_duration_seconds`` across the result, and returns the window with
|
| 896 |
+
the most speech. If no window contains at least ``minimum_speech_seconds``
|
| 897 |
+
of speech, ``out_clip->is_complete`` is zero and no audio is returned; the
|
| 898 |
+
caller should record more and call again (streaming capture).
|
| 899 |
+
|
| 900 |
+
Extract is VAD-only and stays cheap enough for the capture loop. When
|
| 901 |
+
ZipVoice is later created without ``zipvoice_clone_transcript``, the owned
|
| 902 |
+
clone ASR (from ``g2p_root/clone_asr/`` or ``clone_asr/...`` memory keys)
|
| 903 |
+
refines the clip and fills the transcript once — see
|
| 904 |
+
``moonshine_get_tts_dependencies``.
|
| 905 |
+
|
| 906 |
+
The returned clip is always 16 kHz mono regardless of ``sample_rate``.
|
| 907 |
+
|
| 908 |
+
Recognised ``options``:
|
| 909 |
+
``clip_duration_seconds`` length of the window (default 4).
|
| 910 |
+
``minimum_speech_seconds`` speech required in it (default 2).
|
| 911 |
+
``vad_threshold`` speech probability threshold (default 0.5).
|
| 912 |
+
``tail_pad_seconds`` extra audio after the VAD window (default 0).
|
| 913 |
+
|
| 914 |
+
Returns zero on success, or a non-zero error code on failure. The error code
|
| 915 |
+
can be converted to a human-readable string using moonshine_error_to_string.
|
| 916 |
+
*/
|
| 917 |
+
MOONSHINE_EXPORT int32_t moonshine_extract_speech_clip(
|
| 918 |
+
const float *audio_data, uint64_t audio_length, int32_t sample_rate,
|
| 919 |
+
int32_t tts_synthesizer_handle, const struct moonshine_option_t *options,
|
| 920 |
+
uint64_t options_count, struct moonshine_speech_clip_t *out_clip);
|
| 921 |
+
|
| 922 |
+
/* ------------------------------ TEXT TO SPEECH ------------------------- */
|
| 923 |
+
|
| 924 |
+
/* Creates a text to speech synthesizer from files on disk.
|
| 925 |
+
Returns a non-negative handle on success, or a non-zero error code on
|
| 926 |
+
failure. The error code can be converted to a human-readable string using
|
| 927 |
+
moonshine_error_to_string.
|
| 928 |
+
Pass option ``voice`` as ``kokoro_<id>`` or ``piper_<stem>`` to select the
|
| 929 |
+
vocoder, or as a bare Kokoro id / Piper stem when using the default auto
|
| 930 |
+
choice (and other TTS paths via ``moonshine_option_t`` as documented for
|
| 931 |
+
``MoonshineTTSOptions``). ``engine`` / ``vocoder_engine`` options are
|
| 932 |
+
ignored.
|
| 933 |
+
|
| 934 |
+
ZipVoice (zero-shot voice cloning) is selected with ``voice`` =
|
| 935 |
+
``zipvoice_<id>`` for a built-in VCTK reference voice (e.g.
|
| 936 |
+
``zipvoice_american_female``, ``zipvoice_indian_male``), or a bare
|
| 937 |
+
``zipvoice`` together with a caller-supplied reference clip via
|
| 938 |
+
``moonshine_create_tts_synthesizer_from_memory`` (key
|
| 939 |
+
``zipvoice/clone_audio``). ZipVoice model assets
|
| 940 |
+
(``zipvoice/text_encoder.ort``, ``zipvoice/fm_decoder.ort``,
|
| 941 |
+
``zipvoice/vocoder.ort``, ``zipvoice/tokens.txt``,
|
| 942 |
+
``zipvoice/model.json``) are resolved under ``g2p_root`` or supplied in
|
| 943 |
+
memory. English only for now.
|
| 944 |
+
|
| 945 |
+
For ZipVoice cloning, download TTS dependencies (including the
|
| 946 |
+
``role":"clone_asr"`` group) under ``g2p_root`` so ``g2p_root/clone_asr/``
|
| 947 |
+
holds the catalog STT, or pass ``clone_asr/<stt-filename>`` memory keys to
|
| 948 |
+
``moonshine_create_tts_synthesizer_from_memory``. The library owns that ASR
|
| 949 |
+
for the synthesizer lifetime and uses it inside
|
| 950 |
+
``moonshine_extract_speech_clip``. When a caller-supplied
|
| 951 |
+
``zipvoice/clone_audio`` clip has no ``zipvoice_clone_transcript``, the clip
|
| 952 |
+
is refined with that ASR at create time.
|
| 953 |
+
|
| 954 |
+
Phonon (Gradium's 31M-parameter autoregressive English model,
|
| 955 |
+
https://huggingface.co/gradium/phonon-31m-en, Apache 2.0, built on Kyutai's
|
| 956 |
+
Pocket TTS and Mimi codec) is selected with ``voice`` = ``phonon_<id>`` for
|
| 957 |
+
a catalog voice listed in ``phonon/voices.json`` (e.g. ``phonon_zoey``; the
|
| 958 |
+
catalog is Gradium's Apache 2.0 ``phonon-voices`` set), or a bare ``phonon``
|
| 959 |
+
with a caller-supplied voice file under key ``phonon/voice`` (a Phonon
|
| 960 |
+
``.safetensors`` of speaker latents, such as a voice designed or cloned in
|
| 961 |
+
Gradium's hosted Studio and downloaded for Phonon; the speaker encoder is
|
| 962 |
+
not published, so on-device cloning is ZipVoice only). Model assets are the
|
| 963 |
+
six
|
| 964 |
+
``phonon/<graph>.ort`` files, ``phonon/model.json``, ``phonon/tokenizer.bin``
|
| 965 |
+
and
|
| 966 |
+
``phonon/voices/<id>.safetensors``. Options: ``phonon_temperature`` (0 is
|
| 967 |
+
deterministic; default 0.3), ``phonon_seed``, ``phonon_duration_delta``
|
| 968 |
+
(direct duration conditioning, positive is slower; otherwise derived from
|
| 969 |
+
``speed``), ``phonon_normalize_text``. Phonon reads text, so
|
| 970 |
+
``moonshine_phonemes_to_speech`` is refused for it. Streaming cuts on
|
| 971 |
+
generated frames rather than planned ones, so the first chunk arrives after
|
| 972 |
+
roughly ``stream_first_chunk_seconds`` of audio has been generated.
|
| 973 |
+
*/
|
| 974 |
+
MOONSHINE_EXPORT int32_t moonshine_create_tts_synthesizer_from_files(
|
| 975 |
+
const char *language, const char **filenames, uint64_t filenames_count,
|
| 976 |
+
const struct moonshine_option_t *options, uint64_t options_count,
|
| 977 |
+
int32_t moonshine_version);
|
| 978 |
+
|
| 979 |
+
/* Creates a text to speech synthesizer from memory.
|
| 980 |
+
Returns a non-negative handle on success, or a non-zero error code on
|
| 981 |
+
failure. The error code can be converted to a human-readable string using
|
| 982 |
+
moonshine_error_to_string.
|
| 983 |
+
|
| 984 |
+
``filenames[i]`` is the canonical ``MoonshineTTSOptions::files`` key (e.g.
|
| 985 |
+
``kokoro/prosody.model.ort``, ``kokoro/prosody.weights.ort``,
|
| 986 |
+
``kokoro/decoder.model.ort``, ``kokoro/decoder.weights.ort``,
|
| 987 |
+
``kokoro/config.json``, ``kokoro/voices/af_heart.kokorovoice``,
|
| 988 |
+
``piper/onnx``, ``piper/onnx.json``, ``zipvoice/text_encoder.ort``,
|
| 989 |
+
``zipvoice/fm_decoder.ort``, ``zipvoice/vocoder.ort``,
|
| 990 |
+
``zipvoice/tokens.txt``, ``zipvoice/model.json``). For ZipVoice a
|
| 991 |
+
caller-supplied reference clip is passed as key ``zipvoice/clone_audio``
|
| 992 |
+
(raw little-endian float32 mono PCM); set ``zipvoice_clone_sample_rate`` and,
|
| 993 |
+
optionally, ``zipvoice_clone_transcript``. When the transcript is omitted,
|
| 994 |
+
supply ``clone_asr/<stt-filename>`` keys (from the ZipVoice TTS dependency
|
| 995 |
+
``clone_asr`` group) so the library can refine and auto-transcribe the clip
|
| 996 |
+
with its owned ASR. When ``memory[i]`` is non-NULL and
|
| 997 |
+
``memory_sizes[i]`` > 0, that buffer is used as the asset bytes; the library
|
| 998 |
+
does not copy it—keep the buffers valid until
|
| 999 |
+
``moonshine_free_tts_synthesizer``. When ``memory[i]`` is NULL or
|
| 1000 |
+
``memory_sizes[i]`` is zero, the key string is also used as a path relative
|
| 1001 |
+
to ``g2p_options.g2p_root`` (from ``options``), same as path-only map
|
| 1002 |
+
entries.
|
| 1003 |
+
|
| 1004 |
+
Other ``options`` are parsed like
|
| 1005 |
+
``moonshine_create_tts_synthesizer_from_files``.
|
| 1006 |
+
*/
|
| 1007 |
+
MOONSHINE_EXPORT int32_t moonshine_create_tts_synthesizer_from_memory(
|
| 1008 |
+
const char *language, const char **filenames,
|
| 1009 |
+
const uint64_t filenames_count, const uint8_t **memory,
|
| 1010 |
+
const uint64_t *memory_sizes, const struct moonshine_option_t *options,
|
| 1011 |
+
uint64_t options_count, int32_t moonshine_version);
|
| 1012 |
+
|
| 1013 |
+
/* Releases the resources used by a text to speech synthesizer. */
|
| 1014 |
+
MOONSHINE_EXPORT void moonshine_free_tts_synthesizer(
|
| 1015 |
+
int32_t tts_synthesizer_handle);
|
| 1016 |
+
|
| 1017 |
+
/* Returns G2P-only canonical asset keys for one or more languages.
|
| 1018 |
+
``languages`` is comma-separated CLI tags (same as ``moonshine_create_*``
|
| 1019 |
+
``language``); an empty string (or NULL) means all known languages (union of
|
| 1020 |
+
keys).
|
| 1021 |
+
``options`` / ``options_count``: same ``moonshine_option_t`` entries as
|
| 1022 |
+
grapheme phonemizer / G2P
|
| 1023 |
+
(``g2p_root``, ``spanish_narrow_obstruents``, ``oov_onnx_override``, …).
|
| 1024 |
+
TTS-only keys
|
| 1025 |
+
(``voice``, deprecated ``vocoder_engine`` / ``engine``, Piper/Kokoro paths)
|
| 1026 |
+
are ignored here. Non-empty values for in-memory override keys add those
|
| 1027 |
+
canonical key names to the list. On success, writes a comma-separated list to
|
| 1028 |
+
``*out_dependencies_json`` and returns
|
| 1029 |
+
``MOONSHINE_ERROR_NONE``. The buffer is allocated with ``malloc``; release
|
| 1030 |
+
with ``free``. On failure (e.g. unknown language token), logs and returns a
|
| 1031 |
+
non-zero error code and sets
|
| 1032 |
+
``*out_dependencies_json`` to NULL.
|
| 1033 |
+
*/
|
| 1034 |
+
MOONSHINE_EXPORT int32_t moonshine_get_g2p_dependencies(
|
| 1035 |
+
const char *languages, const struct moonshine_option_t *options,
|
| 1036 |
+
uint64_t options_count, char **out_dependencies_json);
|
| 1037 |
+
|
| 1038 |
+
/* Returns merged G2P + TTS vocoder download dependencies as a JSON object with
|
| 1039 |
+
a ``groups`` array (same shape as ``moonshine_get_stt_dependencies``). Each
|
| 1040 |
+
group is ``{ "base_url", "files": [{name,url,size,checksum,checksum_type}]
|
| 1041 |
+
}``.
|
| 1042 |
+
``languages`` is comma-separated; empty or NULL means all known languages.
|
| 1043 |
+
``options`` / ``options_count``: same entries as
|
| 1044 |
+
``moonshine_create_tts_synthesizer_from_files``
|
| 1045 |
+
(``voice`` with optional ``kokoro_`` / ``piper_`` / ``zipvoice_`` prefix,
|
| 1046 |
+
``g2p_root``, …). Vocoder keys follow Kokoro vs Piper vs ZipVoice selection.
|
| 1047 |
+
|
| 1048 |
+
When ``voice`` selects ZipVoice, an additional group with
|
| 1049 |
+
``"role":"clone_asr"`` lists the catalog-default STT for the language
|
| 1050 |
+
(including the attention decoder for word timestamps). Local ``name``s are
|
| 1051 |
+
prefixed ``clone_asr/``;
|
| 1052 |
+
``url``s point at the STT CDN. Bindings should download those files under
|
| 1053 |
+
``g2p_root/clone_asr/`` (or pass ``clone_asr/...`` memory keys on create).
|
| 1054 |
+
|
| 1055 |
+
On success, ``*out_dependencies_json`` is a NUL-terminated JSON object; free
|
| 1056 |
+
with ``free``.
|
| 1057 |
+
*/
|
| 1058 |
+
MOONSHINE_EXPORT int32_t moonshine_get_tts_dependencies(
|
| 1059 |
+
const char *languages, const struct moonshine_option_t *options,
|
| 1060 |
+
uint64_t options_count, char **out_dependencies_json);
|
| 1061 |
+
|
| 1062 |
+
/* Returns known TTS voices for the requested languages with availability state.
|
| 1063 |
+
``languages`` is comma-separated; empty or NULL means all registered catalog
|
| 1064 |
+
languages (same tag set as G2P dependencies) that have a resolved TTS layout.
|
| 1065 |
+
``options`` / ``options_count``: same entries as
|
| 1066 |
+
``moonshine_create_tts_synthesizer_from_files``
|
| 1067 |
+
(``voice`` prefix selects vocoder for listing; ``vocoder_engine`` /
|
| 1068 |
+
``engine`` are ignored; Piper/Kokoro path overrides). For accurate ``found``
|
| 1069 |
+
/ ``missing``, set an asset root with
|
| 1070 |
+
``g2p_root`` or the aliases ``path_root``, ``tts_root``, or ``model_root``
|
| 1071 |
+
(see
|
| 1072 |
+
``MoonshineTTSOptions::parse_options``). If none are set, the implementation
|
| 1073 |
+
uses the process current working directory. Language bindings typically
|
| 1074 |
+
default this to their download/cache directory. The ``voice`` option does not
|
| 1075 |
+
filter the list.
|
| 1076 |
+
|
| 1077 |
+
On success, ``*out_voices_json`` is a NUL-terminated JSON object mapping each
|
| 1078 |
+
language tag to a JSON array of objects ``{"id":"<voice>","state":"found"}``
|
| 1079 |
+
or ``{"id":"<voice>","state":"missing"}``. Voice ids are prefixed with
|
| 1080 |
+
``kokoro_`` or ``piper_``. Kokoro uses the upstream Kokoro-82M voice id
|
| 1081 |
+
catalog plus any extra ``*.kokorovoice`` in the bundle; Piper lists the
|
| 1082 |
+
language default voice stem plus every voice in the resolved voices
|
| 1083 |
+
directory, in either shipped form (``<stem>.ort``, or the split
|
| 1084 |
+
``<stem>.model.ort`` plus ``<stem>.weights.ort`` pair). ``found`` means the
|
| 1085 |
+
asset is on disk or supplied via the in-memory file map like
|
| 1086 |
+
``MoonshineTTS``. Free with ``free``.
|
| 1087 |
+
*/
|
| 1088 |
+
MOONSHINE_EXPORT int32_t moonshine_get_tts_voices(
|
| 1089 |
+
const char *languages, const struct moonshine_option_t *options,
|
| 1090 |
+
uint64_t options_count, char **out_voices_json);
|
| 1091 |
+
|
| 1092 |
+
/* ------------------------------ MODEL DOWNLOAD MANIFESTS ----------------- */
|
| 1093 |
+
|
| 1094 |
+
/* Returns the download manifest for a speech-to-text transcription model as a
|
| 1095 |
+
JSON object. This lets language bindings and applications fetch exactly the
|
| 1096 |
+
files a model needs from the CDN (https://download.moonshine.ai) without
|
| 1097 |
+
hardcoding the file layout, then load the model from the resulting
|
| 1098 |
+
directory with moonshine_load_transcriber_from_files.
|
| 1099 |
+
|
| 1100 |
+
``language`` is a language code (for example ``"en"``) or English name (for
|
| 1101 |
+
example ``"English"``); it must not be empty.
|
| 1102 |
+
|
| 1103 |
+
``options`` / ``options_count`` accept the same option list you would pass to
|
| 1104 |
+
moonshine_load_transcriber_from_files, so a binding can build one set of
|
| 1105 |
+
options and use it both to resolve this manifest and to load the model.
|
| 1106 |
+
Options that do not change which files are needed are ignored; the ones that
|
| 1107 |
+
do are honored:
|
| 1108 |
+
- ``model_arch``: one of the MOONSHINE_MODEL_ARCH_* constants as a decimal
|
| 1109 |
+
string. When omitted, the default (first) model for the language is
|
| 1110 |
+
used. Note: MOONSHINE_MODEL_ARCH_BASE_STREAMING is defined but not
|
| 1111 |
+
currently published in the model catalog.
|
| 1112 |
+
- ``word_timestamps`` (bool): when true, the optional attention decoder
|
| 1113 |
+
(``decoder_kv_with_attention.ort`` for streaming, or
|
| 1114 |
+
``decoder_with_attention.ort`` for non-streaming) is included for
|
| 1115 |
+
languages that publish it. This file is only needed to produce word-level
|
| 1116 |
+
timestamps and roughly doubles the download, so it defaults to false.
|
| 1117 |
+
- ``include_spelling`` / ``spelling`` (bool), or ``spelling_model_path``
|
| 1118 |
+
(non-empty path): when set and a spelling model is published for the
|
| 1119 |
+
language, its files are appended as an extra group. Defaults to false.
|
| 1120 |
+
Other options are ignored.
|
| 1121 |
+
|
| 1122 |
+
On success, writes a NUL-terminated JSON object to
|
| 1123 |
+
``*out_dependencies_json`` and returns ``MOONSHINE_ERROR_NONE``. The shape
|
| 1124 |
+
is:
|
| 1125 |
+
``{"groups":[{"base_url":"https://download.moonshine.ai/model/tiny-en/quantized/tiny-en","files":[{"name":"encoder_model.ort","url":"https://download.moonshine.ai/model/tiny-en/quantized/tiny-en/encoder_model.ort","size":12345,"checksum":"abc==","checksum_type":"crc32c"},
|
| 1126 |
+
...]}]}`` Each entry in ``files`` is an object with ``name`` (canonical
|
| 1127 |
+
filename),
|
| 1128 |
+
``url`` (fully-qualified download URL, i.e. ``base_url + "/" + name``),
|
| 1129 |
+
``size`` (bytes, or null when unknown), ``checksum`` (base64 digest, or ""),
|
| 1130 |
+
and ``checksum_type`` (e.g. "crc32c", or ""). A model is a single group,
|
| 1131 |
+
plus an optional second group for the spelling model (which uses a different
|
| 1132 |
+
``base_url``). The buffer is allocated with ``malloc``; release it with
|
| 1133 |
+
``free``. On failure (empty language, unknown language, or a language that
|
| 1134 |
+
does not publish the requested architecture) returns a non-zero error code,
|
| 1135 |
+
logs which case it is (listing the architectures that language does publish
|
| 1136 |
+
when the language is known), and sets ``*out_dependencies_json`` to NULL. */
|
| 1137 |
+
MOONSHINE_EXPORT int32_t moonshine_get_stt_dependencies(
|
| 1138 |
+
const char *language, const struct moonshine_option_t *options,
|
| 1139 |
+
uint64_t options_count, char **out_dependencies_json);
|
| 1140 |
+
|
| 1141 |
+
/* Returns the download manifest for an embedding model as a JSON object with
|
| 1142 |
+
the same shape as moonshine_get_stt_dependencies. Load the downloaded
|
| 1143 |
+
directory with moonshine_create_embedding_model.
|
| 1144 |
+
|
| 1145 |
+
``model_name`` is an embedding model id (for example
|
| 1146 |
+
``"embeddinggemma-300m"``); pass NULL or an empty string to use the default
|
| 1147 |
+
model.
|
| 1148 |
+
|
| 1149 |
+
``options`` / ``options_count`` recognize ``variant`` (aliases:
|
| 1150 |
+
``model_variant``): one of ``"q4"`` or ``"q8"``. ``"fp32"``, ``"fp16"``,
|
| 1151 |
+
and ``"q4f16"`` are no longer supported. When omitted, the model's
|
| 1152 |
+
default variant is used. Other
|
| 1153 |
+
options are ignored. The manifest lists the single all-in-one model file
|
| 1154 |
+
(``model_<variant>.ort``) and ``tokenizer.bin``.
|
| 1155 |
+
|
| 1156 |
+
On success, writes a NUL-terminated JSON object to
|
| 1157 |
+
``*out_dependencies_json`` (single group, same file-object shape as
|
| 1158 |
+
moonshine_get_stt_dependencies) and returns ``MOONSHINE_ERROR_NONE``; free
|
| 1159 |
+
with ``free``. On failure (unknown model or variant) returns a non-zero
|
| 1160 |
+
error code and sets ``*out_dependencies_json`` to NULL. */
|
| 1161 |
+
MOONSHINE_EXPORT int32_t moonshine_get_embedding_dependencies(
|
| 1162 |
+
const char *model_name, const struct moonshine_option_t *options,
|
| 1163 |
+
uint64_t options_count, char **out_dependencies_json);
|
| 1164 |
+
|
| 1165 |
+
/* Returns the download manifest for the speaker diarization models as a JSON
|
| 1166 |
+
object with the same shape as moonshine_get_stt_dependencies. Fetch these
|
| 1167 |
+
whenever you intend to pass ``identify_speakers=true`` to a transcriber, and
|
| 1168 |
+
point the transcriber at them with the ``diarization_model_dir`` option (or
|
| 1169 |
+
supply them as ``segmentation.ort`` / ``embedding.ort`` entries to
|
| 1170 |
+
moonshine_load_transcriber_from_memory_files).
|
| 1171 |
+
|
| 1172 |
+
There is one set of diarization models and it has no variants, so this takes
|
| 1173 |
+
no arguments beyond the output pointer. The manifest is a single group of two
|
| 1174 |
+
files totalling about 8.2 MB.
|
| 1175 |
+
|
| 1176 |
+
These models were compiled into the library before version 26.8; a
|
| 1177 |
+
transcriber built with ``identify_speakers=true`` and no diarization models
|
| 1178 |
+
now fails to load rather than falling back. See docs/diarization-models.md.
|
| 1179 |
+
|
| 1180 |
+
The buffer is allocated with ``malloc``; release it with ``free``. Returns
|
| 1181 |
+
``MOONSHINE_ERROR_NONE`` on success. */
|
| 1182 |
+
MOONSHINE_EXPORT int32_t
|
| 1183 |
+
moonshine_get_diarization_dependencies(char **out_dependencies_json);
|
| 1184 |
+
|
| 1185 |
+
/* Returns the full speech-to-text model catalog as a JSON object, so bindings
|
| 1186 |
+
can build language/model pickers and resolve defaults without their own copy
|
| 1187 |
+
of the tables. The shape is:
|
| 1188 |
+
``{"languages":[{"code":"en","english_name":"English","models":[{"model_arch":9,"download_url":"https://...","is_default":true},
|
| 1189 |
+
...]}, ...]}`` The buffer is allocated with ``malloc``; release it with
|
| 1190 |
+
``free``. Returns
|
| 1191 |
+
``MOONSHINE_ERROR_NONE`` on success. */
|
| 1192 |
+
MOONSHINE_EXPORT int32_t moonshine_get_stt_catalog(char **out_catalog_json);
|
| 1193 |
+
|
| 1194 |
+
/* Returns the full text embedding model catalog as a JSON object.
|
| 1195 |
+
The shape is:
|
| 1196 |
+
``{"models":[{"name":"embeddinggemma-300m","english_name":"Embedding Gemma
|
| 1197 |
+
300M","download_url":"https://...","variants":["q4",
|
| 1198 |
+
...],"default_variant":"q4"}]}`` The buffer is allocated with ``malloc``;
|
| 1199 |
+
release it with ``free``. Returns
|
| 1200 |
+
``MOONSHINE_ERROR_NONE`` on success. */
|
| 1201 |
+
MOONSHINE_EXPORT int32_t
|
| 1202 |
+
moonshine_get_embedding_catalog(char **out_catalog_json);
|
| 1203 |
+
|
| 1204 |
+
/* Synthesizes text to speech.
|
| 1205 |
+
``options`` / ``options_count``: optional per-call overrides using the same
|
| 1206 |
+
``name`` / ``value`` convention as the synthesizer constructor. Currently
|
| 1207 |
+
only
|
| 1208 |
+
``speed`` is honored for the duration of this call (Kokoro ONNX input and
|
| 1209 |
+
Piper length scale); other entries are ignored. Pass NULL / 0 to use the
|
| 1210 |
+
synthesizer default speed from construction.
|
| 1211 |
+
|
| 1212 |
+
Returns zero on success, or a non-zero error code on failure.
|
| 1213 |
+
*/
|
| 1214 |
+
MOONSHINE_EXPORT int32_t moonshine_text_to_speech(
|
| 1215 |
+
int32_t tts_synthesizer_handle, const char *text,
|
| 1216 |
+
const struct moonshine_option_t *options, uint64_t options_count,
|
| 1217 |
+
float **out_audio_data, uint64_t *out_audio_data_size,
|
| 1218 |
+
int32_t *out_sample_rate);
|
| 1219 |
+
|
| 1220 |
+
/* Synthesizes speech directly from International Phonetic Alphabet (IPA)
|
| 1221 |
+
phonemes, skipping the grapheme-to-phoneme conversion that
|
| 1222 |
+
``moonshine_text_to_speech`` performs internally. ``phonemes`` should be an
|
| 1223 |
+
IPA string in the same format produced by ``moonshine_text_to_phonemes`` (a
|
| 1224 |
+
grapheme-to-phonemizer created for the matching language). This lets callers
|
| 1225 |
+
inspect or edit the phonemes between the text-to-phonemes and
|
| 1226 |
+
phonemes-to-speech steps (e.g. to fix pronunciation of a name). The
|
| 1227 |
+
phonemes are normalized to the active vocoder's phoneme inventory before
|
| 1228 |
+
synthesis, so passing the raw ``moonshine_text_to_phonemes`` output for the
|
| 1229 |
+
same language yields audio equivalent to ``moonshine_text_to_speech`` on the
|
| 1230 |
+
original text.
|
| 1231 |
+
|
| 1232 |
+
``options`` / ``options_count`` behave exactly like
|
| 1233 |
+
``moonshine_text_to_speech``: only ``speed`` is honored for the duration of
|
| 1234 |
+
the call; pass NULL / 0 to use the synthesizer defaults.
|
| 1235 |
+
|
| 1236 |
+
Returns zero on success, or a non-zero error code on failure.
|
| 1237 |
+
*/
|
| 1238 |
+
MOONSHINE_EXPORT int32_t moonshine_phonemes_to_speech(
|
| 1239 |
+
int32_t tts_synthesizer_handle, const char *phonemes,
|
| 1240 |
+
const struct moonshine_option_t *options, uint64_t options_count,
|
| 1241 |
+
float **out_audio_data, uint64_t *out_audio_data_size,
|
| 1242 |
+
int32_t *out_sample_rate);
|
| 1243 |
+
|
| 1244 |
+
/* --------------------------- STREAMING TEXT TO SPEECH -------------------- */
|
| 1245 |
+
|
| 1246 |
+
/* Splits a passage into the utterances a streaming synthesizer would speak one
|
| 1247 |
+
at a time. Exposed on its own so a caller can queue work itself, or show the
|
| 1248 |
+
same boundaries in a UI that the audio will follow.
|
| 1249 |
+
|
| 1250 |
+
``language`` is the same tag as ``moonshine_create_tts_synthesizer_*``; it
|
| 1251 |
+
selects the abbreviation list ("Dr." and "z.B." do not end a sentence) and
|
| 1252 |
+
the terminators that count (``。!?`` need no trailing space, ``;`` is a
|
| 1253 |
+
question mark only in Greek). NULL or empty applies the language-neutral
|
| 1254 |
+
rules.
|
| 1255 |
+
|
| 1256 |
+
Recognised ``options``:
|
| 1257 |
+
``split_on_colon`` (bool, default true) break after ":" so a lead-in like
|
| 1258 |
+
"Warning:" starts playing before the rest is
|
| 1259 |
+
synthesized.
|
| 1260 |
+
``min_codepoints`` (int, default 0) merge a unit shorter than this into
|
| 1261 |
+
the next one, so a stray "Hi." is not spoken alone.
|
| 1262 |
+
|
| 1263 |
+
On success ``*out_units_json`` is a NUL-terminated JSON array of strings;
|
| 1264 |
+
release it with ``moonshine_free_buffer``. An empty or whitespace-only input
|
| 1265 |
+
gives ``[]``. */
|
| 1266 |
+
MOONSHINE_EXPORT int32_t
|
| 1267 |
+
moonshine_tts_split_utterances(const char *language, const char *text,
|
| 1268 |
+
const struct moonshine_option_t *options,
|
| 1269 |
+
uint64_t options_count, char **out_units_json);
|
| 1270 |
+
|
| 1271 |
+
/* One piece of synthesized audio from a streaming session. Owned by the
|
| 1272 |
+
synthesizer and valid only until the next call on the same stream, the same
|
| 1273 |
+
convention transcript_t uses. Copy anything you need to keep. */
|
| 1274 |
+
struct tts_chunk_t {
|
| 1275 |
+
/* Mono PCM in [-1, 1]. Never NULL when a chunk was returned. */
|
| 1276 |
+
const float *audio_data;
|
| 1277 |
+
uint64_t audio_data_count;
|
| 1278 |
+
int32_t sample_rate;
|
| 1279 |
+
/* The text this chunk covers, or "" when the engine cut on acoustic frames
|
| 1280 |
+
rather than a knowable span of characters (only the first chunk of such an
|
| 1281 |
+
utterance carries text). */
|
| 1282 |
+
const char *text;
|
| 1283 |
+
/* Which queued utterance this came from, counting from 1. Lets a consumer
|
| 1284 |
+
tell where one reply ends and the next begins without tracking flushes. */
|
| 1285 |
+
uint64_t utterance_id;
|
| 1286 |
+
/* Non-zero on the last chunk of an utterance. */
|
| 1287 |
+
int8_t is_final;
|
| 1288 |
+
};
|
| 1289 |
+
|
| 1290 |
+
/* Streaming synthesis on ``tts_synthesizer_handle``.
|
| 1291 |
+
|
| 1292 |
+
Pull-based and synchronous: text goes in with ``moonshine_tts_push_text`` as
|
| 1293 |
+
it becomes available, and audio comes out of ``moonshine_tts_next_chunk`` a
|
| 1294 |
+
chunk at a time. No thread is created and no callback is invoked, so a
|
| 1295 |
+
binding can drive it from whatever worker suits its platform.
|
| 1296 |
+
|
| 1297 |
+
There is no session object. A synthesizer runs one generation at a time:
|
| 1298 |
+
pushing text starts one, ``moonshine_tts_end_input`` finishes it, and
|
| 1299 |
+
``moonshine_tts_cancel`` abandons it. While one is in flight the one-shot
|
| 1300 |
+
``moonshine_tts_synthesize`` returns ``MOONSHINE_ERROR_BUSY`` rather than
|
| 1301 |
+
competing for the model. Calls are internally serialized, so driving the
|
| 1302 |
+
stream from a worker thread is safe; they block each other.
|
| 1303 |
+
|
| 1304 |
+
How much audio a chunk holds depends on the engine. Kokoro cuts inside a
|
| 1305 |
+
sentence where its prosody/decoder stages are installed, which starts
|
| 1306 |
+
playback sooner; everything else emits one chunk per sentence, which still
|
| 1307 |
+
starts on the first clause rather than the last. */
|
| 1308 |
+
|
| 1309 |
+
/* Appends text. Pieces are concatenated verbatim, so feeding an LLM's output
|
| 1310 |
+
token by token reassembles the words correctly. Starts a generation if none
|
| 1311 |
+
is running.
|
| 1312 |
+
|
| 1313 |
+
Text is held back until it forms a complete utterance, because synthesizing
|
| 1314 |
+
half a sentence gets the prosody wrong. Anything left over waits for the
|
| 1315 |
+
next push, a ``moonshine_tts_flush``, or ``moonshine_tts_end_input``.
|
| 1316 |
+
|
| 1317 |
+
Returns ``MOONSHINE_ERROR_NONE`` on success. */
|
| 1318 |
+
MOONSHINE_EXPORT int32_t moonshine_tts_push_text(int32_t tts_synthesizer_handle,
|
| 1319 |
+
const char *text);
|
| 1320 |
+
|
| 1321 |
+
/* Queues whatever text is buffered even though it does not look like a
|
| 1322 |
+
complete sentence. Use it where the caller knows the thought is finished but
|
| 1323 |
+
the punctuation does not say so. */
|
| 1324 |
+
MOONSHINE_EXPORT int32_t moonshine_tts_flush(int32_t tts_synthesizer_handle);
|
| 1325 |
+
|
| 1326 |
+
/* Declares that no more text is coming. Flushes, then makes
|
| 1327 |
+
``moonshine_tts_next_chunk`` report ``MOONSHINE_TTS_END_OF_STREAM`` once the
|
| 1328 |
+
queue drains, which also returns the synthesizer to idle. */
|
| 1329 |
+
MOONSHINE_EXPORT int32_t
|
| 1330 |
+
moonshine_tts_end_input(int32_t tts_synthesizer_handle);
|
| 1331 |
+
|
| 1332 |
+
/* Drops queued text, abandons the generation in progress and returns the
|
| 1333 |
+
synthesizer to idle. This is the barge-in path: when someone interrupts the
|
| 1334 |
+
assistant, stop the reply. Safe to call when nothing is streaming. */
|
| 1335 |
+
MOONSHINE_EXPORT int32_t moonshine_tts_cancel(int32_t tts_synthesizer_handle);
|
| 1336 |
+
|
| 1337 |
+
/* Non-zero while a streaming generation is in flight. */
|
| 1338 |
+
MOONSHINE_EXPORT int32_t
|
| 1339 |
+
moonshine_tts_is_streaming(int32_t tts_synthesizer_handle);
|
| 1340 |
+
|
| 1341 |
+
/* Produces the next chunk of audio, synthesizing it during the call.
|
| 1342 |
+
|
| 1343 |
+
This never waits on another thread: it blocks only for as long as the model
|
| 1344 |
+
takes, and returns immediately when there is nothing to do. ``flags`` is
|
| 1345 |
+
reserved and must be 0. The returned chunk is owned by the synthesizer and
|
| 1346 |
+
is valid only until the next call on it.
|
| 1347 |
+
|
| 1348 |
+
Returns ``MOONSHINE_ERROR_NONE`` with ``*out_chunk`` set when a chunk was
|
| 1349 |
+
produced, ``MOONSHINE_TTS_NEED_TEXT`` when no complete utterance is buffered
|
| 1350 |
+
(push more, or flush), ``MOONSHINE_TTS_END_OF_STREAM`` after
|
| 1351 |
+
``moonshine_tts_end_input`` and the queue has drained,
|
| 1352 |
+
``MOONSHINE_TTS_CANCELLED`` once after ``moonshine_tts_cancel`` discarded a
|
| 1353 |
+
reply, or a negative error code. ``*out_chunk`` is set to NULL for every
|
| 1354 |
+
non-success status. */
|
| 1355 |
+
MOONSHINE_EXPORT int32_t
|
| 1356 |
+
moonshine_tts_next_chunk(int32_t tts_synthesizer_handle, uint32_t flags,
|
| 1357 |
+
const struct tts_chunk_t **out_chunk);
|
| 1358 |
+
|
| 1359 |
+
/* Creates a grapheme to phonemizer from files on disk.
|
| 1360 |
+
Returns a non-negative handle on success, or a negative error code on
|
| 1361 |
+
failure. The error code can be converted to a human-readable string using
|
| 1362 |
+
moonshine_error_to_string.
|
| 1363 |
+
|
| 1364 |
+
Lexicons and bundled ONNX assets are resolved under ``g2p_root`` (or the
|
| 1365 |
+
process current working directory when ``g2p_root`` / ``model_root`` is
|
| 1366 |
+
unset) using the same canonical relative keys as
|
| 1367 |
+
``MoonshineG2POptions::files`` in the C++ API (for example
|
| 1368 |
+
``en_us/dict_filtered_heteronyms.tsv``,
|
| 1369 |
+
``zh_hans/roberta_chinese_base_upos_onnx/meta.json``,
|
| 1370 |
+
``zh_hans/roberta_chinese_base_upos_onnx/model.model.ort``,
|
| 1371 |
+
``en_us/g2p-config.json``, ``en_us/oov/model.ort``,
|
| 1372 |
+
``en_us/oov/onnx-config.json``). Japanese and Arabic tok-POS / diacritizer
|
| 1373 |
+
bundles use the same pattern under ``ja/...`` and
|
| 1374 |
+
``ar_msa/...``. Korean rule G2P uses ``ko/dict.tsv`` only. Models that ship
|
| 1375 |
+
as a split ORT pair need both ``<stem>.model.ort`` and
|
| 1376 |
+
``<stem>.weights.ort`` present.
|
| 1377 |
+
|
| 1378 |
+
Every model is ORT-format. Moonshine cannot load a ``.onnx``: the wasm and
|
| 1379 |
+
mobile runtimes are minimal ONNX Runtime builds with no ONNX parser
|
| 1380 |
+
compiled in. Convert one with ``scripts/convert-models-to-ort.py``.
|
| 1381 |
+
*/
|
| 1382 |
+
MOONSHINE_EXPORT int32_t moonshine_create_grapheme_to_phonemizer_from_files(
|
| 1383 |
+
const char *language, const char **filenames, uint64_t filenames_count,
|
| 1384 |
+
const struct moonshine_option_t *options, uint64_t options_count,
|
| 1385 |
+
int32_t moonshine_version);
|
| 1386 |
+
|
| 1387 |
+
/* Creates a grapheme to phonemizer from memory.
|
| 1388 |
+
Returns a non-negative handle on success, or a negative error code on
|
| 1389 |
+
failure. The error code can be converted to a human-readable string using
|
| 1390 |
+
moonshine_error_to_string.
|
| 1391 |
+
|
| 1392 |
+
``filenames[i]`` is the canonical ``MoonshineG2POptions::files`` key.
|
| 1393 |
+
When ``memory[i]`` is non-NULL and ``memory_sizes[i]`` > 0, that buffer is
|
| 1394 |
+
used as the asset bytes (not copied—keep valid until the phonemizer is
|
| 1395 |
+
freed). When ``memory[i]`` is NULL or size zero, the key is also used as a
|
| 1396 |
+
path relative to ``g2p_root``, like path-only map entries.
|
| 1397 |
+
|
| 1398 |
+
Register every file the engine needs: language lexicon ``dict.tsv`` paths,
|
| 1399 |
+
English ``g2p-config.json`` and the OOV model keys under ``en_us/oov/``, and
|
| 1400 |
+
for model bundles the ``meta.json``, ``vocab.txt``,
|
| 1401 |
+
``tokenizer_config.json``, and ``model.ort`` keys under the bundle directory
|
| 1402 |
+
key (or both halves of a split pair). English OOV overrides use
|
| 1403 |
+
``oov_onnx_override`` for the model bytes and ``oov_onnx_config`` for the
|
| 1404 |
+
merged JSON config UTF-8 text; those key names predate the move to ORT and
|
| 1405 |
+
are kept for compatibility, but the bytes must be ORT-format.
|
| 1406 |
+
|
| 1407 |
+
Every model buffer must be a self-contained ORT model. Moonshine cannot
|
| 1408 |
+
load a ``.onnx``, and there is no support for a sidecar weights file:
|
| 1409 |
+
convert with ``scripts/convert-models-to-ort.py``.
|
| 1410 |
+
*/
|
| 1411 |
+
MOONSHINE_EXPORT int32_t moonshine_create_grapheme_to_phonemizer_from_memory(
|
| 1412 |
+
const char *language, const char **filenames,
|
| 1413 |
+
const uint64_t filenames_count, const uint8_t **memory,
|
| 1414 |
+
const uint64_t *memory_sizes, const struct moonshine_option_t *options,
|
| 1415 |
+
uint64_t options_count, int32_t moonshine_version);
|
| 1416 |
+
|
| 1417 |
+
/* Releases the resources used by a grapheme to phonemizer. */
|
| 1418 |
+
MOONSHINE_EXPORT void moonshine_free_grapheme_to_phonemizer(
|
| 1419 |
+
int32_t grapheme_to_phonemizer_handle);
|
| 1420 |
+
|
| 1421 |
+
/* Converts a text into the equivalent International Phonetic Alphabet (IPA)
|
| 1422 |
+
phonemes. Returns zero on success, or a non-zero error code on failure.
|
| 1423 |
+
*/
|
| 1424 |
+
MOONSHINE_EXPORT int32_t moonshine_text_to_phonemes(
|
| 1425 |
+
int32_t grapheme_to_phonemizer_handle, const char *text,
|
| 1426 |
+
const struct moonshine_option_t *options, uint64_t options_count,
|
| 1427 |
+
const char **out_phonemes, uint64_t *out_phonemes_count);
|
| 1428 |
+
|
| 1429 |
+
#ifdef __cplusplus
|
| 1430 |
+
}
|
| 1431 |
+
#endif
|
| 1432 |
+
|
| 1433 |
+
#endif
|
source/app/src/main/cpp/duplex/moonshine_asr.cpp
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "moonshine_asr.h"
|
| 2 |
+
|
| 3 |
+
#include "common.h"
|
| 4 |
+
#include "moonshine-c-api.h"
|
| 5 |
+
|
| 6 |
+
#include <stdexcept>
|
| 7 |
+
|
| 8 |
+
namespace {
|
| 9 |
+
constexpr int frame_samples = 640;
|
| 10 |
+
constexpr int update_samples = 3200;
|
| 11 |
+
|
| 12 |
+
void require_ok(int result) {
|
| 13 |
+
if (result < 0) throw std::runtime_error(moonshine_error_to_string(result));
|
| 14 |
+
}
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
MoonshineAsr::MoonshineAsr(const std::string &path) {
|
| 18 |
+
const moonshine_option_t options[] = {{"max_tokens_per_second", "13.0"}};
|
| 19 |
+
model = moonshine_load_transcriber_from_files(path.c_str(), MOONSHINE_MODEL_ARCH_TINY_STREAMING,
|
| 20 |
+
options, 1, MOONSHINE_HEADER_VERSION);
|
| 21 |
+
require_ok(model);
|
| 22 |
+
try {
|
| 23 |
+
worker = std::thread([this] { run(); });
|
| 24 |
+
} catch (...) {
|
| 25 |
+
moonshine_free_transcriber(model);
|
| 26 |
+
throw;
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
MoonshineAsr::~MoonshineAsr() {
|
| 31 |
+
{
|
| 32 |
+
std::lock_guard<std::mutex> lock(mutex);
|
| 33 |
+
closing = true;
|
| 34 |
+
}
|
| 35 |
+
ready.notify_one();
|
| 36 |
+
worker.join();
|
| 37 |
+
moonshine_free_transcriber(model);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
void MoonshineAsr::reset() {
|
| 41 |
+
std::lock_guard<std::mutex> lock(mutex);
|
| 42 |
+
++generation;
|
| 43 |
+
pending.clear();
|
| 44 |
+
result.reset();
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
std::optional<std::string> MoonshineAsr::push(const float *pcm) {
|
| 48 |
+
std::lock_guard<std::mutex> lock(mutex);
|
| 49 |
+
pending.insert(pending.end(), pcm, pcm + frame_samples);
|
| 50 |
+
if (pending.size() >= update_samples) ready.notify_one();
|
| 51 |
+
auto current = std::move(result);
|
| 52 |
+
result.reset();
|
| 53 |
+
return current;
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
void MoonshineAsr::run() {
|
| 57 |
+
int stream = -1;
|
| 58 |
+
unsigned active_generation = 0;
|
| 59 |
+
std::vector<float> input;
|
| 60 |
+
while (true) {
|
| 61 |
+
unsigned current_generation;
|
| 62 |
+
{
|
| 63 |
+
std::unique_lock<std::mutex> lock(mutex);
|
| 64 |
+
ready.wait(lock, [&] { return closing || pending.size() >= update_samples; });
|
| 65 |
+
if (closing) break;
|
| 66 |
+
current_generation = generation;
|
| 67 |
+
input.clear();
|
| 68 |
+
input.swap(pending);
|
| 69 |
+
}
|
| 70 |
+
if (stream < 0 || current_generation != active_generation) {
|
| 71 |
+
if (stream >= 0) moonshine_free_stream(model, stream);
|
| 72 |
+
stream = moonshine_create_stream(model, 0);
|
| 73 |
+
if (stream < 0 || moonshine_start_stream(model, stream) != 0) {
|
| 74 |
+
LOGE("Moonshine: stream initialization failed");
|
| 75 |
+
if (stream >= 0) moonshine_free_stream(model, stream);
|
| 76 |
+
stream = -1;
|
| 77 |
+
continue;
|
| 78 |
+
}
|
| 79 |
+
active_generation = current_generation;
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
const double start = now_sec();
|
| 83 |
+
transcript_t *transcript = nullptr;
|
| 84 |
+
if (moonshine_transcribe_add_audio_to_stream(model, stream, input.data(), input.size(), 16000, 0) != 0 ||
|
| 85 |
+
moonshine_transcribe_stream(model, stream, MOONSHINE_FLAG_FORCE_UPDATE, &transcript) != 0) {
|
| 86 |
+
LOGE("Moonshine: streaming transcription failed");
|
| 87 |
+
continue;
|
| 88 |
+
}
|
| 89 |
+
last_ms = (now_sec() - start) * 1000;
|
| 90 |
+
std::string text;
|
| 91 |
+
if (transcript) {
|
| 92 |
+
for (size_t i = 0; i < transcript->line_count; i++)
|
| 93 |
+
if (transcript->lines[i].text) text += transcript->lines[i].text;
|
| 94 |
+
}
|
| 95 |
+
std::lock_guard<std::mutex> lock(mutex);
|
| 96 |
+
if (generation == current_generation) result = std::move(text);
|
| 97 |
+
}
|
| 98 |
+
if (stream >= 0) moonshine_free_stream(model, stream);
|
| 99 |
+
}
|
source/app/src/main/cpp/duplex/moonshine_asr.h
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <atomic>
|
| 4 |
+
#include <condition_variable>
|
| 5 |
+
#include <mutex>
|
| 6 |
+
#include <optional>
|
| 7 |
+
#include <string>
|
| 8 |
+
#include <thread>
|
| 9 |
+
#include <vector>
|
| 10 |
+
|
| 11 |
+
class MoonshineAsr {
|
| 12 |
+
public:
|
| 13 |
+
explicit MoonshineAsr(const std::string &path);
|
| 14 |
+
~MoonshineAsr();
|
| 15 |
+
|
| 16 |
+
void reset();
|
| 17 |
+
std::optional<std::string> push(const float *pcm);
|
| 18 |
+
std::atomic<double> last_ms{0};
|
| 19 |
+
|
| 20 |
+
private:
|
| 21 |
+
void run();
|
| 22 |
+
|
| 23 |
+
int model = -1;
|
| 24 |
+
std::mutex mutex;
|
| 25 |
+
std::condition_variable ready;
|
| 26 |
+
std::thread worker;
|
| 27 |
+
std::vector<float> pending;
|
| 28 |
+
std::optional<std::string> result;
|
| 29 |
+
unsigned generation = 0;
|
| 30 |
+
bool closing = false;
|
| 31 |
+
};
|
source/app/src/main/cpp/duplex/tts.cpp
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// tts.cpp — 声を作る(VOICEVOX CORE)
|
| 2 |
+
// アプリには VOICEVOX を入れない。使う人が選んだ libvoicevox_core.so を dlopen で読み込み、使う関数を dlsym で取り出す
|
| 3 |
+
#include "tts.h"
|
| 4 |
+
|
| 5 |
+
#ifdef _WIN32
|
| 6 |
+
// Windows では LoadLibraryW / GetProcAddress で同じことをする(日本語のフォルダ名でも読めるように、UTF-8 を wchar_t に直す)
|
| 7 |
+
#include <windows.h>
|
| 8 |
+
namespace {
|
| 9 |
+
const int RTLD_NOW = 0, RTLD_LOCAL = 0;
|
| 10 |
+
std::string g_dl_error;
|
| 11 |
+
void *dlopen(const char *path, int) {
|
| 12 |
+
const int n = MultiByteToWideChar(CP_UTF8, 0, path, -1, nullptr, 0);
|
| 13 |
+
std::wstring w(n > 0 ? n - 1 : 0, L'\0');
|
| 14 |
+
if (n > 0) MultiByteToWideChar(CP_UTF8, 0, path, -1, w.data(), n);
|
| 15 |
+
// 同じフォルダにある部品(voicevox_onnxruntime.dll など)も探せるように、そのフォルダから読む
|
| 16 |
+
HMODULE h = LoadLibraryExW(w.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
|
| 17 |
+
if (!h) g_dl_error = "Windows のエラー番号 " + std::to_string(GetLastError());
|
| 18 |
+
return (void *) h;
|
| 19 |
+
}
|
| 20 |
+
void *dlsym(void *lib, const char *name) { return (void *) GetProcAddress((HMODULE) lib, name); }
|
| 21 |
+
const char *dlerror() { return g_dl_error.c_str(); }
|
| 22 |
+
} // namespace
|
| 23 |
+
#else
|
| 24 |
+
#include <dlfcn.h>
|
| 25 |
+
#endif
|
| 26 |
+
|
| 27 |
+
#include <algorithm>
|
| 28 |
+
#include <cstring>
|
| 29 |
+
|
| 30 |
+
#include "common.h"
|
| 31 |
+
#include "voicevox_core.h"
|
| 32 |
+
|
| 33 |
+
namespace {
|
| 34 |
+
// 使う関数(型は voicevox_core.h の宣言から取る。ここでは中身をつながない)
|
| 35 |
+
#define VV(name) decltype(&name) p_##name = nullptr
|
| 36 |
+
VV(voicevox_make_default_load_onnxruntime_options);
|
| 37 |
+
VV(voicevox_onnxruntime_load_once);
|
| 38 |
+
VV(voicevox_open_jtalk_rc_new);
|
| 39 |
+
VV(voicevox_make_default_initialize_options);
|
| 40 |
+
VV(voicevox_synthesizer_new);
|
| 41 |
+
VV(voicevox_voice_model_file_open);
|
| 42 |
+
VV(voicevox_synthesizer_load_voice_model);
|
| 43 |
+
VV(voicevox_make_default_load_voice_model_options);
|
| 44 |
+
VV(voicevox_voice_model_file_delete);
|
| 45 |
+
VV(voicevox_synthesizer_create_audio_query);
|
| 46 |
+
VV(voicevox_synthesizer_synthesis);
|
| 47 |
+
VV(voicevox_make_default_synthesis_options);
|
| 48 |
+
VV(voicevox_json_free);
|
| 49 |
+
VV(voicevox_wav_free);
|
| 50 |
+
VV(voicevox_error_result_to_message);
|
| 51 |
+
VV(voicevox_synthesizer_create_audio_feature);
|
| 52 |
+
VV(voicevox_audio_feature_len);
|
| 53 |
+
VV(voicevox_audio_feature_slice);
|
| 54 |
+
VV(voicevox_synthesizer_render);
|
| 55 |
+
VV(voicevox_audio_feature_delete);
|
| 56 |
+
VV(voicevox_bytes_free);
|
| 57 |
+
VV(voicevox_voice_model_file_create_metas_json);
|
| 58 |
+
#undef VV
|
| 59 |
+
|
| 60 |
+
std::string msg(VoicevoxResultCode rc) { return p_voicevox_error_result_to_message ? p_voicevox_error_result_to_message(rc) : "?"; }
|
| 61 |
+
} // namespace
|
| 62 |
+
|
| 63 |
+
bool Tts::init(const std::string &core_so, const std::string &ort_so, const std::string &vvm, const std::string &dic,
|
| 64 |
+
int threads, std::string &err) {
|
| 65 |
+
std::lock_guard<std::mutex> lk(mu);
|
| 66 |
+
syn = nullptr;
|
| 67 |
+
if (!lib) lib = dlopen(core_so.c_str(), RTLD_NOW | RTLD_LOCAL);
|
| 68 |
+
if (!lib) { err = std::string("声を作るプログラムを読み込めません: ") + dlerror(); return false; }
|
| 69 |
+
#define GET(name) \
|
| 70 |
+
p_##name = (decltype(p_##name)) dlsym(lib, #name); \
|
| 71 |
+
if (!p_##name) { err = "声を作るプログラムに " #name " がありません(版が違う可能性)"; return false; }
|
| 72 |
+
GET(voicevox_make_default_load_onnxruntime_options) GET(voicevox_onnxruntime_load_once) GET(voicevox_open_jtalk_rc_new)
|
| 73 |
+
GET(voicevox_make_default_initialize_options) GET(voicevox_synthesizer_new) GET(voicevox_voice_model_file_open)
|
| 74 |
+
GET(voicevox_synthesizer_load_voice_model) GET(voicevox_make_default_load_voice_model_options)
|
| 75 |
+
GET(voicevox_voice_model_file_delete) GET(voicevox_synthesizer_create_audio_query) GET(voicevox_synthesizer_synthesis)
|
| 76 |
+
GET(voicevox_make_default_synthesis_options) GET(voicevox_json_free) GET(voicevox_wav_free)
|
| 77 |
+
GET(voicevox_error_result_to_message)
|
| 78 |
+
#undef GET
|
| 79 |
+
p_voicevox_synthesizer_create_audio_feature = (decltype(p_voicevox_synthesizer_create_audio_feature)) dlsym(lib, "voicevox_synthesizer_create_audio_feature");
|
| 80 |
+
p_voicevox_audio_feature_len = (decltype(p_voicevox_audio_feature_len)) dlsym(lib, "voicevox_audio_feature_len");
|
| 81 |
+
p_voicevox_audio_feature_slice = (decltype(p_voicevox_audio_feature_slice)) dlsym(lib, "voicevox_audio_feature_slice");
|
| 82 |
+
p_voicevox_synthesizer_render = (decltype(p_voicevox_synthesizer_render)) dlsym(lib, "voicevox_synthesizer_render");
|
| 83 |
+
p_voicevox_audio_feature_delete = (decltype(p_voicevox_audio_feature_delete)) dlsym(lib, "voicevox_audio_feature_delete");
|
| 84 |
+
p_voicevox_bytes_free = (decltype(p_voicevox_bytes_free)) dlsym(lib, "voicevox_bytes_free");
|
| 85 |
+
p_voicevox_voice_model_file_create_metas_json =
|
| 86 |
+
(decltype(p_voicevox_voice_model_file_create_metas_json)) dlsym(lib, "voicevox_voice_model_file_create_metas_json");
|
| 87 |
+
auto lo = p_voicevox_make_default_load_onnxruntime_options();
|
| 88 |
+
lo.filename = ort_so.c_str();
|
| 89 |
+
const VoicevoxOnnxruntime *ort = nullptr;
|
| 90 |
+
VoicevoxResultCode rc = p_voicevox_onnxruntime_load_once(lo, &ort);
|
| 91 |
+
if (rc != VOICEVOX_RESULT_OK) { err = "計算の部品(onnxruntime): " + msg(rc); return false; }
|
| 92 |
+
OpenJtalkRc *jt = nullptr;
|
| 93 |
+
rc = p_voicevox_open_jtalk_rc_new(dic.c_str(), &jt);
|
| 94 |
+
if (rc != VOICEVOX_RESULT_OK) { err = "辞書: " + msg(rc); return false; }
|
| 95 |
+
auto io = p_voicevox_make_default_initialize_options();
|
| 96 |
+
io.cpu_num_threads = (uint16_t) threads;
|
| 97 |
+
VoicevoxSynthesizer *s = nullptr;
|
| 98 |
+
rc = p_voicevox_synthesizer_new(ort, jt, io, &s);
|
| 99 |
+
if (rc != VOICEVOX_RESULT_OK) { err = "準備: " + msg(rc); return false; }
|
| 100 |
+
VoicevoxVoiceModelFile *m = nullptr;
|
| 101 |
+
rc = p_voicevox_voice_model_file_open(vvm.c_str(), &m);
|
| 102 |
+
if (rc != VOICEVOX_RESULT_OK) { err = "声のファイル: " + msg(rc); return false; }
|
| 103 |
+
// 声のファイルに入っている声の一覧(キャラクター・スタイル・番号)を覚えておく。設定の「声」の一覧に使う
|
| 104 |
+
if (p_voicevox_voice_model_file_create_metas_json) {
|
| 105 |
+
char *mj = p_voicevox_voice_model_file_create_metas_json(m);
|
| 106 |
+
if (mj) { metas = mj; p_voicevox_json_free(mj); }
|
| 107 |
+
}
|
| 108 |
+
rc = p_voicevox_synthesizer_load_voice_model(s, m, p_voicevox_make_default_load_voice_model_options());
|
| 109 |
+
p_voicevox_voice_model_file_delete(m);
|
| 110 |
+
if (rc != VOICEVOX_RESULT_OK) { err = "声のファイルの読み込み: " + msg(rc); return false; }
|
| 111 |
+
syn = s;
|
| 112 |
+
return true;
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
bool Tts::speak(const std::string &text, int style, Speech &out, std::string &err,
|
| 116 |
+
const std::function<bool(Speech &&)> &publish, const std::function<bool()> &cancelled) {
|
| 117 |
+
std::lock_guard<std::mutex> lk(mu);
|
| 118 |
+
if (!syn) { err = "声(VOICEVOX)が入っていません"; return false; }
|
| 119 |
+
auto *s = (const VoicevoxSynthesizer *) syn;
|
| 120 |
+
char *q = nullptr;
|
| 121 |
+
VoicevoxResultCode rc = p_voicevox_synthesizer_create_audio_query(s, text.c_str(), (VoicevoxStyleId) style, &q);
|
| 122 |
+
if (rc != VOICEVOX_RESULT_OK) { err = msg(rc); return false; }
|
| 123 |
+
auto query = std::unique_ptr<char, decltype(p_voicevox_json_free)>(q, p_voicevox_json_free);
|
| 124 |
+
const auto options = p_voicevox_make_default_synthesis_options();
|
| 125 |
+
if (cancelled && cancelled()) return false;
|
| 126 |
+
if (publish && p_voicevox_synthesizer_create_audio_feature && p_voicevox_audio_feature_len &&
|
| 127 |
+
p_voicevox_audio_feature_slice && p_voicevox_synthesizer_render && p_voicevox_audio_feature_delete &&
|
| 128 |
+
p_voicevox_bytes_free) {
|
| 129 |
+
VoicevoxAudioFeature *raw_feature = nullptr;
|
| 130 |
+
rc = p_voicevox_synthesizer_create_audio_feature(s, q, (VoicevoxStyleId) style, options, &raw_feature);
|
| 131 |
+
if (rc == VOICEVOX_RESULT_OK) {
|
| 132 |
+
auto feature = std::unique_ptr<VoicevoxAudioFeature, decltype(p_voicevox_audio_feature_delete)>(
|
| 133 |
+
raw_feature, p_voicevox_audio_feature_delete);
|
| 134 |
+
constexpr uintptr_t first_frames = 16; // Include speech after the default leading silence.
|
| 135 |
+
uintptr_t block_frames = 28;
|
| 136 |
+
const uintptr_t frames = p_voicevox_audio_feature_len(feature.get());
|
| 137 |
+
bool sent = false;
|
| 138 |
+
for (uintptr_t start = 0; start < frames;) {
|
| 139 |
+
if (cancelled && cancelled()) return false;
|
| 140 |
+
VoicevoxAudioFeatureSlice slice{};
|
| 141 |
+
const uintptr_t end = std::min(start + (start == 0 ? first_frames : block_frames), frames);
|
| 142 |
+
rc = p_voicevox_audio_feature_slice(feature.get(), start, end,
|
| 143 |
+
false, false, false, &slice);
|
| 144 |
+
if (rc != VOICEVOX_RESULT_OK) break;
|
| 145 |
+
uintptr_t length = 0;
|
| 146 |
+
uint8_t *pcm = nullptr;
|
| 147 |
+
const double render_start = now_sec();
|
| 148 |
+
rc = p_voicevox_synthesizer_render(s, slice, &length, &pcm);
|
| 149 |
+
if (rc != VOICEVOX_RESULT_OK) break;
|
| 150 |
+
const double audio_seconds = (end - start) / VOICEVOX_FRAME_RATE;
|
| 151 |
+
if (start != 0 && now_sec() - render_start > audio_seconds * 0.85)
|
| 152 |
+
block_frames = std::min<uintptr_t>(block_frames * 2, 112);
|
| 153 |
+
start = end;
|
| 154 |
+
if (!length) continue;
|
| 155 |
+
auto samples = std::unique_ptr<uint8_t, decltype(p_voicevox_bytes_free)>(pcm, p_voicevox_bytes_free);
|
| 156 |
+
Speech block;
|
| 157 |
+
block.text = text;
|
| 158 |
+
block.continuation = sent;
|
| 159 |
+
block.pcm.resize(length / sizeof(int16_t));
|
| 160 |
+
for (size_t i = 0; i < block.pcm.size(); ++i) {
|
| 161 |
+
int16_t sample;
|
| 162 |
+
memcpy(&sample, samples.get() + i * sizeof(sample), sizeof(sample));
|
| 163 |
+
block.pcm[i] = sample / 32768.0f;
|
| 164 |
+
}
|
| 165 |
+
if (!publish(std::move(block))) return false;
|
| 166 |
+
sent = true;
|
| 167 |
+
}
|
| 168 |
+
if (sent) {
|
| 169 |
+
if (rc != VOICEVOX_RESULT_OK) err = msg(rc);
|
| 170 |
+
return true;
|
| 171 |
+
}
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
if (cancelled && cancelled()) return false;
|
| 175 |
+
uintptr_t n = 0;
|
| 176 |
+
uint8_t *wav = nullptr;
|
| 177 |
+
rc = p_voicevox_synthesizer_synthesis(s, q, (VoicevoxStyleId) style, options, &n, &wav);
|
| 178 |
+
if (rc != VOICEVOX_RESULT_OK) { err = msg(rc); return false; }
|
| 179 |
+
// WAV(16 ビット)→ 小数の音
|
| 180 |
+
out.pcm.clear();
|
| 181 |
+
out.sr = 24000;
|
| 182 |
+
size_t p = 12;
|
| 183 |
+
while (p + 8 <= n) {
|
| 184 |
+
uint32_t sz;
|
| 185 |
+
memcpy(&sz, wav + p + 4, 4);
|
| 186 |
+
if (memcmp(wav + p, "fmt ", 4) == 0) { uint32_t sr; memcpy(&sr, wav + p + 12, 4); out.sr = (int) sr; }
|
| 187 |
+
if (memcmp(wav + p, "data", 4) == 0) {
|
| 188 |
+
const int16_t *d = (const int16_t *) (wav + p + 8);
|
| 189 |
+
size_t cnt = std::min<size_t>(sz, n - p - 8) / 2;
|
| 190 |
+
out.pcm.resize(cnt);
|
| 191 |
+
for (size_t i = 0; i < cnt; i++) out.pcm[i] = d[i] / 32768.0f;
|
| 192 |
+
break;
|
| 193 |
+
}
|
| 194 |
+
p += 8 + sz;
|
| 195 |
+
}
|
| 196 |
+
p_voicevox_wav_free(wav);
|
| 197 |
+
out.text = text;
|
| 198 |
+
if (out.pcm.empty()) return false;
|
| 199 |
+
return !publish || publish(std::move(out));
|
| 200 |
+
}
|