geesawra.industries/hydraulophone
An unofficial YouTube Music app for iPhone, iPad, and Mac.
0
0
import Foundation
import HydraulophoneCore
#if DEBUG
import CoreGraphics
import ImageIO
import UniformTypeIdentifiers
#endif
/// Deterministic data for previews and accessibility checks. It has no
/// transport implementation. A Debug-only launch flag enables silent local
/// playback for clock-driven lyrics UI tests.
actor OfflineFixtureMusicService: PaginatedLibraryMusicService, ArtistBrowsingMusicService,
LyricsProviding
{
private let libraryIsEmpty: Bool
private let libraryPageDelay: TimeInterval
#if DEBUG
private var silentPlaybackURL: URL?
#endif
init(libraryIsEmpty: Bool = false, libraryPageDelay: TimeInterval = 0) {
self.libraryIsEmpty = libraryIsEmpty
self.libraryPageDelay = libraryPageDelay
}
private let fixturePlaylist = Playlist(
id: "fixture-playlist",
title: "Offline Fixture Playlist",
subtitle: "Safe local preview data",
thumbnailURL: nil
)
private let fixtureSongs = [
Song(
id: "fixture-song-1",
title: "Fixture Sunrise",
artist: "Hydraulophone Demo",
album: "Fixture Collection",
durationText: "3:24",
thumbnailURL: nil,
artistReferences: [Artist(browseID: "fixture-artist", title: "Hydraulophone Demo")],
albumReference: Album(
browseID: "fixture-album", title: "Fixture Collection", subtitle: "Hydraulophone Demo",
artistReferences: [Artist(browseID: "fixture-artist", title: "Hydraulophone Demo")])
),
Song(
id: "fixture-song-2",
title: "Fixture Tide",
artist: "Hydraulophone Demo",
album: "Fixture Collection",
durationText: "2:58",
thumbnailURL: nil,
artistReferences: [Artist(browseID: "fixture-artist", title: "Hydraulophone Demo")],
albumReference: Album(
browseID: "fixture-album", title: "Fixture Collection", subtitle: "Hydraulophone Demo",
artistReferences: [Artist(browseID: "fixture-artist", title: "Hydraulophone Demo")])
),
]
private let fixtureAlbum = Album(
browseID: "fixture-album",
title: "Fixture Collection",
subtitle: "Hydraulophone Demo",
thumbnailURL: nil,
artistReferences: [Artist(browseID: "fixture-artist", title: "Hydraulophone Demo")]
)
private let fixtureArtist = Artist(
browseID: "fixture-artist",
title: "Hydraulophone Demo"
)
private let firstHomeContinuation = PaginationToken(rawValue: "fixture-home-page-2")
func search(query: String) async throws -> [SearchResult] {
guard !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
return []
}
return [
.song(fixtureSongs[0]),
.playlist(fixturePlaylist),
.album(fixtureAlbum),
.artist(fixtureArtist),
]
}
func playlists() async throws -> [Playlist] {
[fixturePlaylist]
}
func tracks(in playlist: Playlist) async throws -> [Song] {
guard playlist.id == fixturePlaylist.id else {
return []
}
#if DEBUG
if ProcessInfo.processInfo.arguments.contains("-HydraulophoneQueueScrollFixture") {
// Exercise real queue virtualization without credentials or remote artwork.
return fixtureSongs
+ (3...500).map { index in
Song(
id: "fixture-queue-\(index)", title: "Fixture Queue \(index)",
artist: "Hydraulophone Demo", album: "Fixture Collection", durationText: "3:24")
}
}
#endif
return fixtureSongs
}
func searchPage(
query: String,
continuation: PaginationToken?,
policy: CatalogLoadPolicy
) async throws -> Page<SearchResult> {
Page(items: try await search(query: query))
}
func playlistPage(
continuation: PaginationToken?,
policy: CatalogLoadPolicy
) async throws -> Page<Playlist> {
try await waitForLibraryPage()
guard !libraryIsEmpty else { return Page(items: []) }
return Page(items: [fixturePlaylist])
}
func libraryPage(
category: LibraryCategory,
continuation: PaginationToken?,
policy: CatalogLoadPolicy
) async throws -> Page<LibraryItem> {
try await waitForLibraryPage()
guard !libraryIsEmpty else { return Page(items: []) }
guard continuation == nil else { return Page(items: []) }
switch category {
case .playlists:
return Page(items: [LibraryItem.playlist(fixturePlaylist)])
case .songs:
return Page(items: fixtureSongs.map(LibraryItem.song))
case .albums:
return Page(items: [LibraryItem.album(fixtureAlbum)])
case .artists:
return Page(items: [LibraryItem.artist(fixtureArtist)])
}
}
func trackPage(
in playlist: Playlist,
continuation: PaginationToken?,
policy: CatalogLoadPolicy
) async throws -> Page<Song> {
Page(items: try await tracks(in: playlist))
}
func albumTrackPage(
in album: Album,
continuation: PaginationToken?,
policy: CatalogLoadPolicy
) async throws -> Page<Song> {
guard album.id == fixtureAlbum.id else {
return Page(items: [])
}
#if DEBUG
return Page(
items: fixtureSongs,
header: CatalogPageHeader(
title: fixtureAlbum.title, subtitle: fixtureAlbum.subtitle,
thumbnailURL: try detailArtworkURL(artist: false),
artistReferences: fixtureAlbum.artistReferences))
#else
return Page(items: fixtureSongs)
#endif
}
func homePage(
audience: HomeAudience,
filter: HomeFilter?,
continuation: PaginationToken?,
policy: CatalogLoadPolicy
) async throws -> HomePage {
guard continuation != firstHomeContinuation else {
return HomePage(
sections: [
HomeSection(
id: audience == .authenticated ? "fixture-for-you" : "fixture-discover",
title: audience == .authenticated ? "More for your listening" : "More to explore",
items: [.song(fixtureSongs[1])]
)
]
)
}
return HomePage(
filters: [
HomeFilter(title: "All"),
HomeFilter(title: "Calm", params: "fixture-calm"),
],
sections: [
HomeSection(
id: audience == .authenticated ? "fixture-for-you" : "fixture-discover",
title: audience == .authenticated ? "A start for you" : "A gentle start",
subtitle: audience == .authenticated
? "A deterministic offline listening shelf"
: "Explore without signing in",
items: [
.song(fixtureSongs[0]),
.playlist(fixturePlaylist),
]
),
HomeSection(
id: "fixture-albums",
title: "Albums to explore",
items: [.album(fixtureAlbum)]
),
],
next: firstHomeContinuation
)
}
func artistPage(_ artist: Artist, continuation: PaginationToken?, policy: CatalogLoadPolicy)
async throws -> HomePage
{
guard artist.id == fixtureArtist.id, continuation == nil else { return HomePage(sections: []) }
#if DEBUG
let header = CatalogPageHeader(
title: artist.title, thumbnailURL: try detailArtworkURL(artist: true))
#else
let header: CatalogPageHeader? = nil
#endif
return HomePage(
sections: [
HomeSection(
id: "artist-songs", title: "Top Songs", items: fixtureSongs.map(CatalogItem.song)),
HomeSection(id: "artist-albums", title: "Albums", items: [.album(fixtureAlbum)]),
], header: header)
}
func stream(for song: Song) async throws -> URL {
#if DEBUG
if ProcessInfo.processInfo.arguments.contains("-HydraulophoneLyricsPlaybackFixture"),
fixtureSongs.contains(where: { $0.id == song.id })
{
return try silentPlaybackStreamURL()
}
#endif
throw InnerTubeError.playbackUnavailable("Offline fixture playback is disabled.")
}
#if DEBUG
/// Synthetic PNGs exercise header artwork loading without remote requests.
private func detailArtworkURL(artist: Bool) throws -> URL {
let folder = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
.appendingPathComponent("HydraulophoneArtwork/v1/fixtures", isDirectory: true)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
let url = folder.appendingPathComponent(artist ? "artist.png" : "album.png")
if FileManager.default.fileExists(atPath: url.path) { return url }
guard
let context = CGContext(
data: nil, width: 64, height: 64, bitsPerComponent: 8, bytesPerRow: 256,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
else { throw InnerTubeError.invalidResponse("Could not create fixture artwork.") }
context.setFillColor(
CGColor(red: artist ? 0.1 : 0.85, green: artist ? 0.6 : 0.35, blue: 0.3, alpha: 1))
context.fill(CGRect(x: 0, y: 0, width: 64, height: 64))
context.setFillColor(CGColor(red: 1, green: 0.95, blue: 0.75, alpha: 1))
context.fill(CGRect(x: 16, y: 16, width: 32, height: 32))
guard let image = context.makeImage(),
let destination = CGImageDestinationCreateWithURL(
url as CFURL, UTType.png.identifier as CFString, 1, nil)
else { throw InnerTubeError.invalidResponse("Could not encode fixture artwork.") }
CGImageDestinationAddImage(destination, image, nil)
guard CGImageDestinationFinalize(destination) else {
throw InnerTubeError.invalidResponse("Could not save fixture artwork.")
}
return url
}
private func silentPlaybackStreamURL() throws -> URL {
if let silentPlaybackURL, FileManager.default.fileExists(atPath: silentPlaybackURL.path) {
return silentPlaybackURL
}
let url = FileManager.default.temporaryDirectory.appendingPathComponent(
"hydraulophone-lyrics-silent-180s.wav"
)
let sampleRate: UInt32 = 8_000
let durationSeconds: UInt32 = 180
let bytesPerSample: UInt32 = 2
let audioByteCount = sampleRate * durationSeconds * bytesPerSample
let expectedFileSize = Int(audioByteCount) + 44
if let attributes = try? FileManager.default.attributesOfItem(atPath: url.path),
let size = attributes[.size] as? NSNumber, size.intValue == expectedFileSize
{
silentPlaybackURL = url
return url
}
var wav = Data(capacity: expectedFileSize)
wav.append(contentsOf: "RIFF".utf8)
appendLittleEndian(36 + audioByteCount, to: &wav)
wav.append(contentsOf: "WAVEfmt ".utf8)
appendLittleEndian(UInt32(16), to: &wav)
appendLittleEndian(UInt16(1), to: &wav) // PCM
appendLittleEndian(UInt16(1), to: &wav) // mono
appendLittleEndian(sampleRate, to: &wav)
appendLittleEndian(sampleRate * bytesPerSample, to: &wav)
appendLittleEndian(UInt16(bytesPerSample), to: &wav)
appendLittleEndian(UInt16(16), to: &wav)
wav.append(contentsOf: "data".utf8)
appendLittleEndian(audioByteCount, to: &wav)
wav.append(Data(count: Int(audioByteCount)))
try wav.write(to: url, options: .atomic)
silentPlaybackURL = url
return url
}
private func appendLittleEndian(_ value: UInt16, to data: inout Data) {
data.append(UInt8(truncatingIfNeeded: value))
data.append(UInt8(truncatingIfNeeded: value >> 8))
}
private func appendLittleEndian(_ value: UInt32, to data: inout Data) {
data.append(UInt8(truncatingIfNeeded: value))
data.append(UInt8(truncatingIfNeeded: value >> 8))
data.append(UInt8(truncatingIfNeeded: value >> 16))
data.append(UInt8(truncatingIfNeeded: value >> 24))
}
#endif
func lyrics(for song: Song) async throws -> SongLyrics? {
switch song.id {
case "fixture-song-1":
let text = [
"Morning colors wake the water",
"Soft blue gathers at the shore",
"A little light crosses the window",
"And finds a place upon the floor",
"Every ripple draws a circle",
"Every circle travels on",
"We follow where the daylight settles",
"Then turn to greet the coming dawn",
"A quiet current carries echoes",
"Past the stones and through the reeds",
"The open sky reflects in pieces",
"Like a map of where it leads",
"We let the bright horizon widen",
"We let the turning water sing",
"The morning holds its colors longer",
"As the gentle ripples ring",
"The last soft wave returns to stillness",
"And leaves its light on everything",
]
let firstLineWords = [
LyricsWord(text: "Morning ", startTime: 0, endTime: 2.4),
LyricsWord(text: "colors ", startTime: 2.4, endTime: 4.5),
LyricsWord(text: "wake ", startTime: 4.5, endTime: 6.2),
LyricsWord(text: "the ", startTime: 6.2, endTime: 7.3),
LyricsWord(text: "water", startTime: 7.3, endTime: 10),
]
return SongLyrics(
lines: text.enumerated().map { index, line in
LyricsLine(
id: index + 1,
text: line,
startTime: TimeInterval(index * 10),
endTime: TimeInterval((index + 1) * 10),
words: index == 0 ? firstLineWords : []
)
},
source: "Hydraulophone fixture"
)
case "fixture-song-2":
let text = [
"The tide arrives in quiet circles",
"A pale line touches the sand",
"The harbor keeps a small reflection",
"Of passing clouds above the land",
"We count the stones beside the pathway",
"We watch the distant boats return",
"A lantern glows along the railing",
"Its steady light begins to burn",
"The water lifts and lowers gently",
"The evening air is clear and cool",
"A narrow wake crosses the inlet",
"Then smooths the surface of the pool",
"No clock can hurry this horizon",
"No chart can tell the waves to stay",
"We listen for the smallest current",
"And let the last bright color fade",
"The city lights appear in fragments",
"Across the water, one by one",
"A gull circles above the harbor",
"Then follows where the boats have gone",
"The tide returns in quiet circles",
"And leaves a silver edge behind",
"The shoreline holds the fading daylight",
"A simple place to rest the mind",
]
return SongLyrics(
lines: text.enumerated().map { index, line in
LyricsLine(id: index + 1, text: line)
},
source: "Hydraulophone fixture"
)
default:
return nil
}
}
private func waitForLibraryPage() async throws {
guard libraryPageDelay > 0 else { return }
try await Task.sleep(for: .seconds(libraryPageDelay))
}
}