initialize method
Implementation
Future<void> initialize() async {
if (_isInitialized && _wasmModule != null && _wasmExports != null) {
return;
}
_isInitialized = false; // Đặt lại cờ nếu có gì đó không ổn
// 1. If the factory doesn't exist, inject the script and wait for it.
if (!globalContext.hasProperty('PcmToOggModuleFactory'.toJS).toDart) {
final script = html.ScriptElement()
..type = 'module'
..innerHtml = '''
import createPcmToOggModule from '/pcm_to_ogg.js';
window.PcmToOggModuleFactory = createPcmToOggModule;
''';
html.document.head!.append(script);
// 2. Poll to check when the factory is available.
const maxRetries = 200; // Wait up to 10 seconds
var retries = 0;
while (!globalContext.hasProperty('PcmToOggModuleFactory'.toJS).toDart) {
if (retries++ > maxRetries) {
throw Exception(
'PcmToOggWeb: Timed out waiting for PcmToOggModuleFactory.',
);
}
await Future.delayed(const Duration(milliseconds: 50));
}
} else {}
final createModule = globalContext['PcmToOggModuleFactory'] as JSFunction;
final modulePromise =
createModule.callAsFunction(globalContext) as JSPromise;
final module = (await modulePromise.toDart) as JSObject;
// Chờ cho runtime C++ sẵn sàng ***
final completer = Completer<void>();
bool runtimeReady = false;
// Kiểm tra xem nó đã chạy xong chưa (trong trường hợp hot reload)
// *** ĐÃ SỬA LỖI PHƯƠNG THỨC (toDartBoolean -> toDart) TẠI ĐÂY ***
final JSAny? calledRunProp = module.getProperty('calledRun'.toJS);
if (module.hasProperty('calledRun'.toJS).toDart &&
calledRunProp is JSBoolean &&
calledRunProp.toDart) {
runtimeReady = true;
} else {
// Gán callback
module.setProperty(
'onRuntimeInitialized'.toJS,
() {
runtimeReady = true;
if (!completer.isCompleted) {
completer.complete();
}
}.toJS,
);
}
// Nếu chưa sẵn sàng, hãy đợi completer
if (!runtimeReady) {
await completer.future;
}
// *** KẾT THÚC SỬA LỖI ***
_wasmModule = module;
_wasmExports = _WasmExports._(module);
// Kiểm tra nhanh xem HEAPF32 có thực sự tồn tại không
if (!_wasmExports!.hasProperty('HEAPF32'.toJS).toDart) {
throw Exception('PcmToOggWeb: HEAPF32 not found on Wasm module.');
}
_isInitialized = true;
}