react-native-hls-cache 0.1.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.
Files changed (52) hide show
  1. package/HlsCache.podspec +29 -0
  2. package/LICENSE +20 -0
  3. package/README.md +233 -0
  4. package/android/CMakeLists.txt +24 -0
  5. package/android/build.gradle +118 -0
  6. package/android/src/main/AndroidManifest.xml +2 -0
  7. package/android/src/main/cpp/cpp-adapter.cpp +6 -0
  8. package/android/src/main/java/com/margelo/nitro/hlscache/HlsCache.kt +32 -0
  9. package/android/src/main/java/com/margelo/nitro/hlscache/HlsCachePackage.kt +22 -0
  10. package/ios/ClientConnectionHandler.swift +234 -0
  11. package/ios/DataSource.swift +394 -0
  12. package/ios/HlsCache.swift +121 -0
  13. package/ios/NetworkDownloader.swift +220 -0
  14. package/ios/PrefetchManager.swift +235 -0
  15. package/ios/VideoCacheStorage.swift +235 -0
  16. package/ios/VideoProxyServer.swift +185 -0
  17. package/lib/module/HlsCache.nitro.js +4 -0
  18. package/lib/module/HlsCache.nitro.js.map +1 -0
  19. package/lib/module/index.js +71 -0
  20. package/lib/module/index.js.map +1 -0
  21. package/lib/module/package.json +1 -0
  22. package/lib/typescript/package.json +1 -0
  23. package/lib/typescript/src/HlsCache.nitro.d.ts +13 -0
  24. package/lib/typescript/src/HlsCache.nitro.d.ts.map +1 -0
  25. package/lib/typescript/src/index.d.ts +36 -0
  26. package/lib/typescript/src/index.d.ts.map +1 -0
  27. package/nitro.json +23 -0
  28. package/nitrogen/generated/android/c++/JHybridHlsCacheSpec.cpp +89 -0
  29. package/nitrogen/generated/android/c++/JHybridHlsCacheSpec.hpp +68 -0
  30. package/nitrogen/generated/android/hlscache+autolinking.cmake +81 -0
  31. package/nitrogen/generated/android/hlscache+autolinking.gradle +27 -0
  32. package/nitrogen/generated/android/hlscacheOnLoad.cpp +54 -0
  33. package/nitrogen/generated/android/hlscacheOnLoad.hpp +34 -0
  34. package/nitrogen/generated/android/kotlin/com/margelo/nitro/hlscache/HybridHlsCacheSpec.kt +75 -0
  35. package/nitrogen/generated/android/kotlin/com/margelo/nitro/hlscache/hlscacheOnLoad.kt +35 -0
  36. package/nitrogen/generated/ios/HlsCache+autolinking.rb +60 -0
  37. package/nitrogen/generated/ios/HlsCache-Swift-Cxx-Bridge.cpp +49 -0
  38. package/nitrogen/generated/ios/HlsCache-Swift-Cxx-Bridge.hpp +160 -0
  39. package/nitrogen/generated/ios/HlsCache-Swift-Cxx-Umbrella.hpp +46 -0
  40. package/nitrogen/generated/ios/HlsCacheAutolinking.mm +33 -0
  41. package/nitrogen/generated/ios/HlsCacheAutolinking.swift +26 -0
  42. package/nitrogen/generated/ios/c++/HybridHlsCacheSpecSwift.cpp +11 -0
  43. package/nitrogen/generated/ios/c++/HybridHlsCacheSpecSwift.hpp +118 -0
  44. package/nitrogen/generated/ios/swift/Func_void.swift +46 -0
  45. package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +46 -0
  46. package/nitrogen/generated/ios/swift/HybridHlsCacheSpec.swift +60 -0
  47. package/nitrogen/generated/ios/swift/HybridHlsCacheSpec_cxx.swift +237 -0
  48. package/nitrogen/generated/shared/c++/HybridHlsCacheSpec.cpp +26 -0
  49. package/nitrogen/generated/shared/c++/HybridHlsCacheSpec.hpp +69 -0
  50. package/package.json +174 -0
  51. package/src/HlsCache.nitro.ts +15 -0
  52. package/src/index.tsx +75 -0
@@ -0,0 +1,29 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "HlsCache"
7
+ s.version = package["version"]
8
+ s.summary = package["description"]
9
+ s.homepage = package["homepage"]
10
+ s.license = package["license"]
11
+ s.authors = package["author"]
12
+
13
+ s.platforms = { :ios => min_ios_version_supported }
14
+ s.source = { :git => "https://github.com/chanphiromsok/react-native-hls-cache.git", :tag => "#{s.version}" }
15
+
16
+ s.source_files = [
17
+ "ios/**/*.{swift}",
18
+ "ios/**/*.{m,mm}",
19
+ "cpp/**/*.{hpp,cpp}",
20
+ ]
21
+
22
+ s.dependency 'React-jsi'
23
+ s.dependency 'React-callinvoker'
24
+
25
+ load 'nitrogen/generated/ios/HlsCache+autolinking.rb'
26
+ add_nitrogen_files(s)
27
+
28
+ install_modules_dependencies(s)
29
+ end
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rom
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,233 @@
1
+ # react-native-hls-cache
2
+
3
+ HLS video caching for React Native — intercepts segment requests via a local TCP proxy, caches them to disk, and serves subsequent playback from cache.
4
+
5
+ - **iOS** — full proxy implementation (Swift, Network framework)
6
+ - **Android** — no-op; ExoPlayer/Media3 handle caching natively
7
+ - **Bridge** — [Nitro Modules](https://nitro.margelo.com/) (type-safe FFI)
8
+
9
+ ---
10
+
11
+ ## Installation
12
+
13
+ ```sh
14
+ npm install react-native-hls-cache react-native-nitro-modules
15
+ # or
16
+ yarn add react-native-hls-cache react-native-nitro-modules
17
+ ```
18
+
19
+ > `react-native-nitro-modules` is a required peer dependency.
20
+
21
+ ---
22
+
23
+ ## Quick Start
24
+
25
+ ```tsx
26
+ import { startServer, convertUrl } from 'react-native-hls-cache';
27
+ import { useVideoPlayer, VideoView } from 'expo-video';
28
+ import { useEffect } from 'react';
29
+
30
+ export default function App() {
31
+ useEffect(() => {
32
+ // Start the proxy once on app launch
33
+ startServer();
34
+ }, []);
35
+
36
+ const remoteUrl = 'https://stream.mux.com/abc123.m3u8';
37
+
38
+ const player = useVideoPlayer(
39
+ convertUrl(remoteUrl), // rewrites to http://127.0.0.1:9000/proxy?url=...
40
+ (p) => { p.loop = true; }
41
+ );
42
+
43
+ return <VideoView player={player} style={{ flex: 1 }} />;
44
+ }
45
+ ```
46
+
47
+ ---
48
+
49
+ ## API
50
+
51
+ ### `startServer(port?, maxCacheSize?, headOnlyCache?)`
52
+
53
+ Starts the local HLS proxy server. Call once on app mount.
54
+
55
+ | Parameter | Type | Default | Description |
56
+ |---|---|---|---|
57
+ | `port` | `number` | `9000` | Local TCP port to bind |
58
+ | `maxCacheSize` | `number` | `1073741824` | Max disk cache in bytes (1 GB) |
59
+ | `headOnlyCache` | `boolean` | `false` | Only cache the first 3 segments per stream. Recommended for vertical video feeds |
60
+
61
+ ```ts
62
+ startServer(); // defaults
63
+ startServer(9000, 512 * 1024 * 1024); // 512 MB cache
64
+ startServer(9000, undefined, true); // head-only mode for feeds
65
+ ```
66
+
67
+ - Synchronous and fast (< 1ms) — does not block the JS thread
68
+ - Safe to call multiple times; no-op if already running on the same port
69
+ - Throws with code `409` if a server is already running on a different port
70
+ - No-op on Android / Web
71
+
72
+ ---
73
+
74
+ ### `convertUrl(url, isCacheable?)`
75
+
76
+ Rewrites a remote HLS URL to route through the local proxy.
77
+
78
+ ```ts
79
+ const localUrl = convertUrl('https://cdn.example.com/video.m3u8');
80
+ // → 'http://127.0.0.1:9000/proxy?url=https%3A%2F%2Fcdn.example.com%2Fvideo.m3u8'
81
+ ```
82
+
83
+ | Parameter | Type | Default | Description |
84
+ |---|---|---|---|
85
+ | `url` | `string` | — | Remote HLS URL |
86
+ | `isCacheable` | `boolean` | `true` | Pass `false` to bypass the proxy and return the original URL |
87
+
88
+ - Returns the original URL unchanged on Android / Web, or if the server is not running
89
+ - Synchronous — safe to call inline during render
90
+
91
+ ---
92
+
93
+ ### `clearCache()`
94
+
95
+ Deletes all cached files from disk.
96
+
97
+ ```ts
98
+ await clearCache();
99
+ ```
100
+
101
+ - Runs on a background thread — does not block the JS thread
102
+ - No-op on Android / Web
103
+
104
+ ---
105
+
106
+ ### `prefetch(url, segmentCount?)`
107
+
108
+ Downloads an HLS stream into cache before the user plays it. Returns a `taskId` for cancellation.
109
+
110
+ ```ts
111
+ const taskId = prefetch('https://cdn.example.com/video.m3u8');
112
+ const taskId = prefetch('https://cdn.example.com/video.m3u8', 5); // cache 5 segments
113
+ ```
114
+
115
+ | Parameter | Type | Default | Description |
116
+ |---|---|---|---|
117
+ | `url` | `string` | — | Remote HLS URL |
118
+ | `segmentCount` | `number` | `3` | Number of segments to prefetch |
119
+
120
+ **What it does:**
121
+ 1. Downloads the master playlist
122
+ 2. Picks the lowest-bandwidth media playlist (lightweight for background work)
123
+ 3. Downloads the first `segmentCount` segments into the disk cache
124
+ 4. When the player requests those segments via the proxy → instant cache hit
125
+
126
+ - Returns immediately — all work happens in the background
127
+ - Returns `''` on Android / Web (no-op)
128
+
129
+ ---
130
+
131
+ ### `cancelPrefetch(taskId)`
132
+
133
+ Cancels a specific prefetch task.
134
+
135
+ ```ts
136
+ const taskId = prefetch(url);
137
+ // later...
138
+ cancelPrefetch(taskId);
139
+ ```
140
+
141
+ ---
142
+
143
+ ### `cancelAllPrefetch()`
144
+
145
+ Cancels all active prefetch tasks.
146
+
147
+ ```ts
148
+ cancelAllPrefetch();
149
+ ```
150
+
151
+ ---
152
+
153
+ ## Patterns
154
+
155
+ ### Vertical video feed (TikTok-style)
156
+
157
+ ```tsx
158
+ import { startServer, convertUrl, prefetch, cancelAllPrefetch } from 'react-native-hls-cache';
159
+
160
+ // App.tsx — start with head-only cache to minimise storage on feeds
161
+ useEffect(() => {
162
+ startServer(9000, 512 * 1024 * 1024, true);
163
+ return () => cancelAllPrefetch();
164
+ }, []);
165
+
166
+ // VideoItem.tsx — prefetch the next video as the user scrolls
167
+ useEffect(() => {
168
+ if (shouldPreload) {
169
+ const taskId = prefetch(videoUrl);
170
+ return () => cancelPrefetch(taskId);
171
+ }
172
+ }, [shouldPreload, videoUrl]);
173
+
174
+ const player = useVideoPlayer(convertUrl(videoUrl), (p) => {
175
+ p.loop = true;
176
+ });
177
+ ```
178
+
179
+ ### Selective caching
180
+
181
+ ```ts
182
+ // Skip cache for live streams or DRM content
183
+ const url = convertUrl(streamUrl, !isLive && !isDRM);
184
+ ```
185
+
186
+ ### Clear cache on logout
187
+
188
+ ```ts
189
+ async function onLogout() {
190
+ cancelAllPrefetch();
191
+ await clearCache();
192
+ }
193
+ ```
194
+
195
+ ---
196
+
197
+ ## How It Works
198
+
199
+ ```
200
+ Media Player
201
+ → HTTP request to localhost:9000/proxy?url=<encoded>
202
+ → VideoProxyServer (NWListener, TCP)
203
+ → ClientConnectionHandler (per-connection HTTP handler)
204
+ → DataSource (cache-first router)
205
+ ├── Cache hit → memory-mapped read from disk → instant response
206
+ └── Cache miss → NetworkDownloader (priority queue, 32 concurrent)
207
+ → stream to player + write to disk simultaneously
208
+ ```
209
+
210
+ **Cache storage** — files are keyed by SHA256 hash of the URL (+ byte range for fMP4 segments), stored in the system Caches directory under `ExpoVideoCache/`. LRU eviction runs 5 seconds after server start.
211
+
212
+ **Manifest rewriting** — `.m3u8` responses are intercepted and all segment URLs are rewritten to route through the proxy, so every subsequent segment request is also cacheable.
213
+
214
+ **Priority queue** — `.m3u8` manifests and small requests bypass the concurrency semaphore for instant playback startup. Heavy segment downloads are queued with a limit of 32 concurrent connections.
215
+
216
+ ---
217
+
218
+ ## Requirements
219
+
220
+ - React Native 0.73+
221
+ - iOS 15.1+
222
+ - Android — no native requirements (no-op)
223
+
224
+ ---
225
+
226
+ ## Contributing
227
+
228
+ - [Development workflow](CONTRIBUTING.md#development-workflow)
229
+ - [Sending a pull request](CONTRIBUTING.md#sending-a-pull-request)
230
+
231
+ ## License
232
+
233
+ MIT
@@ -0,0 +1,24 @@
1
+ project(hlscache)
2
+ cmake_minimum_required(VERSION 3.9.0)
3
+
4
+ set(PACKAGE_NAME hlscache)
5
+ set(CMAKE_VERBOSE_MAKEFILE ON)
6
+ set(CMAKE_CXX_STANDARD 20)
7
+
8
+ # Define C++ library and add all sources
9
+ add_library(${PACKAGE_NAME} SHARED src/main/cpp/cpp-adapter.cpp)
10
+
11
+ # Add Nitrogen specs :)
12
+ include(${CMAKE_SOURCE_DIR}/../nitrogen/generated/android/hlscache+autolinking.cmake)
13
+
14
+ # Set up local includes
15
+ include_directories("src/main/cpp" "../cpp")
16
+
17
+ find_library(LOG_LIB log)
18
+
19
+ # Link all libraries together
20
+ target_link_libraries(
21
+ ${PACKAGE_NAME}
22
+ ${LOG_LIB}
23
+ android # <-- Android core
24
+ )
@@ -0,0 +1,118 @@
1
+ buildscript {
2
+ ext.HlsCache = [
3
+ kotlinVersion: "2.0.21",
4
+ minSdkVersion: 24,
5
+ compileSdkVersion: 36,
6
+ targetSdkVersion: 36
7
+ ]
8
+
9
+ ext.getExtOrDefault = { prop ->
10
+ if (rootProject.ext.has(prop)) {
11
+ return rootProject.ext.get(prop)
12
+ }
13
+
14
+ return HlsCache[prop]
15
+ }
16
+
17
+ repositories {
18
+ google()
19
+ mavenCentral()
20
+ }
21
+
22
+ dependencies {
23
+ classpath "com.android.tools.build:gradle:8.7.2"
24
+ // noinspection DifferentKotlinGradleVersion
25
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${getExtOrDefault('kotlinVersion')}"
26
+ }
27
+ }
28
+
29
+ def reactNativeArchitectures() {
30
+ def value = rootProject.getProperties().get("reactNativeArchitectures")
31
+ return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
32
+ }
33
+
34
+ apply plugin: "com.android.library"
35
+ apply plugin: "kotlin-android"
36
+ apply from: '../nitrogen/generated/android/hlscache+autolinking.gradle'
37
+
38
+ apply plugin: "com.facebook.react"
39
+
40
+ android {
41
+ namespace "com.margelo.nitro.hlscache"
42
+
43
+ compileSdkVersion getExtOrDefault("compileSdkVersion")
44
+
45
+ defaultConfig {
46
+ minSdkVersion getExtOrDefault("minSdkVersion")
47
+ targetSdkVersion getExtOrDefault("targetSdkVersion")
48
+
49
+ externalNativeBuild {
50
+ cmake {
51
+ cppFlags "-frtti -fexceptions -Wall -fstack-protector-all"
52
+ arguments "-DANDROID_STL=c++_shared", "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON"
53
+ abiFilters (*reactNativeArchitectures())
54
+
55
+ buildTypes {
56
+ debug {
57
+ cppFlags "-O1 -g"
58
+ }
59
+ release {
60
+ cppFlags "-O2"
61
+ }
62
+ }
63
+ }
64
+ }
65
+ }
66
+
67
+ externalNativeBuild {
68
+ cmake {
69
+ path "CMakeLists.txt"
70
+ }
71
+ }
72
+
73
+ packagingOptions {
74
+ excludes = [
75
+ "META-INF",
76
+ "META-INF/**",
77
+ "**/libc++_shared.so",
78
+ "**/libfbjni.so",
79
+ "**/libjsi.so",
80
+ "**/libfolly_json.so",
81
+ "**/libfolly_runtime.so",
82
+ "**/libglog.so",
83
+ "**/libhermes.so",
84
+ "**/libhermes-executor-debug.so",
85
+ "**/libhermes_executor.so",
86
+ "**/libreactnative.so",
87
+ "**/libreactnativejni.so",
88
+ "**/libturbomodulejsijni.so",
89
+ "**/libreact_nativemodule_core.so",
90
+ "**/libjscexecutor.so"
91
+ ]
92
+ }
93
+
94
+ buildFeatures {
95
+ buildConfig true
96
+ prefab true
97
+ }
98
+
99
+ buildTypes {
100
+ release {
101
+ minifyEnabled false
102
+ }
103
+ }
104
+
105
+ lint {
106
+ disable "GradleCompatible"
107
+ }
108
+
109
+ compileOptions {
110
+ sourceCompatibility JavaVersion.VERSION_1_8
111
+ targetCompatibility JavaVersion.VERSION_1_8
112
+ }
113
+ }
114
+
115
+ dependencies {
116
+ implementation "com.facebook.react:react-android"
117
+ implementation project(":react-native-nitro-modules")
118
+ }
@@ -0,0 +1,2 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ </manifest>
@@ -0,0 +1,6 @@
1
+ #include <jni.h>
2
+ #include "hlscacheOnLoad.hpp"
3
+
4
+ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void*) {
5
+ return margelo::nitro::hlscache::initialize(vm);
6
+ }
@@ -0,0 +1,32 @@
1
+ package com.margelo.nitro.hlscache
2
+
3
+ import androidx.annotation.Keep
4
+ import com.facebook.proguard.annotations.DoNotStrip
5
+ import com.margelo.nitro.core.Promise
6
+
7
+ @DoNotStrip
8
+ @Keep
9
+ class HlsCache : HybridHlsCacheSpec() {
10
+
11
+ // Android uses ExoPlayer/Media3 native caching — no proxy needed.
12
+
13
+ override fun startServer(port: Double?, maxCacheSize: Double?, headOnlyCache: Boolean?): Unit {
14
+ // no-op: Android uses ExoPlayer/Media3 native caching
15
+ }
16
+
17
+ override fun convertUrl(url: String, isCacheable: Boolean?): String {
18
+ return url
19
+ }
20
+
21
+ override fun clearCache(): Promise<Unit> {
22
+ return Promise.resolved(Unit)
23
+ }
24
+
25
+ override fun prefetch(url: String, segmentCount: Double?): String {
26
+ return ""
27
+ }
28
+
29
+ override fun cancelPrefetch(taskId: String): Unit {}
30
+
31
+ override fun cancelAllPrefetch(): Unit {}
32
+ }
@@ -0,0 +1,22 @@
1
+ package com.margelo.nitro.hlscache
2
+
3
+ import com.facebook.react.BaseReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.module.model.ReactModuleInfoProvider
7
+
8
+ class HlsCachePackage : BaseReactPackage() {
9
+ override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? {
10
+ return null
11
+ }
12
+
13
+ override fun getReactModuleInfoProvider(): ReactModuleInfoProvider {
14
+ return ReactModuleInfoProvider { HashMap() }
15
+ }
16
+
17
+ companion object {
18
+ init {
19
+ System.loadLibrary("hlscache")
20
+ }
21
+ }
22
+ }