Added the lipsync repo

source for code.
https://github.com/virtual-puppet-project/real-time-lip-sync-gd/tree/master
This commit is contained in:
Brooks Palin
2024-01-19 14:50:18 -07:00
parent 2df86eaf58
commit 6948c4267c
19 changed files with 32962 additions and 1 deletions
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
target/
.idea/
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "real-time-lip-sync-gd"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
# [lib]
# crate-type = ["cdylib"]
[dependencies]
lazy_static = "1.4.0"
rand = "0.8.4"
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
License shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
Licensor shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
Legal Entity shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
control means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
You (or Your) shall mean an individual or Legal Entity
exercising permissions granted by this License.
Source form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
Object form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
Work shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
Derivative Works shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
Contribution shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, submitted
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as Not a Contribution.
Contributor shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a NOTICE text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an AS IS BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets []
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same printed page as the copyright notice for easier
identification within third-party archives.
Copyright 2021 Timothy Yuen
Licensed under the Apache License, Version 2.0 (the License);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an AS IS BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+19
View File
@@ -0,0 +1,19 @@
# Real-time Lip Sync GD
A Rust port of [uLipSync](https://github.com/hecomi/uLipSync) connected to Godot via [godot-rust](https://github.com/godot-rust/godot-rust). In theory, should work with any game engine with a C api.
## Porting notes
- uLipSync
- Runtime
- Core
- [x] Algorithm.cs
- [x] Common.cs
- [x] LipSyncJob.cs
- [ ] ~~MicUtil.cs~~
- Won't do, should be done from GDScript
- [x] Profile.cs
- [ ] uLipSync.cs
- [ ] uLipSyncAudioSource.cs
- I don't think I need this?
- [ ] uLipSyncBlendShape.cs
- [ ] ~~uLipSyncMicrophone.cs~~
- Won't do, should be done from GDScript
+4
View File
@@ -0,0 +1,4 @@
[ViewState]
Mode=
Vid=
FolderType=Generic
Binary file not shown.
+138
View File
@@ -0,0 +1,138 @@
use std::boxed::Box;
use crate::model::{DataPoint, INV_LOG10, PI2};
pub fn rms(data: &[f32]) -> f32 {
let mut rms: f32 = 0.0;
for i in data.iter() {
rms += i.powi(2);
}
rms = (rms / data.len() as f32).sqrt();
rms = 20.0 * (rms.ln() * *INV_LOG10);
rms
}
pub fn normalize(data: &mut [f32]) {
let mut v_max: f32 = 0.0;
let mut v_min: f32 = 0.0;
for i in data.iter() {
v_max = v_max.max(*i);
v_min = v_min.min(*i);
}
let diff = v_max - v_min;
let d: f32 = if diff != 0.0 { 1.0 / diff } else { 1.0 };
for i in data.iter_mut() {
*i = (*i - v_min) * d;
}
}
pub fn smoothing(data: &mut [f32], before: &[f32]) {
let n = data.len();
for i in 0..n {
data[i] = (data[i] + before[i]) * 0.5;
}
}
pub fn hamming(data: &mut [f32]) {
let n = data.len();
for i in data.iter_mut() {
let h = 0.54 - 0.46 * (*PI2 * *i / (n as f32 - 1.0));
*i = *i * h;
}
data[0] = 0.0;
data[n - 1] = 0.0;
}
pub fn rfft(data: &mut [f32], reverse: bool, positive: bool) {
let n = data.len();
let mut cmp_vec = vec![];
for i in data.iter() {
let dp = DataPoint(*i, 0.0);
cmp_vec.push(Box::new(dp));
}
fft(cmp_vec.as_mut_slice(), reverse);
if positive {
for i in 0..n {
data[i] = cmp_vec[i].0.abs();
}
} else {
for i in 0..n {
data[i] = cmp_vec[i].0;
}
}
if reverse {
let inv_n: f32 = 1.0 / n as f32;
for i in data {
*i *= inv_n;
}
}
}
pub fn fft(data: &mut [Box<DataPoint>], reverse: bool) {
let n = data.len();
if n == 1 {
return;
}
let mut b = vec![];
let mut c = vec![];
for i in 0..n {
if i % 2 == 0 {
b.push(data[i].clone());
} else if i % 2 == 1 {
c.push(data[i].clone());
}
}
fft(b.as_mut_slice(), reverse);
fft(c.as_mut_slice(), reverse);
let circle = if reverse { -*PI2 } else { *PI2 };
for i in 0..n {
// TODO this doesn't feel correct
*data[i] = *b[i % (n / 2)].clone()
+ *c[i % (n / 2)].clone() * (DataPoint(0.0, circle * i as f32 / n as f32)).exp()
}
}
pub fn lifter(data: &mut [f32], level: i32) {
let i_min = level;
let i_max = data.len() as i32 - 1 - level;
for i in 0..data.len() as i32 {
if i > i_min && i <= i_max {
data[i as usize] = 0.0;
}
}
}
pub fn filter(data: &mut [f32], lowcut: i32, highcut: i32) {
let mut minimum = data[0];
for i in data.iter() {
minimum = minimum.min(*i);
}
if minimum == 0.0 {
minimum = 0.000001
}
for i in data {
if *i <= lowcut as f32 || *i >= highcut as f32 {
*i = minimum;
}
}
}
pub fn lerp(a: f32, b: f32, f: f32) -> f32 {
// l = a + f * (b - a)
a + f * (b - a)
}
pub fn inverse_lerp(a: f32, b: f32, l: f32) -> f32 {
// l = a + f * (b - a)
// l - a = f * (b - a)
// (l - a)/(b - a) = f
(l - a) / (b - a)
}
+17
View File
@@ -0,0 +1,17 @@
use godot::prelude::*;
pub fn print_max(sample_vec: Vec<f32>) {
let mut max: f32 = 0.0;
for i in sample_vec {
max = max.max(i.abs());
}
godot_print!("{}", max);
}
pub fn print_min(sample_vec: Vec<f32>) {
let mut min: f32 = 0.0;
for i in sample_vec {
min = min.min(i.abs());
}
godot_print!("{}", min);
}
+320
View File
@@ -0,0 +1,320 @@
use crate::{algorithm::*, model::*};
use godot::prelude::*;
use rand::Rng;
use std::{
collections::{HashMap, VecDeque},
sync::mpsc,
thread,
};
struct Job {
before_sample_array: Vec<f32>,
// TODO pretty sure these are just ring buffers
peaks3_log: VecDeque<Vec<DataPoint>>,
peaks4_log: VecDeque<Vec<DataPoint>>,
vowel_log: VecDeque<i32>,
estimate_log: VecDeque<i32>,
}
impl Job {
pub fn new() -> Self {
Job {
before_sample_array: vec![],
peaks3_log: VecDeque::new(),
peaks4_log: VecDeque::new(),
vowel_log: VecDeque::from(vec![-1, -1, -1]),
estimate_log: VecDeque::from(vec![-1, -1, -1]),
}
}
pub fn execute(&mut self, stream: &Array<f32>) -> Option<VowelEstimate> {
// let mut data = Job::read_16_bit_samples(stream);
let mut data = vec![];
for i in stream.iter_shared() {
data.push(i);
}
if data.len() < FFT_SAMPLES {
godot_print!("Audio data size is too small, skipped!");
return None;
}
let rms = rms(data.as_slice());
data = data[..FFT_SAMPLES as usize].to_vec();
hamming(data.as_mut_slice());
rfft(data.as_mut_slice(), false, true);
data = data[..((FFT_SAMPLES as f32 * 0.5) as usize) + 1].to_vec();
if self.before_sample_array.len() > 0 {
smoothing(data.as_mut_slice(), self.before_sample_array.as_slice());
}
self.before_sample_array = data.clone();
filter(data.as_mut_slice(), 10, 95);
for i in data.iter_mut() {
*i = i.powi(2).ln() * *INV_LOG10;
}
normalize(data.as_mut_slice());
rfft(data.as_mut_slice(), true, false);
lifter(data.as_mut_slice(), 26);
rfft(data.as_mut_slice(), false, false);
data = data[..((FFT_SAMPLES as f32 * 0.25) as usize) + 1].to_vec();
normalize(data.as_mut_slice());
for i in data.iter_mut() {
*i = i.powi(2);
}
normalize(data.as_mut_slice());
let nrm_rms = DYNAMIC_RANGE.min((rms + DYNAMIC_RANGE).max(0.0));
for i in data.iter_mut() {
*i = *i * nrm_rms * *INV_DYNAMIC_RANGE;
}
let amount = inverse_lerp(-DYNAMIC_RANGE, 0.0, rms).clamp(0.0, 1.0);
let current_vowel = self.get_vowel(data.as_slice(), amount);
self.push_estimate(current_vowel.estimate);
self.push_vowel(current_vowel.vowel);
Some(current_vowel)
}
// TODO this is returning values that are not in range -1..1
fn read_16_bit_samples(stream: &Array<u8>) -> Vec<f32> {
let mut res = vec![];
let mut i = 0;
while i < stream.len() {
let b0 = stream.get(i);
let b1 = stream.get(i + 1);
let mut u = b0 as u16 | ((b1 as u16) << 8);
u = (u + 32768) & 0xffff;
let s = (u - 32768) as f32 / 32768.0;
res.push(s);
i += 2;
}
res
}
fn get_peaks(&self, data: &[f32], threshold: f32) -> Vec<DataPoint> {
let n = data.len() - 1;
let mut i = 1;
let mut out = vec![];
let mut div = 1.0;
while i < n {
if data[i] > threshold && data[i] > data[i - 1] && data[i] > data[i + 1] {
if out.len() > 0 {
out.push(DataPoint(i as f32, data[i] * div));
} else {
out.push(DataPoint(i as f32, 1.0));
div = 1.0 / data[i];
}
}
i += 1;
}
out
}
fn get_peaks_average(&mut self, size: usize) -> Vec<DataPoint> {
let mut out = vec![];
let mut i = 1;
let mut j: usize;
let mut div = 1.0;
match size {
3 => {
out = self.peaks3_log[0].clone();
while i < self.peaks3_log.len() {
j = 0;
while j < out.len() {
out[j].0 += self.peaks3_log[i][j].0;
out[j].1 += self.peaks3_log[i][j].1;
j += 1;
}
i += 1;
}
div = 1.0 / self.peaks3_log.len() as f32;
}
4 => {
out = self.peaks4_log[0].clone();
while i < self.peaks4_log.len() {
j = 0;
while j < out.len() {
out[j].0 += self.peaks4_log[i][j].0;
out[j].1 += self.peaks4_log[i][j].1;
j += 1;
}
i += 1;
}
div = 1.0 / self.peaks4_log.len() as f32;
}
_ => {}
}
for k in out.iter_mut() {
*k *= div;
}
out
}
fn get_distance_from_db(&self, data: &[DataPoint]) -> Vec<f32> {
let mut out = vec![];
let mut dist: f32;
let peak_est: &HashMap<String, Phoneme> = match data.len() {
3 => &DEFAULT_ESTIMATES["peak3"],
4 => &DEFAULT_ESTIMATES["peak4"],
_ => {
return out;
}
};
for i in VOWELS {
dist = 0.0;
for j in 0..data.len() {
let est = &peak_est[i][j];
dist += (est.0 - data[j].0).abs() * *INV_255 + (est.1 - data[j].1);
}
out.push(dist);
}
out
}
fn push_peaks(&mut self, data: &[DataPoint]) {
match data.len() {
3 => {
if self.peaks3_log.len() < 3 {
self.peaks3_log.push_back(data.to_owned());
} else {
self.peaks3_log.push_front(data.to_owned());
self.peaks3_log.pop_back();
}
}
4 => {
if self.peaks4_log.len() < 3 {
self.peaks4_log.push_back(data.to_owned());
} else {
self.peaks4_log.push_front(data.to_owned());
self.peaks4_log.pop_back();
}
}
_ => godot_print!("push_peaks encountered invalid data"),
}
}
fn estimate_vowel(&mut self, data: &[f32]) -> i32 {
let peaks = self.get_peaks(data, 0.1);
if peaks.len() != 3 && peaks.len() != 4 {
return -1;
}
self.push_peaks(peaks.as_slice());
let peaks_ave = self.get_peaks_average(peaks.len());
let distance_vowel = self.get_distance_from_db(peaks_ave.as_slice());
let mut i = 1;
let mut min_distance = distance_vowel[0];
let mut min_idx = 0;
while i < VOWELS.len() {
let dist = distance_vowel[i];
if dist < min_distance {
min_distance = dist;
min_idx = i as i32;
}
i += 1;
}
min_idx
}
fn get_vowel(&mut self, data: &[f32], amount: f32) -> VowelEstimate {
let current = self.estimate_vowel(data);
let f_vowel = self.vowel_log[0];
if self.vowel_log[0] != -1 {
if amount < 0.5 {
return VowelEstimate::new(current, f_vowel, amount);
}
}
if self.vowel_log.len() > 2 {
if current == self.estimate_log[0] {
if current != -1 {
return VowelEstimate::new(current, current, amount);
}
} else {
if f_vowel != -1 {
return VowelEstimate::new(current, f_vowel, amount);
}
}
}
return VowelEstimate::new(current, rand::thread_rng().gen_range(0..5), amount);
}
fn push_vowel(&mut self, vowel: i32) {
if self.vowel_log.len() < 3 {
self.vowel_log.push_back(vowel);
} else {
self.vowel_log.push_front(vowel);
self.vowel_log.pop_back();
}
}
fn push_estimate(&mut self, vowel: i32) {
if self.estimate_log.len() < 3 {
self.estimate_log.push_back(vowel);
} else {
self.estimate_log.push_front(vowel);
self.estimate_log.pop_back();
}
}
}
pub enum JobMessage {
InputData(Array<f32>),
OutputData(VowelEstimate),
Shutdown,
}
unsafe impl Send for JobMessage {}
pub fn create_job() -> Option<(
thread::JoinHandle<()>,
mpsc::Sender<JobMessage>,
mpsc::Receiver<JobMessage>,
)> {
let (s1, r2) = mpsc::channel();
let (s2, r1) = mpsc::channel();
let mut job = Job::new();
let builder = thread::Builder::new();
match builder.spawn(move || loop {
let new_data: Array<f32>;
if let Ok(msg) = r1.recv() {
match msg {
JobMessage::InputData(d) => new_data = d,
JobMessage::Shutdown => break,
_ => {
godot_print!("Error when matching job data");
break;
}
}
} else {
godot_print!("Error when receiving job data");
break;
}
if let Some(vowel) = job.execute(&new_data) {
match s1.send(JobMessage::OutputData(vowel)) {
Ok(_) => {}
Err(e) => {
godot_print!("Error when sending output from job: {:?}", e);
break;
}
}
}
}) {
Ok(v) => return Some((v, s2, r2)),
Err(_) => None,
}
}
+13
View File
@@ -0,0 +1,13 @@
use godot::prelude::*;
mod lip_sync;
mod algorithm;
mod debug;
mod job;
mod model;
struct LipSyncLib;
#[gdextension]
unsafe impl ExtensionLibrary for LipSyncLib {}
+97
View File
@@ -0,0 +1,97 @@
use godot::prelude::*;
use lazy_static::lazy_static;
use rand::{rngs::ThreadRng, Rng};
use std::{
collections::{HashMap, VecDeque},
ops::{Add, Div, Index, Mul, MulAssign},
sync::mpsc,
sync::{Arc, Mutex},
thread,
};
use crate::{job, job::JobMessage};
const LIP_SYNC_UPDATED: &str = "updated";
const LIP_SYNC_PANICKED: &str = "panicked";
#[derive(GodotClass)]
#[class(base = Node)]
pub struct LipSyncRs {
join_handle: Option<thread::JoinHandle<()>>,
sender: mpsc::Sender<job::JobMessage>,
receiver: mpsc::Receiver<job::JobMessage>,
#[base]
base: Base<Node>,
}
unsafe impl Sync for LipSyncRs {}
unsafe impl Send for LipSyncRs {}
#[godot_api]
impl LipSyncRs {
#[signal]
fn updated();
#[signal]
fn panicked();
#[func]
pub fn update(&mut self, stream: Array<f32>) {
self.sender
.send(JobMessage::InputData(stream))
.expect("Unable to send stream to thread");
}
#[func]
pub fn poll(&mut self) {
match self.receiver.try_recv() {
Ok(v) => match v {
JobMessage::OutputData(od) => {
// godot_print!("Emitted signal: {:?}", LIP_SYNC_UPDATED);
self.base.emit_signal(
LIP_SYNC_UPDATED.into(),
&[Variant::from(Dictionary::from(od))],
);
}
_ => {
// Unexpected data
self.sender.send(JobMessage::Shutdown).expect("When shutting down thread because of invalid message, encoutered error. Shutting down anyways.");
}
},
Err(e) => {
if e == mpsc::TryRecvError::Disconnected {
// godot_print!("Emitted signal: {:?}", LIP_SYNC_PANICKED);
self.base
.emit_signal(LIP_SYNC_PANICKED.into(), &[Variant::from(format!("{}", e))]);
}
}
}
}
#[func]
pub fn shutdown(&mut self) {
self.sender.send(JobMessage::Shutdown).expect("When shutting down thread because of invalid message, encountered error. Shutting down anyways.");
self.join_handle
.take()
.expect("Unable to take join_handle")
.join()
.expect("Unable to join thread");
}
}
#[godot_api]
impl INode for LipSyncRs {
fn init(base: Base<Self::Base>) -> Self {
let (jh, s, r) = job::create_job().expect("Unable to create job thread");
LipSyncRs {
join_handle: Some(jh),
sender: s,
receiver: r,
base,
}
}
}
+206
View File
@@ -0,0 +1,206 @@
use godot::prelude::*;
use lazy_static::lazy_static;
use std::{
collections::{HashMap, VecDeque},
ops::{Add, Div, Index, Mul, MulAssign},
};
pub const FFT_SAMPLES: usize = 1024;
// pub const UPDATE_FRAME: usize = 5;
pub const DYNAMIC_RANGE: f32 = 100.0;
pub const VOWELS: [&str; 5] = ["A", "E", "I", "O", "U"];
lazy_static! {
pub static ref DEFAULT_ESTIMATES: HashMap<String, HashMap<String, Phoneme>> = HashMap::from([
(
"peak3".to_owned(),
HashMap::from([
(
"A".to_owned(),
Phoneme(vec![
DataPoint(18.0, 1.0),
DataPoint(41.0, 0.9),
DataPoint(85.0, 0.75),
]),
),
(
"E".to_owned(),
Phoneme(vec![
DataPoint(21.0, 1.0),
DataPoint(60.0, 0.75),
DataPoint(84.0, 0.65),
]),
),
(
"I".to_owned(),
Phoneme(vec![
DataPoint(21.0, 1.0),
DataPoint(42.0, 1.1),
DataPoint(84.0, 1.0),
]),
),
(
"O".to_owned(),
Phoneme(vec![
DataPoint(20.0, 1.0),
DataPoint(63.0, 0.9),
DataPoint(85.0, 0.8),
]),
),
(
"U".to_owned(),
Phoneme(vec![
DataPoint(19.0, 1.0),
DataPoint(47.0, 0.65),
DataPoint(84.0, 0.7),
]),
),
]),
),
(
"peak4".to_owned(),
HashMap::from([
(
"A".to_owned(),
Phoneme(vec![
DataPoint(18.0, 1.0),
DataPoint(41.0, 0.9),
DataPoint(68.0, 0.7),
DataPoint(85.0, 0.55),
]),
),
(
"E".to_owned(),
Phoneme(vec![
DataPoint(22.0, 1.0),
DataPoint(43.0, 0.9),
DataPoint(66.0, 0.7),
DataPoint(84.0, 0.65)
])
),
(
"I".to_owned(),
Phoneme(vec![
DataPoint(21.0, 1.0),
DataPoint(42.0, 1.1),
DataPoint(60.0, 1.0),
DataPoint(84.0, 1.1)
])
),
(
"O".to_owned(),
Phoneme(vec![
DataPoint(20.0, 1.0),
DataPoint(39.0, 0.9),
DataPoint(63.0, 0.75),
DataPoint(85.0, 0.8)
])
),
(
"U".to_owned(),
Phoneme(vec![
DataPoint(20.0, 1.0),
DataPoint(39.0, 0.7),
DataPoint(65.0, 0.6),
DataPoint(84.0, 0.75)
])
)
]),
),
]);
pub static ref PI2: f32 = 2.0 * std::f32::consts::PI;
pub static ref INV_255: f32 = 1.0 / 255.0;
pub static ref INV_32767: f32 = 1.0 / 32767.0;
pub static ref INV_LOG10: f32 = 1.0 / (10.0 as f32).ln();
pub static ref INV_DYNAMIC_RANGE: f32 = 1.0 / DYNAMIC_RANGE;
}
#[derive(Debug, PartialEq, Clone)]
pub struct DataPoint(pub f32, pub f32);
impl DataPoint {
pub fn exp(self) -> DataPoint {
let e = self.0.exp();
DataPoint(e * self.1.cos(), e * self.1.sin())
}
pub fn zero() -> DataPoint {
DataPoint(0.0, 0.0)
}
}
impl Add for DataPoint {
type Output = DataPoint;
fn add(self, other: DataPoint) -> DataPoint {
DataPoint(self.0 + other.0, self.1 + other.1)
}
}
impl Mul<DataPoint> for DataPoint {
type Output = DataPoint;
fn mul(self, other: DataPoint) -> DataPoint {
let r = self.0 * other.0 - self.1 * other.1;
let i = self.0 * other.0 + self.1 * other.1;
DataPoint(r, i)
}
}
impl MulAssign<f32> for DataPoint {
fn mul_assign(&mut self, other: f32) {
self.0 *= other;
self.1 *= other;
}
}
impl Div for DataPoint {
type Output = DataPoint;
fn div(self, other: DataPoint) -> DataPoint {
let r = self.0 * other.0 + self.1 * other.1;
let i = self.1 * other.0 - self.1 * other.1;
let d = other.0 * other.0 + other.1 * other.1;
DataPoint(r / d, i / d)
}
}
#[derive(Debug, PartialEq)]
pub struct Phoneme(Vec<DataPoint>);
impl Index<usize> for Phoneme {
type Output = DataPoint;
fn index(&self, idx: usize) -> &DataPoint {
&self.0[idx]
}
}
#[derive(Debug)]
pub struct VowelEstimate {
pub estimate: i32,
pub vowel: i32,
pub amount: f32,
}
impl VowelEstimate {
pub fn new(estimate: i32, vowel: i32, amount: f32) -> Self {
VowelEstimate {
estimate,
vowel,
amount,
}
}
}
impl From<VowelEstimate> for Dictionary {
fn from(ve: VowelEstimate) -> Self {
let mut dict = Dictionary::new();
dict.insert("estimate", ve.estimate);
dict.insert("vowel", ve.vowel);
dict.insert("amount", ve.amount);
dict
}
}
+1
View File
@@ -26,6 +26,7 @@ serde = { version = "1.0.192", optional = true }
serde-wasm-bindgen = { version = "0.6.1", optional = true }
serde_json = { version = "1.0.108", optional = true }
studio-bvh = { path = "../studio-bvh" }
studio-lipsync = {path = "../studio-lipsync"}
wasm-bindgen = "0.2.84"
web-sys = { version = "0.3.65", optional = true, features = [
"CustomEvent",
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -4,7 +4,7 @@ use studio::{StudioMode, ViewportSize};
fn main() {
// Edit the arguments here to change the default startup scene or skybox
let mut app = studio::start_internal(
"Mannequin.gltf",
"BaseHumanMaleHead_SHAPEKEYS_Keyed.gltf",
"gum_trees_4k",
"", // ignored for non-WASM
"Storyteller Studio",
+14
View File
@@ -61,6 +61,7 @@ impl Plugin for ScenePlugin {
tag_scene_elements,
spawn_main_scene_light,
frame_scene_in_view,
start_animation_clip,
)
.in_set(SceneSpawnerSystem),
);
@@ -128,6 +129,9 @@ pub struct BindPoseGlobal(pub Affine3A);
#[derive(Component, Clone, Copy, Debug, Deref, DerefMut)]
pub struct InvBindPose(pub Affine3A);
#[derive(Resource)]
pub struct MorphAnimation(pub Handle<AnimationClip>);
fn initialize(mut cmd: Commands, r_assets: Res<AssetServer>) {
// Camera, graphics settings
let focus = Vec3::ZERO;
@@ -197,6 +201,7 @@ fn init_scene_loading(
}
}
cmd.insert_resource(MorphAnimation(assets.load(format!("{}#Animation2", path))));
cmd.insert_resource(PendingScene(assets.load(path)));
st_next.set(SceneState::Loading);
}
@@ -485,6 +490,15 @@ fn frame_scene_in_view(
cam_xform.translation = cam.focus + cam_xform.back() * radius;
}
fn start_animation_clip(
mut animation_clips: Query<&mut AnimationPlayer>,
morph_animation: Res<MorphAnimation>,
) {
for mut animation_clip in animation_clips.iter_mut() {
animation_clip.play(morph_animation.0.clone()).repeat();
}
}
#[cfg(feature = "wasm")]
mod wasm {
use bevy::{prelude::*, window::PrimaryWindow};