@dvai-bridge/android-mediapipe-core 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,51 @@
1
+ # Deep Voice Ai Limited - Software License Agreement
2
+
3
+ **Version 1.0.0**
4
+
5
+ This License Agreement governs the use of the DVAI-Bridge software (the "Software"). By downloading, installing, or using the Software, you agree to be bound by the terms of this License.
6
+
7
+ ---
8
+
9
+ ## 1. LICENSE GRANTS
10
+
11
+ ### 1.1 Development and Personal Use (Free Tier)
12
+ Deep Voice Ai Limited ("Licensor") grants you a non-exclusive, non-transferable, royalty-free license to use the Software solely for:
13
+ - Internal development and testing purposes.
14
+ - Non-commercial personal projects.
15
+ - Academic and non-profit research.
16
+
17
+ ### 1.2 Commercial Use (Paid Tier)
18
+ Any use of the Software for **Commercial Purposes** requires a separate, paid Commercial License from Licensor. "Commercial Purposes" include:
19
+ - Use in production environments.
20
+ - Integration into revenue-generating products or services.
21
+ - Distribution to third-party customers for a fee.
22
+ - Use by an entity with more than $100,000 USD in annual revenue.
23
+
24
+ To obtain a Commercial License, contact `info@deepvoiceai.co` or visit `https://deepvoiceai.co/licensing`.
25
+
26
+ ---
27
+
28
+ ## 2. RESTRICTIONS
29
+ Except as expressly permitted, you may not:
30
+ - Sublicense, rent, lease, or resell the Software without express permission.
31
+ - Remove any proprietary notices or branding from the Software.
32
+ - Use the Software for any illegal or malicious purposes.
33
+
34
+ ---
35
+
36
+ ## 3. INTELLECTUAL PROPERTY
37
+ The Software is owned by **Deep Voice Ai Limited** and is protected by copyright and intellectual property laws. This agreement does not transfer ownership of the Software.
38
+
39
+ ---
40
+
41
+ ## 4. NO WARRANTY
42
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL THE LICENSOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE.
43
+
44
+ ---
45
+
46
+ ## 5. GOVERNING LAW
47
+ This License shall be governed by and construed in accordance with the laws of the jurisdiction where Deep Voice Ai Limited is registered.
48
+
49
+ ---
50
+
51
+ © 2026 Deep Voice Ai Limited. All rights reserved.
package/README.md ADDED
@@ -0,0 +1,199 @@
1
+ ![DVAI-Bridge](/assets/banner.png)
2
+
3
+ # DVAI-Bridge
4
+
5
+ <!-- [![Smoke — real models](https://github.com/Westenets/dvai-bridge/actions/workflows/smoke-real-models.yml/badge.svg?branch=main)](https://github.com/Westenets/dvai-bridge/actions/workflows/smoke-real-models.yml) -->
6
+
7
+ [![License](https://img.shields.io/badge/License-Commercial-blue.svg)](LICENSE) ![Node.js](https://img.shields.io/badge/Node.js-22+-green?logo=node.js) ![TypeScript](https://img.shields.io/badge/TypeScript-5.6+-blue?logo=typescript) ![Swift](https://img.shields.io/badge/Swift-5.9+-F05138?logo=swift) ![Kotlin](https://img.shields.io/badge/Kotlin-2.0+-7F52FF?logo=kotlin) ![Flutter](https://img.shields.io/badge/Flutter-3.39+-02569B?logo=flutter) ![.NET](https://img.shields.io/badge/.NET-10.0_LTS-512BD4?logo=dotnet)
8
+
9
+ > **The local OpenAI server you embed inside your app.**
10
+ > One library. One HTTP wire. Every platform. Zero install for your users.
11
+
12
+ **Docs:** [dvai-bridge.deepvoiceai.co](https://dvai-bridge.deepvoiceai.co)
13
+
14
+ ```ts
15
+ import { DVAI } from "@dvai-bridge/core";
16
+ import OpenAI from "openai";
17
+
18
+ const dvai = new DVAI({ backend: "transformers" });
19
+ await dvai.initialize();
20
+
21
+ const openai = new OpenAI({ baseURL: dvai.baseUrl, apiKey: "ignored" });
22
+ await openai.chat.completions.create({
23
+ model: dvai.transformersModelId,
24
+ messages: [{ role: "user", content: "Hello!" }],
25
+ });
26
+ ```
27
+
28
+ That's it. A real OpenAI-compatible server is now running inside your app's
29
+ own process. Point any OpenAI client — LangChain, the OpenAI SDK, the Vercel
30
+ AI SDK, anything — at `dvai.baseUrl` and your agent code keeps working.
31
+
32
+ Built by **[Deep Voice AI](https://deepvoiceai.co)**.
33
+
34
+ ---
35
+
36
+ ## Why it exists
37
+
38
+ Local AI works beautifully on a laptop with **Ollama + LangChain**. Then you
39
+ try to ship the app and your users don't have Ollama. Mobile can't run it.
40
+ Corporate IT won't add another daemon. So you reinvent the same plumbing —
41
+ spawn an inference engine, bind a port, translate to OpenAI HTTP, handle
42
+ CORS, manage lifecycle, wrap the accelerator of the day per platform — and
43
+ do it all over again for every target OS.
44
+
45
+ DVAI-Bridge is that plumbing, packaged as a library, for every client
46
+ platform.
47
+
48
+ ---
49
+
50
+ ## What you get
51
+
52
+ - **One OpenAI HTTP surface.** Bound on `127.0.0.1` (or `0.0.0.0` for
53
+ device-to-device). Streaming, embeddings, models, recovery — all built in.
54
+ - **Six SDKs.** `@dvai-bridge/core` + `react` + `vanilla` + `capacitor`,
55
+ `DVAIBridge` (Swift / iOS), `co.deepvoiceai:dvai-bridge` (Kotlin / Android),
56
+ `@dvai-bridge/react-native`, `dvai_bridge` (Flutter), `co.deepvoiceai.dvai-bridge` (.NET).
57
+ - **Nine backends.** WebLLM, Transformers.js, llama.cpp, Apple Foundation
58
+ Models, MLX, CoreML / ANE, MediaPipe LLM, LiteRT, ONNX Runtime GenAI —
59
+ selected per-platform, invisible to your agent code.
60
+ - **Native acceleration** wherever it runs: WebGPU in browsers, CUDA / Metal
61
+ / Vulkan / DirectML on desktop, ANE / Metal / MLX on iOS, NNAPI / QNN
62
+ Hexagon / GPU delegate on Android.
63
+ - **Multimodal.** Text, image, audio, video — declarative loader for
64
+ cutting-edge models (Gemma 4, LLaVA, Idefics) without waiting for library
65
+ updates.
66
+ - **Distributed inference (v3.0+).** Phone too slow? Offload to your laptop
67
+ on the same Wi-Fi via mDNS pairing — same OpenAI wire, transparent to
68
+ your code. Internet path via a self-hostable rendezvous server.
69
+ - **DVAI Hub (v3.1+).** A first-party desktop utility that turns any device
70
+ into a strong-peer for the rest of your fleet. Brand-neutral install via
71
+ Homebrew / winget / GitHub Releases, OR fork it for your own branded
72
+ companion. Routes through Ollama / LM Studio / vLLM / llama-server /
73
+ llamafile if you've already got those running.
74
+ - **Zero user install.** It's a library, not a daemon. `npm install`,
75
+ `cocoapods`, gradle — your CI already has the muscle for it.
76
+
77
+ ---
78
+
79
+ ## Supported platforms
80
+
81
+ | Stack | Package | Backends |
82
+ | --- | --- | --- |
83
+ | Browser (React, Vue, Svelte, vanilla JS) | `@dvai-bridge/core` + `react` / `vanilla` | WebLLM (WebGPU), Transformers.js (WebGPU / WASM SIMD) |
84
+ | Node / Bun / Electron | `@dvai-bridge/core` | Transformers.js, native llama.cpp |
85
+ | Capacitor hybrid mobile | `@dvai-bridge/capacitor` + backend slice | Native llama.cpp (Metal iOS, Vulkan / CPU Android) |
86
+ | iOS native (Swift) | `DVAIBridge` (SPM / CocoaPods) | llama.cpp (Metal), CoreML / ANE, Apple Foundation Models, MLX |
87
+ | Android native (Kotlin / Java) | `co.deepvoiceai:dvai-bridge` (AAR) | llama.cpp, MediaPipe LLM, LiteRT, NNAPI / QNN |
88
+ | React Native (≥0.77, TurboModule) | `@dvai-bridge/react-native` | All iOS + Android backends (delegates) |
89
+ | Flutter (≥3.39) | `dvai_bridge` (pub.dev) | All iOS + Android backends (Pigeon channels) |
90
+ | .NET 10 LTS (MAUI / Avalonia / WinUI / Catalyst / desktop) | `co.deepvoiceai.dvai-bridge*` (NuGet) | iOS / Android delegate to native; desktop = llama.cpp + ONNX Runtime GenAI + ML.NET |
91
+
92
+ Full quickstart per platform: [dvai-bridge.deepvoiceai.co/guide/getting-started](https://dvai-bridge.deepvoiceai.co/guide/getting-started)
93
+
94
+ ---
95
+
96
+ ## Examples
97
+
98
+ ```ts
99
+ // React
100
+ import { DVAIProvider, useDVAI } from "@dvai-bridge/react";
101
+ <DVAIProvider config={{ backend: "transformers" }}>
102
+ <Chat />
103
+ </DVAIProvider>;
104
+ function Chat() {
105
+ const { isReady, baseUrl } = useDVAI();
106
+ return isReady ? <div>Local AI live at {baseUrl}</div> : <Loading />;
107
+ }
108
+ ```
109
+
110
+ ```swift
111
+ // iOS
112
+ let server = try await DVAIBridge.shared.start()
113
+ // server.baseUrl = "http://127.0.0.1:38883/v1"
114
+ ```
115
+
116
+ ```kotlin
117
+ // Android
118
+ val server = DVAIBridge.start(context)
119
+ // server.baseUrl = "http://127.0.0.1:38883/v1"
120
+ ```
121
+
122
+ ```dart
123
+ // Flutter
124
+ final state = await DVAIBridge.instance.start(
125
+ backend: BackendKind.auto,
126
+ modelPath: '/path/to/model.gguf',
127
+ );
128
+ // state.baseUrl = "http://127.0.0.1:38883/v1"
129
+ ```
130
+
131
+ ```csharp
132
+ // .NET
133
+ var server = await DVAIBridge.Shared.StartAsync(new StartOptions {
134
+ Backend = BackendKind.Auto,
135
+ ModelPath = "/path/to/model.gguf",
136
+ });
137
+ // server.BaseUrl = "http://127.0.0.1:38883/v1"
138
+ ```
139
+
140
+ Multimodal, streaming, embeddings, distributed offload, the Hub —
141
+ everything's at the [docs site](https://dvai-bridge.deepvoiceai.co).
142
+
143
+ ---
144
+
145
+ ## What's new in v3.1
146
+
147
+ - **DVAI Hub** — Tauri desktop utility that's the strong-peer side of v3
148
+ distributed inference. `brew install deepvoiceai/dvai-hub/dvai-hub` (or
149
+ `winget install DeepVoiceAI.DVAIHub`) → mobile apps on the same Wi-Fi
150
+ pair with it and offload heavy inference. [Guide →](https://dvai-bridge.deepvoiceai.co/guide/dvai-hub)
151
+ - **External-engine bridge.** Hub surfaces Ollama / LM Studio / vLLM /
152
+ llama-server / llamafile as additional backend pools so paired apps
153
+ serve from whatever's already cached. Opt-in per engine.
154
+ - **Strict substitution policy.** Models with mismatched family / version /
155
+ size / type are refused by default; quant-only mismatches gated behind a
156
+ per-pairing `preferBetterQuant` flag. No silent mis-routing.
157
+ - **HMAC-signed identity** on `/v1/chat/completions`. Per-app audit logs
158
+ surface who served what, with structured `(appId, peerDeviceId,
159
+ engine, requestedModel, servedModel, outcome)` rows.
160
+ - **Library finalization.** `httpBindHost` (LAN bind), `chatCompletionInterceptor`
161
+ (extension point), HMAC primitives re-exported, `/v1/dvai/*` routes
162
+ actually dispatched, TransformersBackend Node-mode device fix.
163
+ [Migration v3.0 → v3.1 →](https://dvai-bridge.deepvoiceai.co/migration/v3.0-to-v3.1)
164
+
165
+ ---
166
+
167
+ ## Robustness
168
+
169
+ Streaming-correct (SSE passthrough + blank-chunk detection), generation
170
+ timeout, automatic engine-state recovery on fatal errors, port fallback,
171
+ worker offloading, Private Network Access ready, CORS configured. The
172
+ boring substrate so your agent code never has to think about it.
173
+
174
+ ---
175
+
176
+ ## Licensing
177
+
178
+ Dual: **free for development & personal use** on `localhost` (verified at
179
+ runtime). **Commercial use** requires a license key — `info@deepvoiceai.co`.
180
+
181
+ ---
182
+
183
+ ## Contributing
184
+
185
+ PRs welcome.
186
+
187
+ ```bash
188
+ pnpm install
189
+ pnpm build
190
+ bash scripts/build-all.sh # full matrix (auto-skips per-host)
191
+ ```
192
+
193
+ [`CONTRIBUTING.md`](./CONTRIBUTING.md) for the PR flow. Per-platform
194
+ contributor docs (iOS / Android / RN / Flutter / .NET) under
195
+ [`docs/development/`](./docs/development/).
196
+
197
+ ---
198
+
199
+ © Deep Voice AI Limited. All rights reserved.
@@ -0,0 +1,134 @@
1
+ buildscript {
2
+ ext {
3
+ kotlinVersion = '2.3.21'
4
+ }
5
+ repositories {
6
+ google()
7
+ mavenCentral()
8
+ }
9
+ dependencies {
10
+ classpath 'com.android.tools.build:gradle:9.2.0'
11
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
12
+ }
13
+ }
14
+
15
+ ext {
16
+ junitVersion = '4.13.2'
17
+ androidxAppCompatVersion = '1.7.1'
18
+ coroutinesVersion = '1.10.2'
19
+ // Pinned within Ktor 2.x — Ktor 3 has breaking API changes around server
20
+ // configuration that would require non-trivial refactors. Stay on the
21
+ // latest 2.x patch (2.3.13) until a deliberate Ktor 3 migration.
22
+ ktorVersion = '2.3.13'
23
+ // LiteRT-LM — replaces the deprecated `com.google.mediapipe:tasks-genai`
24
+ // (Phase 3B, Tasks 18-19). `litertlm-android` bundles the full runtime;
25
+ // no separate `tasks-core` companion is required.
26
+ // Hosted on Google Maven (google() repo, already declared in allprojects).
27
+ litertLmVersion = '0.10.2'
28
+ }
29
+
30
+ allprojects {
31
+ repositories {
32
+ google()
33
+ mavenCentral()
34
+ // Phase 3D: shared-core lives here in dev (after `publishToMavenLocal`).
35
+ // Production publishes resolve from GitHub Packages.
36
+ mavenLocal()
37
+ }
38
+ }
39
+
40
+ // AGP 9+ ships built-in Kotlin support; the standalone 'kotlin-android'
41
+ // plugin is no longer needed (and is rejected by the build).
42
+ // See https://kotl.in/gradle/agp-built-in-kotlin
43
+ apply plugin: 'com.android.library'
44
+ apply plugin: 'maven-publish'
45
+
46
+ android {
47
+ namespace 'co.deepvoiceai.bridge.mediapipe.core'
48
+ // Phase 2 Task 3 (examples) library fix: see shared-core/android/build.gradle
49
+ // for the rationale — `-PcompileSdkOverride=35` lets Windows hosts sidestep
50
+ // an AGP 9.2.0 parseLocalResources bug against android-36's public-final.xml.
51
+ compileSdk(project.findProperty('compileSdkOverride')?.toInteger() ?: 36)
52
+
53
+ defaultConfig {
54
+ minSdk 24
55
+ targetSdk(project.findProperty('compileSdkOverride')?.toInteger() ?: 36)
56
+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
57
+ }
58
+
59
+ compileOptions {
60
+ sourceCompatibility JavaVersion.VERSION_17
61
+ targetCompatibility JavaVersion.VERSION_17
62
+ }
63
+ testOptions {
64
+ unitTests.includeAndroidResources = true
65
+ }
66
+
67
+ publishing {
68
+ singleVariant('release') {
69
+ withSourcesJar()
70
+ }
71
+ }
72
+ }
73
+
74
+ // AGP 9 / Kotlin 2.x: the legacy android.kotlinOptions block is gone. The
75
+ // replacement is the standalone `kotlin { compilerOptions { ... } }` extension
76
+ // (provided by AGP's built-in Kotlin integration).
77
+ kotlin {
78
+ compilerOptions {
79
+ jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
80
+ }
81
+ }
82
+
83
+ dependencies {
84
+ // Phase 3D: shared HTTP server + handler dispatch types live here.
85
+ // `api` (not `implementation`) so consumer projects see them transitively.
86
+ api "co.deepvoiceai:android-shared-core:$dvaiBridgeVersion"
87
+
88
+ implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
89
+ implementation "io.ktor:ktor-server-core:$ktorVersion"
90
+ implementation "io.ktor:ktor-server-cio:$ktorVersion"
91
+ implementation "io.ktor:ktor-server-cors:$ktorVersion"
92
+ implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutinesVersion"
93
+ implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.11.0'
94
+ implementation 'com.squareup.okhttp3:okhttp:5.3.2'
95
+
96
+ // LiteRT-LM: non-deprecated successor to tasks-genai (Phase 3B Task 18-19).
97
+ // Bundles the full LLM runtime including vision support via EngineConfig.visionBackend.
98
+ // ~100MB native libs per ABI — first build will be slow.
99
+ implementation "com.google.ai.edge.litertlm:litertlm-android:$litertLmVersion"
100
+
101
+ testImplementation "junit:junit:$junitVersion"
102
+ testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutinesVersion"
103
+ testImplementation 'org.robolectric:robolectric:4.16.1'
104
+ testImplementation "io.ktor:ktor-server-test-host:$ktorVersion"
105
+ testImplementation 'com.squareup.okhttp3:mockwebserver:5.3.2'
106
+
107
+ androidTestImplementation 'androidx.test:runner:1.7.0'
108
+ androidTestImplementation 'androidx.test.ext:junit:1.3.0'
109
+ }
110
+
111
+ // Phase 3D Task 4: copy-paste publishing block (see llama-core for the
112
+ // rationale on why each Gradle root has its own copy).
113
+ afterEvaluate {
114
+ publishing {
115
+ publications {
116
+ release(MavenPublication) {
117
+ groupId = 'co.deepvoiceai'
118
+ artifactId = 'android-mediapipe-core'
119
+ version = (project.findProperty('dvaiBridgeVersion') ?: '4.0.0').toString()
120
+ from components.release
121
+ }
122
+ }
123
+ repositories {
124
+ maven {
125
+ name = 'GitHubPackages'
126
+ url = uri('https://maven.pkg.github.com/dvai-global/dvai-bridge')
127
+ credentials {
128
+ username = project.findProperty('gpr.user') ?: System.getenv('GITHUB_ACTOR')
129
+ password = project.findProperty('gpr.key') ?: System.getenv('GITHUB_TOKEN')
130
+ }
131
+ }
132
+ }
133
+ }
134
+ }
@@ -0,0 +1,5 @@
1
+ android.useAndroidX=true
2
+ kotlin.code.style=official
3
+ android.nonTransitiveRClass=true
4
+ org.gradle.jvmargs=-Xmx4096m
5
+ dvaiBridgeVersion=4.0.0
@@ -0,0 +1 @@
1
+ rootProject.name = 'dvai-bridge-android-mediapipe-core'
@@ -0,0 +1,14 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
3
+ <application>
4
+ <!-- LiteRT-LM GPU backend optional native libs (Phase 3B Task 18-19).
5
+ android:required="false" lets devices without these still run on
6
+ the CPU backend rather than failing installation outright. -->
7
+ <uses-native-library
8
+ android:name="libvndksupport.so"
9
+ android:required="false" />
10
+ <uses-native-library
11
+ android:name="libOpenCL.so"
12
+ android:required="false" />
13
+ </application>
14
+ </manifest>
@@ -0,0 +1,115 @@
1
+ package co.deepvoiceai.bridge.mediapipe.core
2
+
3
+ import okhttp3.OkHttpClient
4
+ import okhttp3.Request
5
+ import java.io.File
6
+ import java.net.URI
7
+ import java.net.URLDecoder
8
+ import java.util.Base64
9
+ import java.util.concurrent.TimeUnit
10
+
11
+ /**
12
+ * Errors thrown by [ImageDecoder.resolve] when the input URL string can't
13
+ * be turned into image bytes.
14
+ */
15
+ sealed class ImageSourceError(msg: String) : Exception(msg) {
16
+ class MalformedDataURL(url: String) : ImageSourceError("malformed data URL: $url")
17
+ class MalformedURL(url: String) : ImageSourceError("malformed URL: $url")
18
+ class InvalidScheme(scheme: String) : ImageSourceError("unsupported URL scheme: $scheme")
19
+ class HttpError(val status: Int) : ImageSourceError("HTTP $status")
20
+ class Base64DecodeFailed : ImageSourceError("base64 decode failed")
21
+ }
22
+
23
+ /**
24
+ * Resolves any of the three image URL schemes accepted by the DVAI bridge
25
+ * (`data:`, `https:`/`http:`, `file:`) into the raw encoded image bytes
26
+ * (PNG/JPEG/etc.). Format decoding into pixel buffers is performed downstream
27
+ * by Android's `BitmapFactory` (then wrapped in `MPImage` via
28
+ * `BitmapImageBuilder`) — this layer just materializes the encoded bytes.
29
+ *
30
+ * Byte-identical to capacitor-llama's `ImageDecoder` modulo package
31
+ * declaration. If you fix a bug here, mirror it there (and vice versa).
32
+ *
33
+ * Blocking: HTTP fetches use OkHttp synchronously. Call from a background
34
+ * thread or coroutine on `Dispatchers.IO` (the plugin layer already does).
35
+ */
36
+ object ImageDecoder {
37
+ private val httpClient: OkHttpClient by lazy {
38
+ // `callTimeout` caps the entire HTTP exchange (DNS + connect + write
39
+ // + read + redirect) at 30s so worst-case latency matches iOS, where
40
+ // `URLRequest.timeoutInterval = 30` covers the whole request.
41
+ OkHttpClient.Builder()
42
+ .callTimeout(30, TimeUnit.SECONDS)
43
+ .build()
44
+ }
45
+
46
+ /**
47
+ * Resolve any supported URL scheme into raw image bytes.
48
+ *
49
+ * - `data:` URLs are parsed for an optional `;base64` token and decoded
50
+ * accordingly (URL-encoded payloads are also supported).
51
+ * - `https:` / `http:` URLs are fetched via OkHttp with a 30s timeout;
52
+ * non-2xx responses throw [ImageSourceError.HttpError].
53
+ * - `file:` URLs are read off disk via [File.readBytes].
54
+ * - Any other scheme throws [ImageSourceError.InvalidScheme].
55
+ * - URLs that fail to parse, lack a scheme, or have a missing/empty
56
+ * `file:` path throw [ImageSourceError.MalformedURL].
57
+ */
58
+ fun resolve(url: String): ByteArray {
59
+ if (url.startsWith("data:")) {
60
+ return resolveDataURL(url)
61
+ }
62
+ return resolveWithClient(url, httpClient)
63
+ }
64
+
65
+ /**
66
+ * Test seam: same contract as [resolve] but lets the caller inject an
67
+ * [OkHttpClient] (e.g. one pointed at MockWebServer). Data URLs still
68
+ * short-circuit before the client is consulted.
69
+ */
70
+ internal fun resolveWithClient(url: String, client: OkHttpClient): ByteArray {
71
+ if (url.startsWith("data:")) {
72
+ return resolveDataURL(url)
73
+ }
74
+ val parsed = try {
75
+ URI(url)
76
+ } catch (_: Exception) {
77
+ throw ImageSourceError.MalformedURL(url)
78
+ }
79
+ val scheme = parsed.scheme?.lowercase() ?: throw ImageSourceError.MalformedURL(url)
80
+ return when (scheme) {
81
+ "https", "http" -> fetchHttp(url, client)
82
+ "file" -> {
83
+ val path = parsed.path
84
+ if (path.isNullOrEmpty()) throw ImageSourceError.MalformedURL(url)
85
+ File(path).readBytes()
86
+ }
87
+ else -> throw ImageSourceError.InvalidScheme(scheme)
88
+ }
89
+ }
90
+
91
+ /** Parse a `data:[<mediatype>][;base64],<payload>` URL into raw bytes. */
92
+ private fun resolveDataURL(url: String): ByteArray {
93
+ val commaIdx = url.indexOf(',')
94
+ if (commaIdx < 0) throw ImageSourceError.MalformedDataURL(url)
95
+ // Skip the leading "data:" (5 chars) and isolate header / body.
96
+ val header = url.substring(5, commaIdx)
97
+ val body = url.substring(commaIdx + 1)
98
+ if (header.contains(";base64")) {
99
+ return try {
100
+ Base64.getDecoder().decode(body)
101
+ } catch (_: IllegalArgumentException) {
102
+ throw ImageSourceError.Base64DecodeFailed()
103
+ }
104
+ }
105
+ // Non-base64: payload is percent-encoded text per RFC 2397.
106
+ return URLDecoder.decode(body, Charsets.UTF_8.name()).toByteArray(Charsets.UTF_8)
107
+ }
108
+
109
+ private fun fetchHttp(url: String, client: OkHttpClient): ByteArray {
110
+ client.newCall(Request.Builder().url(url).build()).execute().use { resp ->
111
+ if (!resp.isSuccessful) throw ImageSourceError.HttpError(resp.code)
112
+ return resp.body?.bytes() ?: ByteArray(0)
113
+ }
114
+ }
115
+ }