159 lines · 8.2 KB · SwiftRaw
import CottonKitimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class WhatsAppVoiceTests: XCTestCase { // WhatsApp keeps the original Opus object. Playing it must use the // Mac's playable rendition, and cannot offer an Ogg file to AVFoundation. func testPlaybackUsesTheRenditionAndRetainsTheOriginal() throws { let json = try JSONDecoder().decode(JSONValue.self, from: Data(#"{"key":"original.ogg","contentType":"audio/ogg","kind":"voice","durationMs":2000,"playbackKey":"playable.m4a","playbackContentType":"audio/mp4"}"#.utf8)) let entry = MessageMedia(json) XCTAssertEqual(entry.key, "original.ogg") XCTAssertEqual(entry.audioPlaybackKey, "playable.m4a") XCTAssertEqual(MessageMedia(key: "unconverted.ogg", contentType: "audio/ogg", kind: "voice").audioPlaybackKey, nil) XCTAssertEqual(MessageMedia(key: "recording.wav", contentType: "audio/wav", kind: "voice").audioPlaybackKey, "recording.wav") } // RULE: WhatsApp retains its Ogg source; native CAF playback asks only for the rendition and keeps the duration supplied by the reader. func testCAFPlaybackUsesOnlyTheRenditionKeyAndKeepsItsDuration() async throws { // Golden CAF from voice_rendition_tests::voice_note(100, 312, 0). let bytes = try XCTUnwrap(Data(base64Encoded: "Y2FmZgABAABkZXNjAAAAAAAAACBA53AAAAAAAG9wdXMAAAAAAAAAAAAAA8AAAAABAAAAAHBha3QAAAAAAAAAfAAAAAAAAABk" + "AAAAAAABdcgAAAE4AAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMD" + "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwNkYXRhAAAAAAAAATAAAAAA+P/++P/++P/++P/+" + "+P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/+" + "+P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/+" + "+P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/+" + "+P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/++P/+" )) let path = FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).caf") try bytes.write(to: path) defer { try? FileManager.default.removeItem(at: path) } let entry = MessageMedia(key: "source.ogg", contentType: "audio/ogg", kind: "voice", durationMs: 1993, playbackKey: "playable.caf", playbackContentType: "audio/x-caf") let reply = try XCTUnwrap(String(data: JSONSerialization.data(withJSONObject: [ "present": true, "path": path.path, "tier": "original" ]), encoding: .utf8)) let core = ScriptedCore([CottonMethod.readMediaPath: .ok(reply)]) let voice = VoiceNotePlayer() defer { voice.stop() } await voice.toggle(entry.audioPlaybackKey, media: PhotosMediaSource(core: core)) XCTAssertEqual(voice.playingKey, "playable.caf") XCTAssertEqual(voice.duration, 1.9935, accuracy: 0.01) XCTAssertEqual(entry.durationMs, 1993) XCTAssertEqual(entry.key, "source.ogg") let calls = await core.calls XCTAssertEqual(calls.map(\.method), [CottonMethod.readMediaPath]) let call = try XCTUnwrap(calls.first) let request = try JSONSerialization.jsonObject(with: Data(call.requestJSON.utf8)) as? [String: Any] XCTAssertEqual(request?["key"] as? String, "playable.caf") } // RULE: An Ogg voice without a rendition has no playback key and must never fetch or play the original as a substitute. func testAMissingRenditionNeverFetchesOrPlaysTheOggOriginal() async { let entry = MessageMedia(key: "source.ogg", contentType: "audio/ogg", kind: "voice", durationMs: 1993) let core = ScriptedCore() let voice = VoiceNotePlayer() await voice.toggle(entry.audioPlaybackKey, media: PhotosMediaSource(core: core)) XCTAssertNil(voice.playingKey) XCTAssertNil(voice.loadingKey) XCTAssertEqual(entry.key, "source.ogg") XCTAssertEqual(entry.durationMs, 1993) let calls = await core.methodsCalled() XCTAssertTrue(calls.isEmpty) } // Pause keeps the position; resuming the same note does not ask for its // bytes again. A different note ends the first one, and leaving ends both. func testPauseResumesTheSameRecordingWithoutRefetching() async throws { let path = try recording() let reply = try XCTUnwrap(String(data: JSONSerialization.data(withJSONObject: [ "present": true, "path": path.path, "tier": "original" ]), encoding: .utf8)) let core = ScriptedCore([CottonMethod.readMediaPath: .ok(reply)]) let media = PhotosMediaSource(core: core) let voice = VoiceNotePlayer() await voice.toggle("first.wav", media: media) XCTAssertEqual(voice.playingKey, "first.wav") XCTAssertEqual(voice.duration, 2, accuracy: 0.01) try await Task.sleep(for: .milliseconds(150)) await voice.toggle("first.wav", media: media) XCTAssertNil(voice.playingKey) XCTAssertEqual(voice.pausedKey, "first.wav") let held = voice.elapsed XCTAssertGreaterThan(held, 0) try await Task.sleep(for: .milliseconds(100)) XCTAssertEqual(voice.elapsed, held, accuracy: 0.01) await voice.toggle("first.wav", media: media) XCTAssertEqual(voice.playingKey, "first.wav") XCTAssertGreaterThanOrEqual(voice.elapsed, held) let asked = await core.methodsCalled() XCTAssertEqual(asked, [CottonMethod.readMediaPath]) await voice.toggle("second.wav", media: media) XCTAssertEqual(voice.playingKey, "second.wav") XCTAssertNil(voice.pausedKey) voice.stop() XCTAssertNil(voice.playingKey) XCTAssertNil(voice.pausedKey) XCTAssertNil(voice.loadingKey) } // A late availability answer cannot start playback or a download after // the conversation has gone away. func testLeavingDuringALocalReadDoesNotFetchOrStartTheNote() async throws { let core = PendingVoiceCore() let voice = VoiceNotePlayer() let loading = Task { await voice.toggle("pending.wav", media: PhotosMediaSource(core: core)) } for _ in 0..<100 { if await core.waiting { break } try await Task.sleep(for: .milliseconds(10)) } let waiting = await core.waiting XCTAssertTrue(waiting) voice.stop() await core.finish() await loading.value XCTAssertNil(voice.playingKey) XCTAssertNil(voice.loadingKey) let calls = await core.calls XCTAssertEqual(calls, [CottonMethod.readMediaPath]) } private func recording() throws -> URL { var bytes = Data() func word(_ value: UInt32, count: Int) { for shift in 0..<count { bytes.append(UInt8(truncatingIfNeeded: value >> (shift * 8))) } } bytes.append(Data("RIFF".utf8)); word(32_036, count: 4) bytes.append(Data("WAVEfmt ".utf8)); word(16, count: 4) word(1, count: 2); word(1, count: 2); word(8_000, count: 4); word(16_000, count: 4) word(2, count: 2); word(16, count: 2) bytes.append(Data("data".utf8)); word(32_000, count: 4) bytes.append(Data(repeating: 0, count: 32_000)) let path = FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).wav") try bytes.write(to: path) return path }}private actor PendingVoiceCore: CottonCalling { var waiting = false var calls: [String] = [] private var answer: CheckedContinuation<String, Never>? func callRaw(_ method: String, requestJSON: String) async -> String { calls.append(method) guard method == CottonMethod.readMediaPath else { return #"{"ok":false,"error":{"code":"missing","message":"Not here"}}"# } return await withCheckedContinuation { answer in self.answer = answer waiting = true } } func finish() { answer?.resume(returning: #"{"ok":true,"data":{"present":false}}"#) answer = nil } func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {} func close() {}}