From 57a1654ca69c6506ba25edf2ce7f6bb62ebe3e02 Mon Sep 17 00:00:00 2001 From: lovegaoshi <106490582+lovegaoshi@users.noreply.github.com> Date: Thu, 1 Feb 2024 14:16:43 -0800 Subject: [PATCH 01/14] feat: android cache --- .../exoplayer/ReactExoplayerView.java | 32 ++++++++++++++++--- .../exoplayer/ReactExoplayerViewManager.java | 5 ++- examples/basic/src/VideoPlayer.tsx | 19 +++++++---- src/VideoNativeComponent.ts | 1 + 4 files changed, 45 insertions(+), 12 deletions(-) diff --git a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java index 55d7dd1acb..3c4a8f066f 100644 --- a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java +++ b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java @@ -16,6 +16,7 @@ import android.os.Looper; import android.os.Message; import android.text.TextUtils; +import android.util.Log; import android.view.View; import android.view.Window; import android.view.accessibility.CaptioningManager; @@ -42,6 +43,10 @@ import androidx.media3.common.TrackSelectionOverride; import androidx.media3.common.Tracks; import androidx.media3.common.util.Util; +import androidx.media3.database.StandaloneDatabaseProvider; +import androidx.media3.datasource.cache.CacheDataSource; +import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor; +import androidx.media3.datasource.cache.SimpleCache; import androidx.media3.datasource.DataSource; import androidx.media3.datasource.DataSpec; import androidx.media3.datasource.HttpDataSource; @@ -111,6 +116,7 @@ import com.google.ads.interactivemedia.v3.api.AdErrorEvent; import com.google.common.collect.ImmutableList; +import java.io.File; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookiePolicy; @@ -185,6 +191,7 @@ public class ReactExoplayerView extends FrameLayout implements private boolean isUsingContentResolution = false; private boolean selectTrackWhenReady = false; + private DataSource.Factory cacheDataSourceFactory; private int minBufferMs = DefaultLoadControl.DEFAULT_MIN_BUFFER_MS; private int maxBufferMs = DefaultLoadControl.DEFAULT_MAX_BUFFER_MS; private int bufferForPlaybackMs = DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_MS; @@ -634,8 +641,11 @@ private void initializePlayerCore(ReactExoplayerView self) { .setAdEventListener(this) .setAdErrorListener(this) .build(); - DefaultMediaSourceFactory mediaSourceFactory = new DefaultMediaSourceFactory(mediaDataSourceFactory); + if (cacheDataSourceFactory != null) { + mediaSourceFactory.setDataSourceFactory(cacheDataSourceFactory); + } + if (adsLoader != null) { mediaSourceFactory.setLocalAdInsertionComponents(unusedAdTagUri -> adsLoader, exoPlayerView); } @@ -830,9 +840,16 @@ private MediaSource buildMediaSource(Uri uri, String overrideExtension, DrmSessi ); break; case CONTENT_TYPE_OTHER: - mediaSourceFactory = new ProgressiveMediaSource.Factory( - mediaDataSourceFactory - ); + if (cacheDataSourceFactory == null) { + mediaSourceFactory = new ProgressiveMediaSource.Factory( + mediaDataSourceFactory + ); + } else { + mediaSourceFactory = new ProgressiveMediaSource.Factory( + cacheDataSourceFactory + ); + + } break; default: { throw new IllegalStateException("Unsupported type: " + type); @@ -2025,7 +2042,7 @@ public void setHideShutterView(boolean hideShutterView) { exoPlayerView.setHideShutterView(hideShutterView); } - public void setBufferConfig(int newMinBufferMs, int newMaxBufferMs, int newBufferForPlaybackMs, int newBufferForPlaybackAfterRebufferMs, double newMaxHeapAllocationPercent, double newMinBackBufferMemoryReservePercent, double newMinBufferMemoryReservePercent) { + public void setBufferConfig(int newMinBufferMs, int newMaxBufferMs, int newBufferForPlaybackMs, int newBufferForPlaybackAfterRebufferMs, double newMaxHeapAllocationPercent, double newMinBackBufferMemoryReservePercent, double newMinBufferMemoryReservePercent, int bufferSize) { minBufferMs = newMinBufferMs; maxBufferMs = newMaxBufferMs; bufferForPlaybackMs = newBufferForPlaybackMs; @@ -2033,6 +2050,11 @@ public void setBufferConfig(int newMinBufferMs, int newMaxBufferMs, int newBuffe maxHeapAllocationPercent = newMaxHeapAllocationPercent; minBackBufferMemoryReservePercent = newMinBackBufferMemoryReservePercent; minBufferMemoryReservePercent = newMinBufferMemoryReservePercent; + SimpleCache simpleCache = new SimpleCache(new File(this.getContext().getCacheDir(), "RNVCache"), new LeastRecentlyUsedCacheEvictor((long) bufferSize*1024*1024), new StandaloneDatabaseProvider(this.getContext())); + cacheDataSourceFactory = + new CacheDataSource.Factory() + .setCache(simpleCache) + .setUpstreamDataSourceFactory(buildHttpDataSourceFactory(false)); releasePlayer(); initializePlayer(); } diff --git a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerViewManager.java b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerViewManager.java index 8536bc2b5c..1099b8417f 100644 --- a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerViewManager.java +++ b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerViewManager.java @@ -61,6 +61,7 @@ public class ReactExoplayerViewManager extends ViewGroupManager { - this.channelUp(); + // this.channelUp(); }; toggleFullscreen() { @@ -759,10 +759,17 @@ class VideoPlayer extends Component { onAspectRatio={this.onAspectRatio} onReadyForDisplay={this.onReadyForDisplay} onBuffer={this.onVideoBuffer} - repeat={this.state.loop} + repeat selectedTextTrack={this.state.selectedTextTrack} selectedAudioTrack={this.state.selectedAudioTrack} playInBackground={false} + bufferConfig={{ + minBufferMs: 15000, + maxBufferMs: 50000, + bufferForPlaybackMs: 2500, + bufferForPlaybackAfterRebufferMs: 5000, + bufferSize: 200, + }} /> ); diff --git a/src/VideoNativeComponent.ts b/src/VideoNativeComponent.ts index 9692356129..90032917de 100644 --- a/src/VideoNativeComponent.ts +++ b/src/VideoNativeComponent.ts @@ -103,6 +103,7 @@ type BufferConfig = Readonly<{ maxHeapAllocationPercent?: number; minBackBufferMemoryReservePercent?: number; minBufferMemoryReservePercent?: number; + bufferSize?: number; }>; type SelectedVideoTrack = Readonly<{ From 09637b134e121b9ca3ffd78f2f5bc657319ed67a Mon Sep 17 00:00:00 2001 From: lovegaoshi <106490582+lovegaoshi@users.noreply.github.com> Date: Thu, 1 Feb 2024 14:20:20 -0800 Subject: [PATCH 02/14] docs: bufferSize --- docs/pages/component/props.md | 534 ++++++++++++++++++++-------------- src/types/video.ts | 1 + 2 files changed, 313 insertions(+), 222 deletions(-) diff --git a/docs/pages/component/props.md b/docs/pages/component/props.md index e4ecb97473..52db45cbf2 100644 --- a/docs/pages/component/props.md +++ b/docs/pages/component/props.md @@ -1,160 +1,179 @@ # Configurable props + This page shows the list of available properties to configure player ## List -| Name | Platforms Support | -|-------------------------------------------------------------------------------------|---------------------------| -| [adTagUrl](#adtagurl) | Android, iOS | -| [allowsExternalPlayback](#allowsexternalplayback) | iOS | -| [audioOnly](#audioonly) | All | -| [audioOutput](#audioOutput) | Android, iOS, visionOS | -| [automaticallyWaitsToMinimizeStalling](#automaticallywaitstominimizestalling) | iOS, visionOS | -| [backBufferDurationMs](#backbufferdurationms) | Android | -| [bufferConfig](#bufferconfig) | Android | -| [contentStartTime](#contentstarttime) | Android | -| [controls](#controls) | Android, iOS, visionOS | -| [currentPlaybackTime](#currentplaybacktime) | Android | -| [debug](#debug) | Android | -| [disableFocus](#disablefocus) | Android | -| [disableDisconnectError](#disabledisconnecterror) | Android | -| [filter](#filter) | iOS, visionOS | -| [filterEnabled](#filterenabled) | iOS, visionOS | -| [focusable](#focusable) | Android | -| [fullscreen](#fullscreen) | Android, iOS | -| [fullscreenAutorotate](#fullscreenautorotate) | iOS, visionOS | -| [fullscreenOrientation](#fullscreenorientation) | iOS, visionOS | -| [headers](#headers) | Android | -| [hideShutterView](#hideshutterview) | Android | -| [ignoreSilentSwitch](#ignoresilentswitch) | iOS, visionOS | -| [maxBitRate](#maxbitrate) | Android, iOS, visionOS | -| [minLoadRetryCount](#minloadretrycount) | Android | -| [mixWithOthers](#mixwithothers) | iOS, visionOS | -| [muted](#muted) | All | -| [paused](#paused) | All | -| [pictureInPicture](#pictureinpicture) | iOS | -| [playInBackground](#playinbackground) | Android, iOS, visionOS | -| [playWhenInactive](#playwheninactive) | iOS, visionOS | -| [poster](#poster) | All | -| [posterResizeMode](#posterresizemode) | All | -| [preferredForwardBufferDuration](#preferredforwardbufferduration) | iOS, visionOS | -| [preventsDisplaySleepDuringVideoPlayback](#preventsdisplaysleepduringvideoplayback) | iOS, Android | -| [progressUpdateInterval](#progressupdateinterval) | All | -| [rate](#rate) | All | -| [repeat](#repeat) | All | -| [reportBandwidth](#reportbandwidth) | Android | -| [resizeMode](#resizemode) | All | -| [selectedAudioTrack](#selectedaudiotrack) | Android, iOS, visionOS | -| [selectedTextTrack](#selectedtexttrack) | Android, iOS visionOS | -| [selectedVideoTrack](#selectedvideotrack) | Android | -| [shutterColor](#shutterColor) | Android | -| [source](#source) | All | -| [subtitleStyle](#subtitlestyle) | Android | -| [textTracks](#texttracks) | Android, iOS, visionOS | -| [trackId](#trackid) | Android | -| [useTextureView](#usetextureview) | Android | -| [useSecureView](#usesecureview) | Android | -| [volume](#volume) | All | -| [localSourceEncryptionKeyScheme](#localsourceencryptionkeyscheme) | All | +| Name | Platforms Support | +| ----------------------------------------------------------------------------------- | ---------------------- | +| [adTagUrl](#adtagurl) | Android, iOS | +| [allowsExternalPlayback](#allowsexternalplayback) | iOS | +| [audioOnly](#audioonly) | All | +| [audioOutput](#audioOutput) | Android, iOS, visionOS | +| [automaticallyWaitsToMinimizeStalling](#automaticallywaitstominimizestalling) | iOS, visionOS | +| [backBufferDurationMs](#backbufferdurationms) | Android | +| [bufferConfig](#bufferconfig) | Android | +| [contentStartTime](#contentstarttime) | Android | +| [controls](#controls) | Android, iOS, visionOS | +| [currentPlaybackTime](#currentplaybacktime) | Android | +| [debug](#debug) | Android | +| [disableFocus](#disablefocus) | Android | +| [disableDisconnectError](#disabledisconnecterror) | Android | +| [filter](#filter) | iOS, visionOS | +| [filterEnabled](#filterenabled) | iOS, visionOS | +| [focusable](#focusable) | Android | +| [fullscreen](#fullscreen) | Android, iOS | +| [fullscreenAutorotate](#fullscreenautorotate) | iOS, visionOS | +| [fullscreenOrientation](#fullscreenorientation) | iOS, visionOS | +| [headers](#headers) | Android | +| [hideShutterView](#hideshutterview) | Android | +| [ignoreSilentSwitch](#ignoresilentswitch) | iOS, visionOS | +| [maxBitRate](#maxbitrate) | Android, iOS, visionOS | +| [minLoadRetryCount](#minloadretrycount) | Android | +| [mixWithOthers](#mixwithothers) | iOS, visionOS | +| [muted](#muted) | All | +| [paused](#paused) | All | +| [pictureInPicture](#pictureinpicture) | iOS | +| [playInBackground](#playinbackground) | Android, iOS, visionOS | +| [playWhenInactive](#playwheninactive) | iOS, visionOS | +| [poster](#poster) | All | +| [posterResizeMode](#posterresizemode) | All | +| [preferredForwardBufferDuration](#preferredforwardbufferduration) | iOS, visionOS | +| [preventsDisplaySleepDuringVideoPlayback](#preventsdisplaysleepduringvideoplayback) | iOS, Android | +| [progressUpdateInterval](#progressupdateinterval) | All | +| [rate](#rate) | All | +| [repeat](#repeat) | All | +| [reportBandwidth](#reportbandwidth) | Android | +| [resizeMode](#resizemode) | All | +| [selectedAudioTrack](#selectedaudiotrack) | Android, iOS, visionOS | +| [selectedTextTrack](#selectedtexttrack) | Android, iOS visionOS | +| [selectedVideoTrack](#selectedvideotrack) | Android | +| [shutterColor](#shutterColor) | Android | +| [source](#source) | All | +| [subtitleStyle](#subtitlestyle) | Android | +| [textTracks](#texttracks) | Android, iOS, visionOS | +| [trackId](#trackid) | Android | +| [useTextureView](#usetextureview) | Android | +| [useSecureView](#usesecureview) | Android | +| [volume](#volume) | All | +| [localSourceEncryptionKeyScheme](#localsourceencryptionkeyscheme) | All | ## Details + ### `adTagUrl` + Sets the VAST uri to play AVOD ads. Example: + ``` adTagUrl="https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sample_ar%3Dpremidpostoptimizedpodbumper&ciu_szs=300x250&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&cmsid=496&vid=short_onecue&correlator=" ``` Note: You need enable IMA SDK in gradle or pod file - [enable client side ads insertion](/installation) - Platforms: Android, iOS ### `allowsExternalPlayback` + Indicates whether the player allows switching to external playback mode such as AirPlay or HDMI. -* **true (default)** - allow switching to external playback mode -* **false** - Don't allow switching to external playback mode + +- **true (default)** - allow switching to external playback mode +- **false** - Don't allow switching to external playback mode Platforms: iOS ### `audioOnly` + Indicates whether the player should only play the audio track and instead of displaying the video track, show the poster instead. -* **false (default)** - Display the video as normal -* **true** - Show the poster and play the audio + +- **false (default)** - Display the video as normal +- **true** - Show the poster and play the audio For this to work, the poster prop must be set. Platforms: all ### `audioOutput` + Changes the audio output. -* **speaker (default)** - plays through speaker -* **earpiece** - plays through earpiece + +- **speaker (default)** - plays through speaker +- **earpiece** - plays through earpiece Platforms: Android, iOS, visionOS ### `automaticallyWaitsToMinimizeStalling` + A Boolean value that indicates whether the player should automatically delay playback in order to minimize stalling. For clients linked against iOS 10.0 and later -* **false** - Immediately starts playback -* **true (default)** - Delays playback in order to minimize stalling + +- **false** - Immediately starts playback +- **true (default)** - Delays playback in order to minimize stalling Platforms: iOS, visionOS ### `backBufferDurationMs` + The number of milliseconds of buffer to keep before the current position. This allows rewinding without rebuffering within that duration. Platforms: Android ### `bufferConfig` + Adjust the buffer settings. This prop takes an object with one or more of the properties listed below. -Property | Type | Description ---- | --- | --- -minBufferMs | number | The default minimum duration of media that the player will attempt to ensure is buffered at all times, in milliseconds. -maxBufferMs | number | The default maximum duration of media that the player will attempt to buffer, in milliseconds. -bufferForPlaybackMs | number | The default duration of media that must be buffered for playback to start or resume following a user action such as a seek, in milliseconds. -bufferForPlaybackAfterRebufferMs | number | The default duration of media that must be buffered for playback to resume after a rebuffer, in milliseconds. A rebuffer is defined to be caused by buffer depletion rather than a user action. -maxHeapAllocationPercent | number | The percentage of available heap that the video can use to buffer, between 0 and 1 -minBackBufferMemoryReservePercent | number | The percentage of available app memory at which during startup the back buffer will be disabled, between 0 and 1 -minBufferMemoryReservePercent | number | The percentage of available app memory to keep in reserve that prevents buffer from using it, between 0 and 1 +| Property | Type | Description | +| --------------------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| bufferSize | number | The maximum cache size for Android to use as a cache folder, in MB. | +| minBufferMs | number | The default minimum duration of media that the player will attempt to ensure is buffered at all times, in milliseconds. | +| maxBufferMs | number | The default maximum duration of media that the player will attempt to buffer, in milliseconds. | +| bufferForPlaybackMs | number | The default duration of media that must be buffered for playback to start or resume following a user action such as a seek, in milliseconds. | +| bufferForPlaybackAfterRebufferMs | number | The default duration of media that must be buffered for playback to resume after a rebuffer, in milliseconds. A rebuffer is defined to be caused by buffer depletion rather than a user action. | +| maxHeapAllocationPercent | number | The percentage of available heap that the video can use to buffer, between 0 and 1 | +| minBackBufferMemoryReservePercent | number | The percentage of available app memory at which during startup the back buffer will be disabled, between 0 and 1 | +| minBufferMemoryReservePercent | number | The percentage of available app memory to keep in reserve that prevents buffer from using it, between 0 and 1 | This prop should only be set when you are setting the source, changing it after the media is loaded will cause it to be reloaded. Example with default values: + ```javascript bufferConfig={{ minBufferMs: 15000, maxBufferMs: 50000, bufferForPlaybackMs: 2500, - bufferForPlaybackAfterRebufferMs: 5000 + bufferForPlaybackAfterRebufferMs: 5000, + bufferSize: 0 }} ``` Platforms: Android ### `chapters` + To provide a custom chapter source for tvOS. This prop takes an array of objects with the properties listed below. | Property | Type | Description | -|-----------|---------|-----------------------------------------------------------------------------------------------------------------------------------------------------------| +| --------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | title | string | The title of the chapter to create | | startTime | number | The start time of the chapter in seconds | | endTime | number | The end time of the chapter in seconds | | uri | string? | Optional: Provide an http orl or the some base64 string to override the image of the chapter. For some media files the images are generated automatically | - Platforms: tvOS ### `currentPlaybackTime` + When playing an HLS live stream with a `EXT-X-PROGRAM-DATE-TIME` tag configured, then this property will contain the epoch value in msec. Platforms: Android, iOS ### `controls` + Determines whether to show player controls. -* **false (default)** - Don't show player controls -* **true** - Show player controls + +- **false (default)** - Don't show player controls +- **true** - Show player controls Note on iOS, controls are always shown when in fullscreen mode. Note on Android, native controls are available by default. @@ -163,6 +182,7 @@ If needed, you can also add your controls or use a package like [react-native-vi Platforms: Android, iOS, visionOS ### `contentStartTime` + The start time in ms for SSAI content. This determines at what time to load the video info like resolutions. Use this only when you have SSAI stream where ads resolution is not the same as content resolution. Platforms: Android @@ -174,66 +194,75 @@ Enable more verbosity in logs. > [!WARNING] > Do not use this open in production build -| Property | Type | Description | -| ------------------ | ------ | ------------------------------------------------------------------------------------------- | -| `enable` | boolean | when true, display logs with verbosity higher | -| `thread` | boolean | enable thread display | - +| Property | Type | Description | +| -------- | ------- | --------------------------------------------- | +| `enable` | boolean | when true, display logs with verbosity higher | +| `thread` | boolean | enable thread display | Example with default values: + ```javascript debug={{ enable: true, thread: true, }} ``` -Platforms: Android +Platforms: Android ### `disableFocus` + Determines whether video audio should override background music/audio in Android devices. -* **false (default)** - Override background audio/music -* **true** - Let background audio/music from other apps play - + +- **false (default)** - Override background audio/music +- **true** - Let background audio/music from other apps play + Note: Allows multiple videos to play if set to `true`. If `false`, when one video is playing and another is started, the first video will be paused. - + Platforms: Android ### `disableDisconnectError` + Determines if the player needs to throw an error when connection is lost or not -* **false (default)** - Player will throw an error when connection is lost -* **true** - Player will keep trying to buffer when network connect is lost + +- **false (default)** - Player will throw an error when connection is lost +- **true** - Player will keep trying to buffer when network connect is lost Platforms: Android ### `DRM` + To setup DRM please follow [this guide](/component/drm) Platforms: Android, iOS + > ⚠️ DRM is not supported on visionOS yet ### `filter` + Add video filter -* **FilterType.NONE (default)** - No Filter -* **FilterType.INVERT** - CIColorInvert -* **FilterType.MONOCHROME** - CIColorMonochrome -* **FilterType.POSTERIZE** - CIColorPosterize -* **FilterType.FALSE** - CIFalseColor -* **FilterType.MAXIMUMCOMPONENT** - CIMaximumComponent -* **FilterType.MINIMUMCOMPONENT** - CIMinimumComponent -* **FilterType.CHROME** - CIPhotoEffectChrome -* **FilterType.FADE** - CIPhotoEffectFade -* **FilterType.INSTANT** - CIPhotoEffectInstant -* **FilterType.MONO** - CIPhotoEffectMono -* **FilterType.NOIR** - CIPhotoEffectNoir -* **FilterType.PROCESS** - CIPhotoEffectProcess -* **FilterType.TONAL** - CIPhotoEffectTonal -* **FilterType.TRANSFER** - CIPhotoEffectTransfer -* **FilterType.SEPIA** - CISepiaTone + +- **FilterType.NONE (default)** - No Filter +- **FilterType.INVERT** - CIColorInvert +- **FilterType.MONOCHROME** - CIColorMonochrome +- **FilterType.POSTERIZE** - CIColorPosterize +- **FilterType.FALSE** - CIFalseColor +- **FilterType.MAXIMUMCOMPONENT** - CIMaximumComponent +- **FilterType.MINIMUMCOMPONENT** - CIMinimumComponent +- **FilterType.CHROME** - CIPhotoEffectChrome +- **FilterType.FADE** - CIPhotoEffectFade +- **FilterType.INSTANT** - CIPhotoEffectInstant +- **FilterType.MONO** - CIPhotoEffectMono +- **FilterType.NOIR** - CIPhotoEffectNoir +- **FilterType.PROCESS** - CIPhotoEffectProcess +- **FilterType.TONAL** - CIPhotoEffectTonal +- **FilterType.TRANSFER** - CIPhotoEffectTransfer +- **FilterType.SEPIA** - CISepiaTone For more details on these filters refer to the [iOS docs](https://developer.apple.com/library/archive/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/uid/TP30000136-SW55). -Notes: +Notes: + 1. Using a filter can impact CPU usage. A workaround is to save the video with the filter and then load the saved video. 2. Video filter is currently not supported on HLS playlists. 3. `filterEnabled` must be set to `true` @@ -241,47 +270,53 @@ Notes: Platforms: iOS, visionOS ### `filterEnabled` -Enable video filter. -* **false (default)** - Don't enable filter -* **true** - Enable filter +Enable video filter. + +- **false (default)** - Don't enable filter +- **true** - Enable filter Platforms: iOS, visionOS ### `Focusable` + Whether this video view should be focusable with a non-touch input device, eg. receive focus with a hardware keyboard. -* **false** - Makes view unfocusable -* **true (default)** - Makes view focusable - -Platforms: Android +- **false** - Makes view unfocusable +- **true (default)** - Makes view focusable + +Platforms: Android ### `fullscreen` + Controls whether the player enters fullscreen on play. See [presentFullscreenPlayer](#presentfullscreenplayer) for details. -* **false (default)** - Don't display the video in fullscreen -* **true** - Display the video in fullscreen +- **false (default)** - Don't display the video in fullscreen +- **true** - Display the video in fullscreen Platforms: iOS, Android, visionOS ### `fullscreenAutorotate` + If a preferred [fullscreenOrientation](#fullscreenorientation) is set, causes the video to rotate to that orientation but permits rotation of the screen to orientation held by user. Defaults to TRUE. Platforms: iOS, visionOS ### `fullscreenOrientation` -* **all (default)** - -* **landscape** -* **portrait** +- **all (default)** - +- **landscape** +- **portrait** Platforms: iOS, visionOS ### `headers` + Pass headers to the HTTP client. Can be used for authorization. Headers must be a part of the source object. Example: + ```javascript source={{ uri: "https://www.example.com/video.mp4", @@ -295,27 +330,32 @@ source={{ Platforms: Android ### `hideShutterView` + Controls whether the ExoPlayer shutter view (black screen while loading) is enabled. -* **false (default)** - Show shutter view -* **true** - Hide shutter view +- **false (default)** - Show shutter view +- **true** - Hide shutter view Platforms: Android ### `ignoreSilentSwitch` + Controls the iOS silent switch behavior -* **"inherit" (default)** - Use the default AVPlayer behavior -* **"ignore"** - Play audio even if the silent switch is set -* **"obey"** - Don't play audio if the silent switch is set + +- **"inherit" (default)** - Use the default AVPlayer behavior +- **"ignore"** - Play audio even if the silent switch is set +- **"obey"** - Don't play audio if the silent switch is set Platforms: iOS, visionOS ### `maxBitRate` + Sets the desired limit, in bits per second, of network bandwidth consumption when multiple video streams are available for a playlist. Default: 0. Don't limit the maxBitRate. Example: + ```javascript maxBitRate={2000000} // 2 megabits ``` @@ -323,11 +363,13 @@ maxBitRate={2000000} // 2 megabits Platforms: Android, iOS, visionOS ### `minLoadRetryCount` + Sets the minimum number of times to retry loading data before failing and reporting an error to the application. Useful to recover from transient internet failures. Default: 3. Retry 3 times. Example: + ```javascript minLoadRetryCount={5} // retry 5 times ``` @@ -335,72 +377,89 @@ minLoadRetryCount={5} // retry 5 times Platforms: Android ### `mixWithOthers` + Controls how Audio mix with other apps. -* **"inherit" (default)** - Use the default AVPlayer behavior -* **"mix"** - Audio from this video mixes with audio from other apps. -* **"duck"** - Reduces the volume of other apps while audio from this video plays. + +- **"inherit" (default)** - Use the default AVPlayer behavior +- **"mix"** - Audio from this video mixes with audio from other apps. +- **"duck"** - Reduces the volume of other apps while audio from this video plays. Platforms: iOS, visionOS ### `muted` + Controls whether the audio is muted -* **false (default)** - Don't mute audio -* **true** - Mute audio + +- **false (default)** - Don't mute audio +- **true** - Mute audio Platforms: all ### `paused` + Controls whether the media is paused -* **false (default)** - Don't pause the media -* **true** - Pause the media + +- **false (default)** - Don't pause the media +- **true** - Pause the media Platforms: all ### `pictureInPicture` + Determine whether the media should played as picture in picture. -* **false (default)** - Don't not play as picture in picture -* **true** - Play the media as picture in picture -NOTE: Video ads cannot start when you are using the PIP on iOS (more info available at [Google IMA SDK Docs](https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/picture_in_picture?hl=en#starting_ads)). If you are using custom controls, you must hide your PIP button when you receive the ```STARTED``` event from ```onReceiveAdEvent``` and show it again when you receive the ```ALL_ADS_COMPLETED``` event. +- **false (default)** - Don't not play as picture in picture +- **true** - Play the media as picture in picture + +NOTE: Video ads cannot start when you are using the PIP on iOS (more info available at [Google IMA SDK Docs](https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/picture_in_picture?hl=en#starting_ads)). If you are using custom controls, you must hide your PIP button when you receive the `STARTED` event from `onReceiveAdEvent` and show it again when you receive the `ALL_ADS_COMPLETED` event. Platforms: iOS ### `playInBackground` + Determine whether the media should continue playing while the app is in the background. This allows customers to continue listening to the audio. -* **false (default)** - Don't continue playing the media -* **true** - Continue playing the media + +- **false (default)** - Don't continue playing the media +- **true** - Continue playing the media To use this feature on iOS, you must: -* [Enable Background Audio](https://developer.apple.com/library/archive/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/AudioSessionBasics/AudioSessionBasics.html#//apple_ref/doc/uid/TP40007875-CH3-SW3) in your Xcode project -* Set the ignoreSilentSwitch prop to "ignore" + +- [Enable Background Audio](https://developer.apple.com/library/archive/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/AudioSessionBasics/AudioSessionBasics.html#//apple_ref/doc/uid/TP40007875-CH3-SW3) in your Xcode project +- Set the ignoreSilentSwitch prop to "ignore" Platforms: Android, iOS, visionOS ### `playWhenInactive` + Determine whether the media should continue playing when notifications or the Control Center are in front of the video. -* **false (default)** - Don't continue playing the media -* **true** - Continue playing the media + +- **false (default)** - Don't continue playing the media +- **true** - Continue playing the media Platforms: iOS, visionOS ### `poster` + An image to display while the video is loading
Value: string with a URL for the poster, e.g. "https://baconmockup.com/300/200/" Platforms: all ### `posterResizeMode` + Determines how to resize the poster image when the frame doesn't match the raw video dimensions. -* **"contain" (default)** - Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding). -* **"center"** - Center the image in the view along both dimensions. If the image is larger than the view, scale it down uniformly so that it is contained in the view. -* **"cover"** - Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). -* **"none"** - Don't apply resize -* **"repeat"** - Repeat the image to cover the frame of the view. The image will keep its size and aspect ratio. (iOS only) -* **"stretch"** - Scale width and height independently, This may change the aspect ratio of the src. + +- **"contain" (default)** - Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding). +- **"center"** - Center the image in the view along both dimensions. If the image is larger than the view, scale it down uniformly so that it is contained in the view. +- **"cover"** - Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). +- **"none"** - Don't apply resize +- **"repeat"** - Repeat the image to cover the frame of the view. The image will keep its size and aspect ratio. (iOS only) +- **"stretch"** - Scale width and height independently, This may change the aspect ratio of the src. Platforms: all ### `preferredForwardBufferDuration` + The duration the player should buffer media from the network ahead of the playhead to guard against playback disruption. Sets the [preferredForwardBufferDuration](https://developer.apple.com/documentation/avfoundation/avplayeritem/1643630-preferredforwardbufferduration) instance property on AVPlayerItem. Default: 0 @@ -408,6 +467,7 @@ Default: 0 Platforms: iOS, visionOS ### `preventsDisplaySleepDuringVideoPlayback` + Controls whether or not the display should be allowed to sleep while playing the video. Default is not to allow display to sleep. Default: true @@ -415,6 +475,7 @@ Default: true Platforms: iOS, Android ### `progressUpdateInterval` + Delay in milliseconds between onProgress events in milliseconds. Default: 250.0 @@ -422,36 +483,41 @@ Default: 250.0 Platforms: all ### `rate` -Speed at which the media should play. -* **0.0** - Pauses the video -* **1.0** - Play at normal speed -* **Other values** - Slow down or speed up playback + +Speed at which the media should play. + +- **0.0** - Pauses the video +- **1.0** - Play at normal speed +- **Other values** - Slow down or speed up playback Platforms: all ### `repeat` + Determine whether to repeat the video when the end is reached -* **false (default)** - Don't repeat the video -* **true** - Repeat the video -Platforms: all +- **false (default)** - Don't repeat the video +- **true** - Repeat the video +Platforms: all ### `onAudioTracks` + Callback function that is called when audio tracks change Payload: -Property | Type | Description ---- | --- | --- -index | number | Internal track ID -title | string | Descriptive name for the track -language | string | 2 letter [ISO 639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) representing the language -bitrate | number | bitrate of track -type | string | Mime type of track -selected | boolean | true if track is playing +| Property | Type | Description | +| -------- | ------- | ---------------------------------------------------------------------------------------------------------- | +| index | number | Internal track ID | +| title | string | Descriptive name for the track | +| language | string | 2 letter [ISO 639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) representing the language | +| bitrate | number | bitrate of track | +| type | string | Mime type of track | +| selected | boolean | true if track is playing | Example: + ```javascript { audioTracks: [ @@ -461,27 +527,30 @@ Example: } ``` - Platforms: Android ### `reportBandwidth` + Determine whether to generate onBandwidthUpdate events. This is needed due to the high frequency of these events on ExoPlayer. -* **false (default)** - Don't generate onBandwidthUpdate events -* **true** - Generate onBandwidthUpdate events +- **false (default)** - Don't generate onBandwidthUpdate events +- **true** - Generate onBandwidthUpdate events Platforms: Android ### `resizeMode` + Determines how to resize the video when the frame doesn't match the raw video dimensions. -* **"none" (default)** - Don't apply resize -* **"contain"** - Scale the video uniformly (maintain the video's aspect ratio) so that both dimensions (width and height) of the video will be equal to or less than the corresponding dimension of the view (minus padding). -* **"cover"** - Scale the video uniformly (maintain the video's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). -* **"stretch"** - Scale width and height independently, This may change the aspect ratio of the src. + +- **"none" (default)** - Don't apply resize +- **"contain"** - Scale the video uniformly (maintain the video's aspect ratio) so that both dimensions (width and height) of the video will be equal to or less than the corresponding dimension of the view (minus padding). +- **"cover"** - Scale the video uniformly (maintain the video's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). +- **"stretch"** - Scale width and height independently, This may change the aspect ratio of the src. Platforms: Android, iOS, Windows UWP ### `selectedAudioTrack` + Configure which audio track, if any, is played. ```javascript @@ -492,6 +561,7 @@ selectedAudioTrack={{ ``` Example: + ```javascript selectedAudioTrack={{ type: "title", @@ -499,19 +569,20 @@ selectedAudioTrack={{ }} ``` -Type | Value | Description ---- | --- | --- -"system" (default) | N/A | Play the audio track that matches the system language. If none match, play the first track. -"disabled" | N/A | Turn off audio -"title" | string | Play the audio track with the title specified as the Value, e.g. "French" -"language" | string | Play the audio track with the language specified as the Value, e.g. "fr" -"index" | number | Play the audio track with the index specified as the value, e.g. 0 +| Type | Value | Description | +| ------------------ | ------ | ------------------------------------------------------------------------------------------- | +| "system" (default) | N/A | Play the audio track that matches the system language. If none match, play the first track. | +| "disabled" | N/A | Turn off audio | +| "title" | string | Play the audio track with the title specified as the Value, e.g. "French" | +| "language" | string | Play the audio track with the language specified as the Value, e.g. "fr" | +| "index" | number | Play the audio track with the index specified as the value, e.g. 0 | If a track matching the specified Type (and Value if appropriate) is unavailable, the first audio track will be played. If multiple tracks match the criteria, the first match will be used. Platforms: Android, iOS, visionOS ### `selectedTextTrack` + Configure which text track (caption or subtitle), if any, is shown. ```javascript @@ -522,6 +593,7 @@ selectedTextTrack={{ ``` Example: + ```javascript selectedTextTrack={{ type: "title", @@ -529,21 +601,22 @@ selectedTextTrack={{ }} ``` -Type | Value | Description ---- | --- | --- -"system" (default) | N/A | Display captions only if the system preference for captions is enabled -"disabled" | N/A | Don't display a text track -"title" | string | Display the text track with the title specified as the Value, e.g. "French 1" -"language" | string | Display the text track with the language specified as the Value, e.g. "fr" -"index" | number | Display the text track with the index specified as the value, e.g. 0 +| Type | Value | Description | +| ------------------ | ------ | ----------------------------------------------------------------------------- | +| "system" (default) | N/A | Display captions only if the system preference for captions is enabled | +| "disabled" | N/A | Don't display a text track | +| "title" | string | Display the text track with the title specified as the Value, e.g. "French 1" | +| "language" | string | Display the text track with the language specified as the Value, e.g. "fr" | +| "index" | number | Display the text track with the index specified as the value, e.g. 0 | -Both iOS & Android (only 4.4 and higher) offer Settings to enable Captions for hearing impaired people. If "system" is selected and the Captions Setting is enabled, iOS/Android will look for a caption that matches that customer's language and display it. +Both iOS & Android (only 4.4 and higher) offer Settings to enable Captions for hearing impaired people. If "system" is selected and the Captions Setting is enabled, iOS/Android will look for a caption that matches that customer's language and display it. If a track matching the specified Type (and Value if appropriate) is unavailable, no text track will be displayed. If multiple tracks match the criteria, the first match will be used. Platforms: Android, iOS, visionOS ### `selectedVideoTrack` + Configure which video track should be played. By default, the player uses Adaptive Bitrate Streaming to automatically select the stream it thinks will perform best based on available bandwidth. ```javascript @@ -554,6 +627,7 @@ selectedVideoTrack={{ ``` Example: + ```javascript selectedVideoTrack={{ type: "resolution", @@ -561,22 +635,23 @@ selectedVideoTrack={{ }} ``` -Type | Value | Description ---- | --- | --- -"auto" (default) | N/A | Let the player determine which track to play using ABR -"disabled" | N/A | Turn off video -"resolution" | number | Play the video track with the height specified, e.g. 480 for the 480p stream -"index" | number | Play the video track with the index specified as the value, e.g. 0 +| Type | Value | Description | +| ---------------- | ------ | ---------------------------------------------------------------------------- | +| "auto" (default) | N/A | Let the player determine which track to play using ABR | +| "disabled" | N/A | Turn off video | +| "resolution" | number | Play the video track with the height specified, e.g. 480 for the 480p stream | +| "index" | number | Play the video track with the index specified as the value, e.g. 0 | If a track matching the specified Type (and Value if appropriate) is unavailable, ABR will be used. Platforms: Android ### `shutterColor` -Apply color to shutter view, if you see black flashes before video start then set + +Apply color to shutter view, if you see black flashes before video start then set ```javascript -shutterColor='transparent' +shutterColor = 'transparent'; ``` - black (default) @@ -584,6 +659,7 @@ shutterColor='transparent' Platforms: Android ### `source` + Sets the media source. You can pass an asset loaded via require or an object with a uri. Setting the source will trigger the player to attempt to load the provided media with all other given props. Please be sure that all props are provided before/at the same time as setting the source. @@ -594,16 +670,16 @@ Providing a null source value after loading a previous source will stop playback The docs for this prop are incomplete and will be updated as each option is investigated and tested. - #### Asset loaded via require > ⚠️ on iOS, you file name must not contain spaces eg. `my video.mp4` will not work, use `my-video.mp4` instead -Example: +Example: + ```javascript const sintel = require('./sintel.mp4'); -source={sintel} +source = {sintel}; ``` #### URI string @@ -616,6 +692,7 @@ For exemple 'www.myurl.com/blabla?q=test uri' is invalid, where 'www.myurl.com/b ##### Web address (http://, https://) Example: + ```javascript source={{uri: 'https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_10mb.mp4' }} ``` @@ -625,6 +702,7 @@ Platforms: all ##### File path (file://) Example: + ```javascript source={{ uri: 'file:///sdcard/Movies/sintel.mp4' }} ``` @@ -638,6 +716,7 @@ Platforms: Android, possibly others Path to a sound file in your iTunes library. Typically shared from iTunes to your app. Example: + ```javascript source={{ uri: 'ipod-library:///path/to/music.mp3' }} ``` @@ -652,6 +731,7 @@ Provide a member `type` with value (`mpd`/`m3u8`/`ism`) inside the source object Sometimes is needed when URL extension does not match with the mimetype that you are expecting, as seen on the next example. (Extension is .ism -smooth streaming- but file served is on format mpd -mpeg dash-) Example: + ```javascript source={{ uri: 'http://host-serving-a-type-different-than-the-extension.ism/manifest(format=mpd-time-csf)', type: 'mpd' }} @@ -674,6 +754,7 @@ Platforms: Android, iOS Provide an optional `cropStart` and/or `cropEnd` for the video. Value is in milliseconds. Useful when you want to play only a portion of a large video. Example + ```javascript source={{ uri: 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8', cropStart: 36012, cropEnd: 48500 }} @@ -686,16 +767,16 @@ Platforms: iOS, Android #### Overriding the metadata of a source -Provide an optional `title`, `subtitle`, `customImageUri` and/or `description` properties for the video. +Provide an optional `title`, `subtitle`, `customImageUri` and/or `description` properties for the video. Useful when to adapt the tvOS playback experience. Example: ```javascript -source={{ - uri: 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8', - title: 'Custom Title', - subtitle: 'Custom Subtitle', +source={{ + uri: 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8', + title: 'Custom Title', + subtitle: 'Custom Subtitle', description: 'Custom Description', customImageUri: 'https://pbs.twimg.com/profile_images/1498641868397191170/6qW2XkuI_400x400.png' }} @@ -705,14 +786,13 @@ Platforms: tvOS ### `subtitleStyle` -Property | Description | Platforms ---- | --- | --- -fontSize | Adjust the font size of the subtitles. Default: font size of the device | Android -paddingTop | Adjust the top padding of the subtitles. Default: 0| Android -paddingBottom | Adjust the bottom padding of the subtitles. Default: 0| Android -paddingLeft | Adjust the left padding of the subtitles. Default: 0| Android -paddingRight | Adjust the right padding of the subtitles. Default: 0| Android - +| Property | Description | Platforms | +| ------------- | ----------------------------------------------------------------------- | --------- | +| fontSize | Adjust the font size of the subtitles. Default: font size of the device | Android | +| paddingTop | Adjust the top padding of the subtitles. Default: 0 | Android | +| paddingBottom | Adjust the bottom padding of the subtitles. Default: 0 | Android | +| paddingLeft | Adjust the left padding of the subtitles. Default: 0 | Android | +| paddingRight | Adjust the right padding of the subtitles. Default: 0 | Android | Example: @@ -721,21 +801,24 @@ subtitleStyle={{ paddingBottom: 50, fontSize: 20 }} ``` ### `textTracks` + Load one or more "sidecar" text tracks. This takes an array of objects representing each track. Each object should have the format: + > ⚠️ This feature does not work with HLS playlists (e.g m3u8) on iOS -Property | Description ---- | --- -title | Descriptive name for the track -language | 2 letter [ISO 639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) representing the language -type | Mime type of the track
* TextTrackType.SRT - SubRip (.srt)
* TextTrackType.TTML - TTML (.ttml)
* TextTrackType.VTT - WebVTT (.vtt)
iOS only supports VTT, Android supports all 3 -uri | URL for the text track. Currently, only tracks hosted on a webserver are supported +| Property | Description | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| title | Descriptive name for the track | +| language | 2 letter [ISO 639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) representing the language | +| type | Mime type of the track
_ TextTrackType.SRT - SubRip (.srt)
_ TextTrackType.TTML - TTML (.ttml)
\* TextTrackType.VTT - WebVTT (.vtt)
iOS only supports VTT, Android supports all 3 | +| uri | URL for the text track. Currently, only tracks hosted on a webserver are supported | On iOS, sidecar text tracks are only supported for individual files, not HLS playlists. For HLS, you should include the text tracks as part of the playlist. Note: Due to iOS limitations, sidecar text tracks are not compatible with Airplay. If textTracks are specified, AirPlay support will be automatically disabled. Example: + ```javascript import { TextTrackType }, Video from 'react-native-video'; @@ -755,56 +838,63 @@ textTracks={[ ]} ``` - Platforms: Android, iOS, visionOS ### `trackId` + Configure an identifier for the video stream to link the playback context to the events emitted. Platforms: Android ### `useTextureView` + Controls whether to output to a TextureView or SurfaceView. SurfaceView is more efficient and provides better performance but has two limitations: -* It can't be animated, transformed or scaled -* You can't overlay multiple SurfaceViews + +- It can't be animated, transformed or scaled +- You can't overlay multiple SurfaceViews useTextureView can only be set at same time you're setting the source. -* **true (default)** - Use a TextureView -* **false** - Use a SurfaceView +- **true (default)** - Use a TextureView +- **false** - Use a SurfaceView Platforms: Android ### `useSecureView` + Force the output to a SurfaceView and enables the secure surface. This will override useTextureView flag. SurfaceView is is the only one that can be labeled as secure. -* **true** - Use security -* **false (default)** - Do not use security +- **true** - Use security +- **false (default)** - Do not use security Platforms: Android ### `volume` + Adjust the volume. -* **1.0 (default)** - Play at full volume -* **0.0** - Mute the audio -* **Other values** - Reduce volume + +- **1.0 (default)** - Play at full volume +- **0.0** - Mute the audio +- **Other values** - Reduce volume Platforms: all ### `localSourceEncryptionKeyScheme` + Set the url scheme for stream encryption key for local assets Type: String Example: + ``` localSourceEncryptionKeyScheme="my-offline-key" ``` -Platforms: iOS \ No newline at end of file +Platforms: iOS diff --git a/src/types/video.ts b/src/types/video.ts index 415c69c530..3c9f400478 100644 --- a/src/types/video.ts +++ b/src/types/video.ts @@ -68,6 +68,7 @@ export type BufferConfig = { maxHeapAllocationPercent?: number; minBackBufferMemoryReservePercent?: number; minBufferMemoryReservePercent?: number; + bufferSize?: number; }; export enum SelectedTrackType { From 1734794157e01c9be9851e4c67b2a2bdfdcb8344 Mon Sep 17 00:00:00 2001 From: lovegaoshi <106490582+lovegaoshi@users.noreply.github.com> Date: Mon, 5 Feb 2024 12:12:01 -0800 Subject: [PATCH 03/14] Revert "docs: bufferSize" This reverts commit 09637b134e121b9ca3ffd78f2f5bc657319ed67a. --- docs/pages/component/props.md | 534 ++++++++++++++-------------------- src/types/video.ts | 1 - 2 files changed, 222 insertions(+), 313 deletions(-) diff --git a/docs/pages/component/props.md b/docs/pages/component/props.md index 52db45cbf2..e4ecb97473 100644 --- a/docs/pages/component/props.md +++ b/docs/pages/component/props.md @@ -1,179 +1,160 @@ # Configurable props - This page shows the list of available properties to configure player ## List -| Name | Platforms Support | -| ----------------------------------------------------------------------------------- | ---------------------- | -| [adTagUrl](#adtagurl) | Android, iOS | -| [allowsExternalPlayback](#allowsexternalplayback) | iOS | -| [audioOnly](#audioonly) | All | -| [audioOutput](#audioOutput) | Android, iOS, visionOS | -| [automaticallyWaitsToMinimizeStalling](#automaticallywaitstominimizestalling) | iOS, visionOS | -| [backBufferDurationMs](#backbufferdurationms) | Android | -| [bufferConfig](#bufferconfig) | Android | -| [contentStartTime](#contentstarttime) | Android | -| [controls](#controls) | Android, iOS, visionOS | -| [currentPlaybackTime](#currentplaybacktime) | Android | -| [debug](#debug) | Android | -| [disableFocus](#disablefocus) | Android | -| [disableDisconnectError](#disabledisconnecterror) | Android | -| [filter](#filter) | iOS, visionOS | -| [filterEnabled](#filterenabled) | iOS, visionOS | -| [focusable](#focusable) | Android | -| [fullscreen](#fullscreen) | Android, iOS | -| [fullscreenAutorotate](#fullscreenautorotate) | iOS, visionOS | -| [fullscreenOrientation](#fullscreenorientation) | iOS, visionOS | -| [headers](#headers) | Android | -| [hideShutterView](#hideshutterview) | Android | -| [ignoreSilentSwitch](#ignoresilentswitch) | iOS, visionOS | -| [maxBitRate](#maxbitrate) | Android, iOS, visionOS | -| [minLoadRetryCount](#minloadretrycount) | Android | -| [mixWithOthers](#mixwithothers) | iOS, visionOS | -| [muted](#muted) | All | -| [paused](#paused) | All | -| [pictureInPicture](#pictureinpicture) | iOS | -| [playInBackground](#playinbackground) | Android, iOS, visionOS | -| [playWhenInactive](#playwheninactive) | iOS, visionOS | -| [poster](#poster) | All | -| [posterResizeMode](#posterresizemode) | All | -| [preferredForwardBufferDuration](#preferredforwardbufferduration) | iOS, visionOS | -| [preventsDisplaySleepDuringVideoPlayback](#preventsdisplaysleepduringvideoplayback) | iOS, Android | -| [progressUpdateInterval](#progressupdateinterval) | All | -| [rate](#rate) | All | -| [repeat](#repeat) | All | -| [reportBandwidth](#reportbandwidth) | Android | -| [resizeMode](#resizemode) | All | -| [selectedAudioTrack](#selectedaudiotrack) | Android, iOS, visionOS | -| [selectedTextTrack](#selectedtexttrack) | Android, iOS visionOS | -| [selectedVideoTrack](#selectedvideotrack) | Android | -| [shutterColor](#shutterColor) | Android | -| [source](#source) | All | -| [subtitleStyle](#subtitlestyle) | Android | -| [textTracks](#texttracks) | Android, iOS, visionOS | -| [trackId](#trackid) | Android | -| [useTextureView](#usetextureview) | Android | -| [useSecureView](#usesecureview) | Android | -| [volume](#volume) | All | -| [localSourceEncryptionKeyScheme](#localsourceencryptionkeyscheme) | All | +| Name | Platforms Support | +|-------------------------------------------------------------------------------------|---------------------------| +| [adTagUrl](#adtagurl) | Android, iOS | +| [allowsExternalPlayback](#allowsexternalplayback) | iOS | +| [audioOnly](#audioonly) | All | +| [audioOutput](#audioOutput) | Android, iOS, visionOS | +| [automaticallyWaitsToMinimizeStalling](#automaticallywaitstominimizestalling) | iOS, visionOS | +| [backBufferDurationMs](#backbufferdurationms) | Android | +| [bufferConfig](#bufferconfig) | Android | +| [contentStartTime](#contentstarttime) | Android | +| [controls](#controls) | Android, iOS, visionOS | +| [currentPlaybackTime](#currentplaybacktime) | Android | +| [debug](#debug) | Android | +| [disableFocus](#disablefocus) | Android | +| [disableDisconnectError](#disabledisconnecterror) | Android | +| [filter](#filter) | iOS, visionOS | +| [filterEnabled](#filterenabled) | iOS, visionOS | +| [focusable](#focusable) | Android | +| [fullscreen](#fullscreen) | Android, iOS | +| [fullscreenAutorotate](#fullscreenautorotate) | iOS, visionOS | +| [fullscreenOrientation](#fullscreenorientation) | iOS, visionOS | +| [headers](#headers) | Android | +| [hideShutterView](#hideshutterview) | Android | +| [ignoreSilentSwitch](#ignoresilentswitch) | iOS, visionOS | +| [maxBitRate](#maxbitrate) | Android, iOS, visionOS | +| [minLoadRetryCount](#minloadretrycount) | Android | +| [mixWithOthers](#mixwithothers) | iOS, visionOS | +| [muted](#muted) | All | +| [paused](#paused) | All | +| [pictureInPicture](#pictureinpicture) | iOS | +| [playInBackground](#playinbackground) | Android, iOS, visionOS | +| [playWhenInactive](#playwheninactive) | iOS, visionOS | +| [poster](#poster) | All | +| [posterResizeMode](#posterresizemode) | All | +| [preferredForwardBufferDuration](#preferredforwardbufferduration) | iOS, visionOS | +| [preventsDisplaySleepDuringVideoPlayback](#preventsdisplaysleepduringvideoplayback) | iOS, Android | +| [progressUpdateInterval](#progressupdateinterval) | All | +| [rate](#rate) | All | +| [repeat](#repeat) | All | +| [reportBandwidth](#reportbandwidth) | Android | +| [resizeMode](#resizemode) | All | +| [selectedAudioTrack](#selectedaudiotrack) | Android, iOS, visionOS | +| [selectedTextTrack](#selectedtexttrack) | Android, iOS visionOS | +| [selectedVideoTrack](#selectedvideotrack) | Android | +| [shutterColor](#shutterColor) | Android | +| [source](#source) | All | +| [subtitleStyle](#subtitlestyle) | Android | +| [textTracks](#texttracks) | Android, iOS, visionOS | +| [trackId](#trackid) | Android | +| [useTextureView](#usetextureview) | Android | +| [useSecureView](#usesecureview) | Android | +| [volume](#volume) | All | +| [localSourceEncryptionKeyScheme](#localsourceencryptionkeyscheme) | All | ## Details - ### `adTagUrl` - Sets the VAST uri to play AVOD ads. Example: - ``` adTagUrl="https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/vmap_ad_samples&sz=640x480&cust_params=sample_ar%3Dpremidpostoptimizedpodbumper&ciu_szs=300x250&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&env=vp&impl=s&cmsid=496&vid=short_onecue&correlator=" ``` Note: You need enable IMA SDK in gradle or pod file - [enable client side ads insertion](/installation) + Platforms: Android, iOS ### `allowsExternalPlayback` - Indicates whether the player allows switching to external playback mode such as AirPlay or HDMI. - -- **true (default)** - allow switching to external playback mode -- **false** - Don't allow switching to external playback mode +* **true (default)** - allow switching to external playback mode +* **false** - Don't allow switching to external playback mode Platforms: iOS ### `audioOnly` - Indicates whether the player should only play the audio track and instead of displaying the video track, show the poster instead. - -- **false (default)** - Display the video as normal -- **true** - Show the poster and play the audio +* **false (default)** - Display the video as normal +* **true** - Show the poster and play the audio For this to work, the poster prop must be set. Platforms: all ### `audioOutput` - Changes the audio output. - -- **speaker (default)** - plays through speaker -- **earpiece** - plays through earpiece +* **speaker (default)** - plays through speaker +* **earpiece** - plays through earpiece Platforms: Android, iOS, visionOS ### `automaticallyWaitsToMinimizeStalling` - A Boolean value that indicates whether the player should automatically delay playback in order to minimize stalling. For clients linked against iOS 10.0 and later - -- **false** - Immediately starts playback -- **true (default)** - Delays playback in order to minimize stalling +* **false** - Immediately starts playback +* **true (default)** - Delays playback in order to minimize stalling Platforms: iOS, visionOS ### `backBufferDurationMs` - The number of milliseconds of buffer to keep before the current position. This allows rewinding without rebuffering within that duration. Platforms: Android ### `bufferConfig` - Adjust the buffer settings. This prop takes an object with one or more of the properties listed below. -| Property | Type | Description | -| --------------------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| bufferSize | number | The maximum cache size for Android to use as a cache folder, in MB. | -| minBufferMs | number | The default minimum duration of media that the player will attempt to ensure is buffered at all times, in milliseconds. | -| maxBufferMs | number | The default maximum duration of media that the player will attempt to buffer, in milliseconds. | -| bufferForPlaybackMs | number | The default duration of media that must be buffered for playback to start or resume following a user action such as a seek, in milliseconds. | -| bufferForPlaybackAfterRebufferMs | number | The default duration of media that must be buffered for playback to resume after a rebuffer, in milliseconds. A rebuffer is defined to be caused by buffer depletion rather than a user action. | -| maxHeapAllocationPercent | number | The percentage of available heap that the video can use to buffer, between 0 and 1 | -| minBackBufferMemoryReservePercent | number | The percentage of available app memory at which during startup the back buffer will be disabled, between 0 and 1 | -| minBufferMemoryReservePercent | number | The percentage of available app memory to keep in reserve that prevents buffer from using it, between 0 and 1 | +Property | Type | Description +--- | --- | --- +minBufferMs | number | The default minimum duration of media that the player will attempt to ensure is buffered at all times, in milliseconds. +maxBufferMs | number | The default maximum duration of media that the player will attempt to buffer, in milliseconds. +bufferForPlaybackMs | number | The default duration of media that must be buffered for playback to start or resume following a user action such as a seek, in milliseconds. +bufferForPlaybackAfterRebufferMs | number | The default duration of media that must be buffered for playback to resume after a rebuffer, in milliseconds. A rebuffer is defined to be caused by buffer depletion rather than a user action. +maxHeapAllocationPercent | number | The percentage of available heap that the video can use to buffer, between 0 and 1 +minBackBufferMemoryReservePercent | number | The percentage of available app memory at which during startup the back buffer will be disabled, between 0 and 1 +minBufferMemoryReservePercent | number | The percentage of available app memory to keep in reserve that prevents buffer from using it, between 0 and 1 This prop should only be set when you are setting the source, changing it after the media is loaded will cause it to be reloaded. Example with default values: - ```javascript bufferConfig={{ minBufferMs: 15000, maxBufferMs: 50000, bufferForPlaybackMs: 2500, - bufferForPlaybackAfterRebufferMs: 5000, - bufferSize: 0 + bufferForPlaybackAfterRebufferMs: 5000 }} ``` Platforms: Android ### `chapters` - To provide a custom chapter source for tvOS. This prop takes an array of objects with the properties listed below. | Property | Type | Description | -| --------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | +|-----------|---------|-----------------------------------------------------------------------------------------------------------------------------------------------------------| | title | string | The title of the chapter to create | | startTime | number | The start time of the chapter in seconds | | endTime | number | The end time of the chapter in seconds | | uri | string? | Optional: Provide an http orl or the some base64 string to override the image of the chapter. For some media files the images are generated automatically | + Platforms: tvOS ### `currentPlaybackTime` - When playing an HLS live stream with a `EXT-X-PROGRAM-DATE-TIME` tag configured, then this property will contain the epoch value in msec. Platforms: Android, iOS ### `controls` - Determines whether to show player controls. - -- **false (default)** - Don't show player controls -- **true** - Show player controls +* **false (default)** - Don't show player controls +* **true** - Show player controls Note on iOS, controls are always shown when in fullscreen mode. Note on Android, native controls are available by default. @@ -182,7 +163,6 @@ If needed, you can also add your controls or use a package like [react-native-vi Platforms: Android, iOS, visionOS ### `contentStartTime` - The start time in ms for SSAI content. This determines at what time to load the video info like resolutions. Use this only when you have SSAI stream where ads resolution is not the same as content resolution. Platforms: Android @@ -194,75 +174,66 @@ Enable more verbosity in logs. > [!WARNING] > Do not use this open in production build -| Property | Type | Description | -| -------- | ------- | --------------------------------------------- | -| `enable` | boolean | when true, display logs with verbosity higher | -| `thread` | boolean | enable thread display | +| Property | Type | Description | +| ------------------ | ------ | ------------------------------------------------------------------------------------------- | +| `enable` | boolean | when true, display logs with verbosity higher | +| `thread` | boolean | enable thread display | -Example with default values: +Example with default values: ```javascript debug={{ enable: true, thread: true, }} ``` - Platforms: Android -### `disableFocus` +### `disableFocus` Determines whether video audio should override background music/audio in Android devices. - -- **false (default)** - Override background audio/music -- **true** - Let background audio/music from other apps play - +* **false (default)** - Override background audio/music +* **true** - Let background audio/music from other apps play + Note: Allows multiple videos to play if set to `true`. If `false`, when one video is playing and another is started, the first video will be paused. - + Platforms: Android ### `disableDisconnectError` - Determines if the player needs to throw an error when connection is lost or not - -- **false (default)** - Player will throw an error when connection is lost -- **true** - Player will keep trying to buffer when network connect is lost +* **false (default)** - Player will throw an error when connection is lost +* **true** - Player will keep trying to buffer when network connect is lost Platforms: Android ### `DRM` - To setup DRM please follow [this guide](/component/drm) Platforms: Android, iOS - > ⚠️ DRM is not supported on visionOS yet ### `filter` - Add video filter - -- **FilterType.NONE (default)** - No Filter -- **FilterType.INVERT** - CIColorInvert -- **FilterType.MONOCHROME** - CIColorMonochrome -- **FilterType.POSTERIZE** - CIColorPosterize -- **FilterType.FALSE** - CIFalseColor -- **FilterType.MAXIMUMCOMPONENT** - CIMaximumComponent -- **FilterType.MINIMUMCOMPONENT** - CIMinimumComponent -- **FilterType.CHROME** - CIPhotoEffectChrome -- **FilterType.FADE** - CIPhotoEffectFade -- **FilterType.INSTANT** - CIPhotoEffectInstant -- **FilterType.MONO** - CIPhotoEffectMono -- **FilterType.NOIR** - CIPhotoEffectNoir -- **FilterType.PROCESS** - CIPhotoEffectProcess -- **FilterType.TONAL** - CIPhotoEffectTonal -- **FilterType.TRANSFER** - CIPhotoEffectTransfer -- **FilterType.SEPIA** - CISepiaTone +* **FilterType.NONE (default)** - No Filter +* **FilterType.INVERT** - CIColorInvert +* **FilterType.MONOCHROME** - CIColorMonochrome +* **FilterType.POSTERIZE** - CIColorPosterize +* **FilterType.FALSE** - CIFalseColor +* **FilterType.MAXIMUMCOMPONENT** - CIMaximumComponent +* **FilterType.MINIMUMCOMPONENT** - CIMinimumComponent +* **FilterType.CHROME** - CIPhotoEffectChrome +* **FilterType.FADE** - CIPhotoEffectFade +* **FilterType.INSTANT** - CIPhotoEffectInstant +* **FilterType.MONO** - CIPhotoEffectMono +* **FilterType.NOIR** - CIPhotoEffectNoir +* **FilterType.PROCESS** - CIPhotoEffectProcess +* **FilterType.TONAL** - CIPhotoEffectTonal +* **FilterType.TRANSFER** - CIPhotoEffectTransfer +* **FilterType.SEPIA** - CISepiaTone For more details on these filters refer to the [iOS docs](https://developer.apple.com/library/archive/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/uid/TP30000136-SW55). -Notes: - +Notes: 1. Using a filter can impact CPU usage. A workaround is to save the video with the filter and then load the saved video. 2. Video filter is currently not supported on HLS playlists. 3. `filterEnabled` must be set to `true` @@ -270,53 +241,47 @@ Notes: Platforms: iOS, visionOS ### `filterEnabled` +Enable video filter. -Enable video filter. - -- **false (default)** - Don't enable filter -- **true** - Enable filter +* **false (default)** - Don't enable filter +* **true** - Enable filter Platforms: iOS, visionOS ### `Focusable` - Whether this video view should be focusable with a non-touch input device, eg. receive focus with a hardware keyboard. - -- **false** - Makes view unfocusable -- **true (default)** - Makes view focusable - +* **false** - Makes view unfocusable +* **true (default)** - Makes view focusable + Platforms: Android -### `fullscreen` +### `fullscreen` Controls whether the player enters fullscreen on play. See [presentFullscreenPlayer](#presentfullscreenplayer) for details. -- **false (default)** - Don't display the video in fullscreen -- **true** - Display the video in fullscreen +* **false (default)** - Don't display the video in fullscreen +* **true** - Display the video in fullscreen Platforms: iOS, Android, visionOS ### `fullscreenAutorotate` - If a preferred [fullscreenOrientation](#fullscreenorientation) is set, causes the video to rotate to that orientation but permits rotation of the screen to orientation held by user. Defaults to TRUE. Platforms: iOS, visionOS ### `fullscreenOrientation` -- **all (default)** - -- **landscape** -- **portrait** +* **all (default)** - +* **landscape** +* **portrait** Platforms: iOS, visionOS ### `headers` - Pass headers to the HTTP client. Can be used for authorization. Headers must be a part of the source object. Example: - ```javascript source={{ uri: "https://www.example.com/video.mp4", @@ -330,32 +295,27 @@ source={{ Platforms: Android ### `hideShutterView` - Controls whether the ExoPlayer shutter view (black screen while loading) is enabled. -- **false (default)** - Show shutter view -- **true** - Hide shutter view +* **false (default)** - Show shutter view +* **true** - Hide shutter view Platforms: Android ### `ignoreSilentSwitch` - Controls the iOS silent switch behavior - -- **"inherit" (default)** - Use the default AVPlayer behavior -- **"ignore"** - Play audio even if the silent switch is set -- **"obey"** - Don't play audio if the silent switch is set +* **"inherit" (default)** - Use the default AVPlayer behavior +* **"ignore"** - Play audio even if the silent switch is set +* **"obey"** - Don't play audio if the silent switch is set Platforms: iOS, visionOS ### `maxBitRate` - Sets the desired limit, in bits per second, of network bandwidth consumption when multiple video streams are available for a playlist. Default: 0. Don't limit the maxBitRate. Example: - ```javascript maxBitRate={2000000} // 2 megabits ``` @@ -363,13 +323,11 @@ maxBitRate={2000000} // 2 megabits Platforms: Android, iOS, visionOS ### `minLoadRetryCount` - Sets the minimum number of times to retry loading data before failing and reporting an error to the application. Useful to recover from transient internet failures. Default: 3. Retry 3 times. Example: - ```javascript minLoadRetryCount={5} // retry 5 times ``` @@ -377,89 +335,72 @@ minLoadRetryCount={5} // retry 5 times Platforms: Android ### `mixWithOthers` - Controls how Audio mix with other apps. - -- **"inherit" (default)** - Use the default AVPlayer behavior -- **"mix"** - Audio from this video mixes with audio from other apps. -- **"duck"** - Reduces the volume of other apps while audio from this video plays. +* **"inherit" (default)** - Use the default AVPlayer behavior +* **"mix"** - Audio from this video mixes with audio from other apps. +* **"duck"** - Reduces the volume of other apps while audio from this video plays. Platforms: iOS, visionOS ### `muted` - Controls whether the audio is muted - -- **false (default)** - Don't mute audio -- **true** - Mute audio +* **false (default)** - Don't mute audio +* **true** - Mute audio Platforms: all ### `paused` - Controls whether the media is paused - -- **false (default)** - Don't pause the media -- **true** - Pause the media +* **false (default)** - Don't pause the media +* **true** - Pause the media Platforms: all ### `pictureInPicture` - Determine whether the media should played as picture in picture. +* **false (default)** - Don't not play as picture in picture +* **true** - Play the media as picture in picture -- **false (default)** - Don't not play as picture in picture -- **true** - Play the media as picture in picture - -NOTE: Video ads cannot start when you are using the PIP on iOS (more info available at [Google IMA SDK Docs](https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/picture_in_picture?hl=en#starting_ads)). If you are using custom controls, you must hide your PIP button when you receive the `STARTED` event from `onReceiveAdEvent` and show it again when you receive the `ALL_ADS_COMPLETED` event. +NOTE: Video ads cannot start when you are using the PIP on iOS (more info available at [Google IMA SDK Docs](https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/picture_in_picture?hl=en#starting_ads)). If you are using custom controls, you must hide your PIP button when you receive the ```STARTED``` event from ```onReceiveAdEvent``` and show it again when you receive the ```ALL_ADS_COMPLETED``` event. Platforms: iOS ### `playInBackground` - Determine whether the media should continue playing while the app is in the background. This allows customers to continue listening to the audio. - -- **false (default)** - Don't continue playing the media -- **true** - Continue playing the media +* **false (default)** - Don't continue playing the media +* **true** - Continue playing the media To use this feature on iOS, you must: - -- [Enable Background Audio](https://developer.apple.com/library/archive/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/AudioSessionBasics/AudioSessionBasics.html#//apple_ref/doc/uid/TP40007875-CH3-SW3) in your Xcode project -- Set the ignoreSilentSwitch prop to "ignore" +* [Enable Background Audio](https://developer.apple.com/library/archive/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/AudioSessionBasics/AudioSessionBasics.html#//apple_ref/doc/uid/TP40007875-CH3-SW3) in your Xcode project +* Set the ignoreSilentSwitch prop to "ignore" Platforms: Android, iOS, visionOS ### `playWhenInactive` - Determine whether the media should continue playing when notifications or the Control Center are in front of the video. - -- **false (default)** - Don't continue playing the media -- **true** - Continue playing the media +* **false (default)** - Don't continue playing the media +* **true** - Continue playing the media Platforms: iOS, visionOS ### `poster` - An image to display while the video is loading
Value: string with a URL for the poster, e.g. "https://baconmockup.com/300/200/" Platforms: all ### `posterResizeMode` - Determines how to resize the poster image when the frame doesn't match the raw video dimensions. - -- **"contain" (default)** - Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding). -- **"center"** - Center the image in the view along both dimensions. If the image is larger than the view, scale it down uniformly so that it is contained in the view. -- **"cover"** - Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). -- **"none"** - Don't apply resize -- **"repeat"** - Repeat the image to cover the frame of the view. The image will keep its size and aspect ratio. (iOS only) -- **"stretch"** - Scale width and height independently, This may change the aspect ratio of the src. +* **"contain" (default)** - Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding). +* **"center"** - Center the image in the view along both dimensions. If the image is larger than the view, scale it down uniformly so that it is contained in the view. +* **"cover"** - Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). +* **"none"** - Don't apply resize +* **"repeat"** - Repeat the image to cover the frame of the view. The image will keep its size and aspect ratio. (iOS only) +* **"stretch"** - Scale width and height independently, This may change the aspect ratio of the src. Platforms: all ### `preferredForwardBufferDuration` - The duration the player should buffer media from the network ahead of the playhead to guard against playback disruption. Sets the [preferredForwardBufferDuration](https://developer.apple.com/documentation/avfoundation/avplayeritem/1643630-preferredforwardbufferduration) instance property on AVPlayerItem. Default: 0 @@ -467,7 +408,6 @@ Default: 0 Platforms: iOS, visionOS ### `preventsDisplaySleepDuringVideoPlayback` - Controls whether or not the display should be allowed to sleep while playing the video. Default is not to allow display to sleep. Default: true @@ -475,7 +415,6 @@ Default: true Platforms: iOS, Android ### `progressUpdateInterval` - Delay in milliseconds between onProgress events in milliseconds. Default: 250.0 @@ -483,41 +422,36 @@ Default: 250.0 Platforms: all ### `rate` - -Speed at which the media should play. - -- **0.0** - Pauses the video -- **1.0** - Play at normal speed -- **Other values** - Slow down or speed up playback +Speed at which the media should play. +* **0.0** - Pauses the video +* **1.0** - Play at normal speed +* **Other values** - Slow down or speed up playback Platforms: all ### `repeat` - Determine whether to repeat the video when the end is reached - -- **false (default)** - Don't repeat the video -- **true** - Repeat the video +* **false (default)** - Don't repeat the video +* **true** - Repeat the video Platforms: all -### `onAudioTracks` +### `onAudioTracks` Callback function that is called when audio tracks change Payload: -| Property | Type | Description | -| -------- | ------- | ---------------------------------------------------------------------------------------------------------- | -| index | number | Internal track ID | -| title | string | Descriptive name for the track | -| language | string | 2 letter [ISO 639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) representing the language | -| bitrate | number | bitrate of track | -| type | string | Mime type of track | -| selected | boolean | true if track is playing | +Property | Type | Description +--- | --- | --- +index | number | Internal track ID +title | string | Descriptive name for the track +language | string | 2 letter [ISO 639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) representing the language +bitrate | number | bitrate of track +type | string | Mime type of track +selected | boolean | true if track is playing Example: - ```javascript { audioTracks: [ @@ -527,30 +461,27 @@ Example: } ``` + Platforms: Android ### `reportBandwidth` - Determine whether to generate onBandwidthUpdate events. This is needed due to the high frequency of these events on ExoPlayer. -- **false (default)** - Don't generate onBandwidthUpdate events -- **true** - Generate onBandwidthUpdate events +* **false (default)** - Don't generate onBandwidthUpdate events +* **true** - Generate onBandwidthUpdate events Platforms: Android ### `resizeMode` - Determines how to resize the video when the frame doesn't match the raw video dimensions. - -- **"none" (default)** - Don't apply resize -- **"contain"** - Scale the video uniformly (maintain the video's aspect ratio) so that both dimensions (width and height) of the video will be equal to or less than the corresponding dimension of the view (minus padding). -- **"cover"** - Scale the video uniformly (maintain the video's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). -- **"stretch"** - Scale width and height independently, This may change the aspect ratio of the src. +* **"none" (default)** - Don't apply resize +* **"contain"** - Scale the video uniformly (maintain the video's aspect ratio) so that both dimensions (width and height) of the video will be equal to or less than the corresponding dimension of the view (minus padding). +* **"cover"** - Scale the video uniformly (maintain the video's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). +* **"stretch"** - Scale width and height independently, This may change the aspect ratio of the src. Platforms: Android, iOS, Windows UWP ### `selectedAudioTrack` - Configure which audio track, if any, is played. ```javascript @@ -561,7 +492,6 @@ selectedAudioTrack={{ ``` Example: - ```javascript selectedAudioTrack={{ type: "title", @@ -569,20 +499,19 @@ selectedAudioTrack={{ }} ``` -| Type | Value | Description | -| ------------------ | ------ | ------------------------------------------------------------------------------------------- | -| "system" (default) | N/A | Play the audio track that matches the system language. If none match, play the first track. | -| "disabled" | N/A | Turn off audio | -| "title" | string | Play the audio track with the title specified as the Value, e.g. "French" | -| "language" | string | Play the audio track with the language specified as the Value, e.g. "fr" | -| "index" | number | Play the audio track with the index specified as the value, e.g. 0 | +Type | Value | Description +--- | --- | --- +"system" (default) | N/A | Play the audio track that matches the system language. If none match, play the first track. +"disabled" | N/A | Turn off audio +"title" | string | Play the audio track with the title specified as the Value, e.g. "French" +"language" | string | Play the audio track with the language specified as the Value, e.g. "fr" +"index" | number | Play the audio track with the index specified as the value, e.g. 0 If a track matching the specified Type (and Value if appropriate) is unavailable, the first audio track will be played. If multiple tracks match the criteria, the first match will be used. Platforms: Android, iOS, visionOS ### `selectedTextTrack` - Configure which text track (caption or subtitle), if any, is shown. ```javascript @@ -593,7 +522,6 @@ selectedTextTrack={{ ``` Example: - ```javascript selectedTextTrack={{ type: "title", @@ -601,22 +529,21 @@ selectedTextTrack={{ }} ``` -| Type | Value | Description | -| ------------------ | ------ | ----------------------------------------------------------------------------- | -| "system" (default) | N/A | Display captions only if the system preference for captions is enabled | -| "disabled" | N/A | Don't display a text track | -| "title" | string | Display the text track with the title specified as the Value, e.g. "French 1" | -| "language" | string | Display the text track with the language specified as the Value, e.g. "fr" | -| "index" | number | Display the text track with the index specified as the value, e.g. 0 | +Type | Value | Description +--- | --- | --- +"system" (default) | N/A | Display captions only if the system preference for captions is enabled +"disabled" | N/A | Don't display a text track +"title" | string | Display the text track with the title specified as the Value, e.g. "French 1" +"language" | string | Display the text track with the language specified as the Value, e.g. "fr" +"index" | number | Display the text track with the index specified as the value, e.g. 0 -Both iOS & Android (only 4.4 and higher) offer Settings to enable Captions for hearing impaired people. If "system" is selected and the Captions Setting is enabled, iOS/Android will look for a caption that matches that customer's language and display it. +Both iOS & Android (only 4.4 and higher) offer Settings to enable Captions for hearing impaired people. If "system" is selected and the Captions Setting is enabled, iOS/Android will look for a caption that matches that customer's language and display it. If a track matching the specified Type (and Value if appropriate) is unavailable, no text track will be displayed. If multiple tracks match the criteria, the first match will be used. Platforms: Android, iOS, visionOS ### `selectedVideoTrack` - Configure which video track should be played. By default, the player uses Adaptive Bitrate Streaming to automatically select the stream it thinks will perform best based on available bandwidth. ```javascript @@ -627,7 +554,6 @@ selectedVideoTrack={{ ``` Example: - ```javascript selectedVideoTrack={{ type: "resolution", @@ -635,23 +561,22 @@ selectedVideoTrack={{ }} ``` -| Type | Value | Description | -| ---------------- | ------ | ---------------------------------------------------------------------------- | -| "auto" (default) | N/A | Let the player determine which track to play using ABR | -| "disabled" | N/A | Turn off video | -| "resolution" | number | Play the video track with the height specified, e.g. 480 for the 480p stream | -| "index" | number | Play the video track with the index specified as the value, e.g. 0 | +Type | Value | Description +--- | --- | --- +"auto" (default) | N/A | Let the player determine which track to play using ABR +"disabled" | N/A | Turn off video +"resolution" | number | Play the video track with the height specified, e.g. 480 for the 480p stream +"index" | number | Play the video track with the index specified as the value, e.g. 0 If a track matching the specified Type (and Value if appropriate) is unavailable, ABR will be used. Platforms: Android ### `shutterColor` - -Apply color to shutter view, if you see black flashes before video start then set +Apply color to shutter view, if you see black flashes before video start then set ```javascript -shutterColor = 'transparent'; +shutterColor='transparent' ``` - black (default) @@ -659,7 +584,6 @@ shutterColor = 'transparent'; Platforms: Android ### `source` - Sets the media source. You can pass an asset loaded via require or an object with a uri. Setting the source will trigger the player to attempt to load the provided media with all other given props. Please be sure that all props are provided before/at the same time as setting the source. @@ -670,16 +594,16 @@ Providing a null source value after loading a previous source will stop playback The docs for this prop are incomplete and will be updated as each option is investigated and tested. + #### Asset loaded via require > ⚠️ on iOS, you file name must not contain spaces eg. `my video.mp4` will not work, use `my-video.mp4` instead -Example: - +Example: ```javascript const sintel = require('./sintel.mp4'); -source = {sintel}; +source={sintel} ``` #### URI string @@ -692,7 +616,6 @@ For exemple 'www.myurl.com/blabla?q=test uri' is invalid, where 'www.myurl.com/b ##### Web address (http://, https://) Example: - ```javascript source={{uri: 'https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_10mb.mp4' }} ``` @@ -702,7 +625,6 @@ Platforms: all ##### File path (file://) Example: - ```javascript source={{ uri: 'file:///sdcard/Movies/sintel.mp4' }} ``` @@ -716,7 +638,6 @@ Platforms: Android, possibly others Path to a sound file in your iTunes library. Typically shared from iTunes to your app. Example: - ```javascript source={{ uri: 'ipod-library:///path/to/music.mp3' }} ``` @@ -731,7 +652,6 @@ Provide a member `type` with value (`mpd`/`m3u8`/`ism`) inside the source object Sometimes is needed when URL extension does not match with the mimetype that you are expecting, as seen on the next example. (Extension is .ism -smooth streaming- but file served is on format mpd -mpeg dash-) Example: - ```javascript source={{ uri: 'http://host-serving-a-type-different-than-the-extension.ism/manifest(format=mpd-time-csf)', type: 'mpd' }} @@ -754,7 +674,6 @@ Platforms: Android, iOS Provide an optional `cropStart` and/or `cropEnd` for the video. Value is in milliseconds. Useful when you want to play only a portion of a large video. Example - ```javascript source={{ uri: 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8', cropStart: 36012, cropEnd: 48500 }} @@ -767,16 +686,16 @@ Platforms: iOS, Android #### Overriding the metadata of a source -Provide an optional `title`, `subtitle`, `customImageUri` and/or `description` properties for the video. +Provide an optional `title`, `subtitle`, `customImageUri` and/or `description` properties for the video. Useful when to adapt the tvOS playback experience. Example: ```javascript -source={{ - uri: 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8', - title: 'Custom Title', - subtitle: 'Custom Subtitle', +source={{ + uri: 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8', + title: 'Custom Title', + subtitle: 'Custom Subtitle', description: 'Custom Description', customImageUri: 'https://pbs.twimg.com/profile_images/1498641868397191170/6qW2XkuI_400x400.png' }} @@ -786,13 +705,14 @@ Platforms: tvOS ### `subtitleStyle` -| Property | Description | Platforms | -| ------------- | ----------------------------------------------------------------------- | --------- | -| fontSize | Adjust the font size of the subtitles. Default: font size of the device | Android | -| paddingTop | Adjust the top padding of the subtitles. Default: 0 | Android | -| paddingBottom | Adjust the bottom padding of the subtitles. Default: 0 | Android | -| paddingLeft | Adjust the left padding of the subtitles. Default: 0 | Android | -| paddingRight | Adjust the right padding of the subtitles. Default: 0 | Android | +Property | Description | Platforms +--- | --- | --- +fontSize | Adjust the font size of the subtitles. Default: font size of the device | Android +paddingTop | Adjust the top padding of the subtitles. Default: 0| Android +paddingBottom | Adjust the bottom padding of the subtitles. Default: 0| Android +paddingLeft | Adjust the left padding of the subtitles. Default: 0| Android +paddingRight | Adjust the right padding of the subtitles. Default: 0| Android + Example: @@ -801,24 +721,21 @@ subtitleStyle={{ paddingBottom: 50, fontSize: 20 }} ``` ### `textTracks` - Load one or more "sidecar" text tracks. This takes an array of objects representing each track. Each object should have the format: - > ⚠️ This feature does not work with HLS playlists (e.g m3u8) on iOS -| Property | Description | -| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| title | Descriptive name for the track | -| language | 2 letter [ISO 639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) representing the language | -| type | Mime type of the track
_ TextTrackType.SRT - SubRip (.srt)
_ TextTrackType.TTML - TTML (.ttml)
\* TextTrackType.VTT - WebVTT (.vtt)
iOS only supports VTT, Android supports all 3 | -| uri | URL for the text track. Currently, only tracks hosted on a webserver are supported | +Property | Description +--- | --- +title | Descriptive name for the track +language | 2 letter [ISO 639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) representing the language +type | Mime type of the track
* TextTrackType.SRT - SubRip (.srt)
* TextTrackType.TTML - TTML (.ttml)
* TextTrackType.VTT - WebVTT (.vtt)
iOS only supports VTT, Android supports all 3 +uri | URL for the text track. Currently, only tracks hosted on a webserver are supported On iOS, sidecar text tracks are only supported for individual files, not HLS playlists. For HLS, you should include the text tracks as part of the playlist. Note: Due to iOS limitations, sidecar text tracks are not compatible with Airplay. If textTracks are specified, AirPlay support will be automatically disabled. Example: - ```javascript import { TextTrackType }, Video from 'react-native-video'; @@ -838,63 +755,56 @@ textTracks={[ ]} ``` + Platforms: Android, iOS, visionOS ### `trackId` - Configure an identifier for the video stream to link the playback context to the events emitted. Platforms: Android ### `useTextureView` - Controls whether to output to a TextureView or SurfaceView. SurfaceView is more efficient and provides better performance but has two limitations: - -- It can't be animated, transformed or scaled -- You can't overlay multiple SurfaceViews +* It can't be animated, transformed or scaled +* You can't overlay multiple SurfaceViews useTextureView can only be set at same time you're setting the source. -- **true (default)** - Use a TextureView -- **false** - Use a SurfaceView +* **true (default)** - Use a TextureView +* **false** - Use a SurfaceView Platforms: Android ### `useSecureView` - Force the output to a SurfaceView and enables the secure surface. This will override useTextureView flag. SurfaceView is is the only one that can be labeled as secure. -- **true** - Use security -- **false (default)** - Do not use security +* **true** - Use security +* **false (default)** - Do not use security Platforms: Android ### `volume` - Adjust the volume. - -- **1.0 (default)** - Play at full volume -- **0.0** - Mute the audio -- **Other values** - Reduce volume +* **1.0 (default)** - Play at full volume +* **0.0** - Mute the audio +* **Other values** - Reduce volume Platforms: all ### `localSourceEncryptionKeyScheme` - Set the url scheme for stream encryption key for local assets Type: String Example: - ``` localSourceEncryptionKeyScheme="my-offline-key" ``` -Platforms: iOS +Platforms: iOS \ No newline at end of file diff --git a/src/types/video.ts b/src/types/video.ts index 3c9f400478..415c69c530 100644 --- a/src/types/video.ts +++ b/src/types/video.ts @@ -68,7 +68,6 @@ export type BufferConfig = { maxHeapAllocationPercent?: number; minBackBufferMemoryReservePercent?: number; minBufferMemoryReservePercent?: number; - bufferSize?: number; }; export enum SelectedTrackType { From 47ddca62c9811f57e42c8bb1c87c4d15d92396d2 Mon Sep 17 00:00:00 2001 From: lovegaoshi <106490582+lovegaoshi@users.noreply.github.com> Date: Mon, 5 Feb 2024 13:54:10 -0800 Subject: [PATCH 04/14] fix: cacheSize name --- .../exoplayer/ReactExoplayerView.java | 17 ++++++++++------- .../exoplayer/ReactExoplayerViewManager.java | 8 ++++---- docs/pages/component/props.md | 1 + examples/basic/src/VideoPlayer.tsx | 6 +++--- src/VideoNativeComponent.ts | 2 +- src/types/video.ts | 1 + 6 files changed, 20 insertions(+), 15 deletions(-) diff --git a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java index 3c4a8f066f..2bcf37cc1b 100644 --- a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java +++ b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java @@ -16,7 +16,6 @@ import android.os.Looper; import android.os.Message; import android.text.TextUtils; -import android.util.Log; import android.view.View; import android.view.Window; import android.view.accessibility.CaptioningManager; @@ -2042,7 +2041,7 @@ public void setHideShutterView(boolean hideShutterView) { exoPlayerView.setHideShutterView(hideShutterView); } - public void setBufferConfig(int newMinBufferMs, int newMaxBufferMs, int newBufferForPlaybackMs, int newBufferForPlaybackAfterRebufferMs, double newMaxHeapAllocationPercent, double newMinBackBufferMemoryReservePercent, double newMinBufferMemoryReservePercent, int bufferSize) { + public void setBufferConfig(int newMinBufferMs, int newMaxBufferMs, int newBufferForPlaybackMs, int newBufferForPlaybackAfterRebufferMs, double newMaxHeapAllocationPercent, double newMinBackBufferMemoryReservePercent, double newMinBufferMemoryReservePercent, int cacheSize) { minBufferMs = newMinBufferMs; maxBufferMs = newMaxBufferMs; bufferForPlaybackMs = newBufferForPlaybackMs; @@ -2050,11 +2049,15 @@ public void setBufferConfig(int newMinBufferMs, int newMaxBufferMs, int newBuffe maxHeapAllocationPercent = newMaxHeapAllocationPercent; minBackBufferMemoryReservePercent = newMinBackBufferMemoryReservePercent; minBufferMemoryReservePercent = newMinBufferMemoryReservePercent; - SimpleCache simpleCache = new SimpleCache(new File(this.getContext().getCacheDir(), "RNVCache"), new LeastRecentlyUsedCacheEvictor((long) bufferSize*1024*1024), new StandaloneDatabaseProvider(this.getContext())); - cacheDataSourceFactory = - new CacheDataSource.Factory() - .setCache(simpleCache) - .setUpstreamDataSourceFactory(buildHttpDataSourceFactory(false)); + if (cacheSize == 0) { + cacheDataSourceFactory = null; + } else { + SimpleCache simpleCache = new SimpleCache(new File(this.getContext().getCacheDir(), "RNVCache"), new LeastRecentlyUsedCacheEvictor((long) cacheSize*1024*1024), new StandaloneDatabaseProvider(this.getContext())); + cacheDataSourceFactory = + new CacheDataSource.Factory() + .setCache(simpleCache) + .setUpstreamDataSourceFactory(buildHttpDataSourceFactory(false)); + } releasePlayer(); initializePlayer(); } diff --git a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerViewManager.java b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerViewManager.java index 1099b8417f..5836e9f16e 100644 --- a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerViewManager.java +++ b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerViewManager.java @@ -61,7 +61,7 @@ public class ReactExoplayerViewManager extends ViewGroupManager { - // this.channelUp(); + !this.state.loop && this.channelUp(); }; toggleFullscreen() { @@ -759,7 +759,7 @@ class VideoPlayer extends Component { onAspectRatio={this.onAspectRatio} onReadyForDisplay={this.onReadyForDisplay} onBuffer={this.onVideoBuffer} - repeat + repeat={this.state.loop} selectedTextTrack={this.state.selectedTextTrack} selectedAudioTrack={this.state.selectedAudioTrack} playInBackground={false} @@ -768,7 +768,7 @@ class VideoPlayer extends Component { maxBufferMs: 50000, bufferForPlaybackMs: 2500, bufferForPlaybackAfterRebufferMs: 5000, - bufferSize: 200, + cacheSizeMB: 200, }} /> diff --git a/src/VideoNativeComponent.ts b/src/VideoNativeComponent.ts index 90032917de..c6b78c6a92 100644 --- a/src/VideoNativeComponent.ts +++ b/src/VideoNativeComponent.ts @@ -103,7 +103,7 @@ type BufferConfig = Readonly<{ maxHeapAllocationPercent?: number; minBackBufferMemoryReservePercent?: number; minBufferMemoryReservePercent?: number; - bufferSize?: number; + cacheSizeMB?: number; }>; type SelectedVideoTrack = Readonly<{ diff --git a/src/types/video.ts b/src/types/video.ts index 415c69c530..8d340007a5 100644 --- a/src/types/video.ts +++ b/src/types/video.ts @@ -68,6 +68,7 @@ export type BufferConfig = { maxHeapAllocationPercent?: number; minBackBufferMemoryReservePercent?: number; minBufferMemoryReservePercent?: number; + cacheSizeMB?: number; }; export enum SelectedTrackType { From e61fe193f01a3b82f9a1d8c420cefb9012696a7e Mon Sep 17 00:00:00 2001 From: lovegaoshi <106490582+lovegaoshi@users.noreply.github.com> Date: Mon, 19 Feb 2024 12:00:33 -0800 Subject: [PATCH 05/14] feat: singleton android cache --- .../common/toolbox/RNVSimpleCache.kt | 31 +++++++++++++++++++ .../exoplayer/ReactExoplayerView.java | 30 ++++++------------ 2 files changed, 41 insertions(+), 20 deletions(-) create mode 100644 android/src/main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt diff --git a/android/src/main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt b/android/src/main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt new file mode 100644 index 0000000000..75d350eff4 --- /dev/null +++ b/android/src/main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt @@ -0,0 +1,31 @@ +package com.brentvatne.common.toolbox + +import android.content.Context +import androidx.media3.database.StandaloneDatabaseProvider +import androidx.media3.datasource.DataSource +import androidx.media3.datasource.HttpDataSource +import androidx.media3.datasource.cache.CacheDataSource +import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor +import androidx.media3.datasource.cache.SimpleCache +import java.io.File + +object RNVSimpleCache { + // TODO: when to release? hwo to check if cache is released? + var simpleCache: SimpleCache? = null + var cacheDataSourceFactory: DataSource.Factory? = null + + fun setSimpleCache(context: Context, cacheSize: Int, factory: HttpDataSource.Factory) { + if (cacheDataSourceFactory != null || cacheSize == 0) return + simpleCache = SimpleCache( + File(context.cacheDir, "RNVCache"), + LeastRecentlyUsedCacheEvictor( + cacheSize.toLong() * 1024 * 1024 + ), + StandaloneDatabaseProvider(context) + ); + cacheDataSourceFactory = + CacheDataSource.Factory() + .setCache(simpleCache!!) + .setUpstreamDataSourceFactory(factory) + } +} diff --git a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java index 2bcf37cc1b..c22b66f4c7 100644 --- a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java +++ b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java @@ -42,10 +42,6 @@ import androidx.media3.common.TrackSelectionOverride; import androidx.media3.common.Tracks; import androidx.media3.common.util.Util; -import androidx.media3.database.StandaloneDatabaseProvider; -import androidx.media3.datasource.cache.CacheDataSource; -import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor; -import androidx.media3.datasource.cache.SimpleCache; import androidx.media3.datasource.DataSource; import androidx.media3.datasource.DataSpec; import androidx.media3.datasource.HttpDataSource; @@ -102,6 +98,7 @@ import com.brentvatne.common.api.VideoTrack; import com.brentvatne.common.react.VideoEventEmitter; import com.brentvatne.common.toolbox.DebugLog; +import com.brentvatne.common.toolbox.RNVSimpleCache; import com.brentvatne.react.R; import com.brentvatne.receiver.AudioBecomingNoisyReceiver; import com.brentvatne.receiver.BecomingNoisyListener; @@ -115,7 +112,6 @@ import com.google.ads.interactivemedia.v3.api.AdErrorEvent; import com.google.common.collect.ImmutableList; -import java.io.File; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookiePolicy; @@ -189,8 +185,6 @@ public class ReactExoplayerView extends FrameLayout implements private boolean hasDrmFailed = false; private boolean isUsingContentResolution = false; private boolean selectTrackWhenReady = false; - - private DataSource.Factory cacheDataSourceFactory; private int minBufferMs = DefaultLoadControl.DEFAULT_MIN_BUFFER_MS; private int maxBufferMs = DefaultLoadControl.DEFAULT_MAX_BUFFER_MS; private int bufferForPlaybackMs = DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_MS; @@ -641,8 +635,8 @@ private void initializePlayerCore(ReactExoplayerView self) { .setAdErrorListener(this) .build(); DefaultMediaSourceFactory mediaSourceFactory = new DefaultMediaSourceFactory(mediaDataSourceFactory); - if (cacheDataSourceFactory != null) { - mediaSourceFactory.setDataSourceFactory(cacheDataSourceFactory); + if (RNVSimpleCache.INSTANCE.getCacheDataSourceFactory() != null) { + mediaSourceFactory.setDataSourceFactory(RNVSimpleCache.INSTANCE.getCacheDataSourceFactory()); } if (adsLoader != null) { @@ -839,13 +833,13 @@ private MediaSource buildMediaSource(Uri uri, String overrideExtension, DrmSessi ); break; case CONTENT_TYPE_OTHER: - if (cacheDataSourceFactory == null) { + if (RNVSimpleCache.INSTANCE.getCacheDataSourceFactory() == null) { mediaSourceFactory = new ProgressiveMediaSource.Factory( mediaDataSourceFactory ); } else { mediaSourceFactory = new ProgressiveMediaSource.Factory( - cacheDataSourceFactory + RNVSimpleCache.INSTANCE.getCacheDataSourceFactory() ); } @@ -2049,15 +2043,11 @@ public void setBufferConfig(int newMinBufferMs, int newMaxBufferMs, int newBuffe maxHeapAllocationPercent = newMaxHeapAllocationPercent; minBackBufferMemoryReservePercent = newMinBackBufferMemoryReservePercent; minBufferMemoryReservePercent = newMinBufferMemoryReservePercent; - if (cacheSize == 0) { - cacheDataSourceFactory = null; - } else { - SimpleCache simpleCache = new SimpleCache(new File(this.getContext().getCacheDir(), "RNVCache"), new LeastRecentlyUsedCacheEvictor((long) cacheSize*1024*1024), new StandaloneDatabaseProvider(this.getContext())); - cacheDataSourceFactory = - new CacheDataSource.Factory() - .setCache(simpleCache) - .setUpstreamDataSourceFactory(buildHttpDataSourceFactory(false)); - } + RNVSimpleCache.INSTANCE.setSimpleCache( + this.getContext(), + cacheSize, + buildHttpDataSourceFactory(false) + ); releasePlayer(); initializePlayer(); } From f7cc2ad4fce722c91ad7bc03dba99499724917cb Mon Sep 17 00:00:00 2001 From: lovegaoshi <106490582+lovegaoshi@users.noreply.github.com> Date: Fri, 1 Mar 2024 11:00:08 -0800 Subject: [PATCH 06/14] fix: local cache resolve --- .../main/java/com/brentvatne/exoplayer/ReactExoplayerView.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java index c22b66f4c7..f1b5e16723 100644 --- a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java +++ b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java @@ -833,7 +833,8 @@ private MediaSource buildMediaSource(Uri uri, String overrideExtension, DrmSessi ); break; case CONTENT_TYPE_OTHER: - if (RNVSimpleCache.INSTANCE.getCacheDataSourceFactory() == null) { + if (uri.toString().startsWith("file://") || + RNVSimpleCache.INSTANCE.getCacheDataSourceFactory() == null) { mediaSourceFactory = new ProgressiveMediaSource.Factory( mediaDataSourceFactory ); From e36de4e8a896771bd255d54ff47cc06cd3186530 Mon Sep 17 00:00:00 2001 From: lovegaoshi <106490582+lovegaoshi@users.noreply.github.com> Date: Fri, 8 Mar 2024 08:49:16 -0800 Subject: [PATCH 07/14] fix: lint --- .../main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/src/main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt b/android/src/main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt index 75d350eff4..c0e923c711 100644 --- a/android/src/main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt +++ b/android/src/main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt @@ -22,7 +22,7 @@ object RNVSimpleCache { cacheSize.toLong() * 1024 * 1024 ), StandaloneDatabaseProvider(context) - ); + ) cacheDataSourceFactory = CacheDataSource.Factory() .setCache(simpleCache!!) From b4a434656c41c27cd7f3b8851878e3ca89685940 Mon Sep 17 00:00:00 2001 From: lovegaoshi <106490582+lovegaoshi@users.noreply.github.com> Date: Fri, 8 Mar 2024 08:56:56 -0800 Subject: [PATCH 08/14] docs: android cache --- docs/pages/component/props.mdx | 1 + docs/pages/other/caching.md | 22 +++++++++++++++------- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/docs/pages/component/props.mdx b/docs/pages/component/props.mdx index 7bf21d57dd..956823e685 100644 --- a/docs/pages/component/props.mdx +++ b/docs/pages/component/props.mdx @@ -91,6 +91,7 @@ bufferConfig={{ maxBufferMs: 50000, bufferForPlaybackMs: 2500, bufferForPlaybackAfterRebufferMs: 5000 + cacheSizeMB: 0 }} ``` diff --git a/docs/pages/other/caching.md b/docs/pages/other/caching.md index f955db367d..f157d752d0 100644 --- a/docs/pages/other/caching.md +++ b/docs/pages/other/caching.md @@ -1,22 +1,30 @@ # Caching -Caching is currently only supported on `iOS` platforms with a CocoaPods setup. +Caching is supported on `iOS` platforms with a CocoaPods setup, and on `android` using `SimpleCache`. -## Technology +## Android + +Android uses a LRU `SimpleCache` with a variable cache size that can be specified by bufferConfig - cacheSizeMB. This creates a folder named `RNVCache` in the app's `cache` folder. Do note RNV does not yet offer a native call to flush the cache yet, users can expect the cache to be flushed by cleaning the app's cache. + +In addition, this resolves RNV6's repeated source URI call problem when looping a video on Android. + +## iOS + +### Technology The cache is backed by [SPTPersistentCache](https://github.com/spotify/SPTPersistentCache) and [DVAssetLoaderDelegate](https://github.com/vdugnist/DVAssetLoaderDelegate). -## How Does It Work +### How Does It Work The caching is based on the url of the asset. -SPTPersistentCache is a LRU ([Least Recently Used](https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU))) cache. +SPTPersistentCache is a LRU ([Least Recently Used]()) cache. -## Restrictions +### Restrictions -Currently, caching is only supported for URLs that end in a `.mp4`, `.m4v`, or `.mov` extension. In future versions, URLs that end in a query string (e.g. test.mp4?resolution=480p) will be support once dependencies allow access to the `Content-Type` header. At this time, HLS playlists (.m3u8) and videos that sideload text tracks are not supported and will bypass the cache. +Currently, caching is only supported for URLs that end in a `.mp4`, `.m4v`, or `.mov` extension. In future versions, URLs that end in a query string (e.g. test.mp4?resolution=480p) will be support once dependencies allow access to the `Content-Type` header. At this time, HLS playlists (.m3u8) and videos that sideload text tracks are not supported and will bypass the cache. You will also receive warnings in the Xcode logs by using the `debug` mode. So if you are not 100% sure if your video is cached, check your Xcode logs! By default files expire after 30 days and the maximum cache size is 100mb. -In a future release the cache might have more configurable options. \ No newline at end of file +In a future release the cache might have more configurable options. From 3eae85d52b0ba0798ba25a9954d73e43f1881b64 Mon Sep 17 00:00:00 2001 From: lovegaoshi <106490582+lovegaoshi@users.noreply.github.com> Date: Fri, 8 Mar 2024 09:00:07 -0800 Subject: [PATCH 09/14] chore: merge conflict --- src/VideoNativeComponent.ts | 418 ------------------------------------ 1 file changed, 418 deletions(-) delete mode 100644 src/VideoNativeComponent.ts diff --git a/src/VideoNativeComponent.ts b/src/VideoNativeComponent.ts deleted file mode 100644 index 7d04438873..0000000000 --- a/src/VideoNativeComponent.ts +++ /dev/null @@ -1,418 +0,0 @@ -import type { - HostComponent, - NativeSyntheticEvent, - ViewProps, -} from 'react-native'; -import {NativeModules, requireNativeComponent} from 'react-native'; -import type ResizeMode from './types/ResizeMode'; -import type FilterType from './types/FilterType'; -import type Orientation from './types/Orientation'; -import type { - AdEvent, - EnumValues, - OnTextTrackDataChangedData, - OnTextTracksTypeData, -} from './types'; - -// -------- There are types for native component (future codegen) -------- -// if you are looking for types for react component, see src/types/video.ts - -type Headers = Record; - -type VideoSrc = Readonly<{ - uri?: string; - isNetwork?: boolean; - isAsset?: boolean; - shouldCache?: boolean; - type?: string; - mainVer?: number; - patchVer?: number; - requestHeaders?: Headers; - startPosition?: number; - cropStart?: number; - cropEnd?: number; - title?: string; - subtitle?: string; - description?: string; - customImageUri?: string; -}>; - -export type Filter = - | 'None' - | 'CIColorInvert' - | 'CIColorMonochrome' - | 'CIColorPosterize' - | 'CIFalseColor' - | 'CIMaximumComponent' - | 'CIMinimumComponent' - | 'CIPhotoEffectChrome' - | 'CIPhotoEffectFade' - | 'CIPhotoEffectInstant' - | 'CIPhotoEffectMono' - | 'CIPhotoEffectNoir' - | 'CIPhotoEffectProcess' - | 'CIPhotoEffectTonal' - | 'CIPhotoEffectTransfer' - | 'CISepiaTone'; - -export type DRMType = 'widevine' | 'playready' | 'clearkey' | 'fairplay'; - -type DebugConfig = Readonly<{ - enable?: boolean; - thread?: boolean; -}>; - -type Drm = Readonly<{ - type?: DRMType; - licenseServer?: string; - headers?: Headers; - contentId?: string; // ios - certificateUrl?: string; // ios - base64Certificate?: boolean; // ios default: false - useExternalGetLicense?: boolean; // ios -}>; - -type TextTracks = ReadonlyArray< - Readonly<{ - title: string; - language: string; - type: string; - uri: string; - }> ->; - -type TextTrackType = 'system' | 'disabled' | 'title' | 'language' | 'index'; - -type SelectedTextTrack = Readonly<{ - type: TextTrackType; - value?: string | number; -}>; - -type AudioTrackType = 'system' | 'disabled' | 'title' | 'language' | 'index'; - -type SelectedAudioTrack = Readonly<{ - type: AudioTrackType; - value?: string | number; -}>; - -export type Seek = Readonly<{ - time: number; - tolerance?: number; -}>; - -type BufferConfig = Readonly<{ - minBufferMs?: number; - maxBufferMs?: number; - bufferForPlaybackMs?: number; - bufferForPlaybackAfterRebufferMs?: number; - maxHeapAllocationPercent?: number; - minBackBufferMemoryReservePercent?: number; - minBufferMemoryReservePercent?: number; - cacheSizeMB?: number; -}>; - -type SelectedVideoTrack = Readonly<{ - type: 'auto' | 'disabled' | 'resolution' | 'index'; - value?: number; -}>; - -type SubtitleStyle = Readonly<{ - fontSize?: number; - paddingTop?: number; - paddingBottom?: number; - paddingLeft?: number; - paddingRight?: number; -}>; - -export type OnLoadData = Readonly<{ - currentTime: number; - duration: number; - naturalSize: Readonly<{ - width: number; - height: number; - orientation: Orientation; - }>; -}> & - OnAudioTracksData & - OnTextTracksData; - -export type OnLoadStartData = Readonly<{ - isNetwork: boolean; - type: string; - uri: string; -}>; - -export type OnVideoAspectRatioData = Readonly<{ - width: number; - height: number; -}>; - -export type OnBufferData = Readonly<{isBuffering: boolean}>; - -export type OnProgressData = Readonly<{ - currentTime: number; - playableDuration: number; - seekableDuration: number; -}>; - -export type OnBandwidthUpdateData = Readonly<{ - bitrate: number; - width?: number; - height?: number; - trackId?: number; -}>; - -export type OnSeekData = Readonly<{ - currentTime: number; - seekTime: number; -}>; - -export type OnPlaybackStateChangedData = Readonly<{ - isPlaying: boolean; -}>; - -export type OnTimedMetadataData = Readonly<{ - metadata: ReadonlyArray< - Readonly<{ - value?: string; - identifier: string; - }> - >; -}>; - -export type OnAudioTracksData = Readonly<{ - audioTracks: ReadonlyArray< - Readonly<{ - index: number; - title?: string; - language?: string; - bitrate?: number; - type?: string; - selected?: boolean; - }> - >; -}>; - -export type OnTextTracksData = Readonly<{ - textTracks: ReadonlyArray< - Readonly<{ - index: number; - title?: string; - language?: string; - /** - * iOS only supports VTT, Android supports all 3 - */ - type?: OnTextTracksTypeData; - selected?: boolean; - }> - >; -}>; - -export type OnVideoTracksData = Readonly<{ - videoTracks: ReadonlyArray< - Readonly<{ - trackId: number; - codecs?: string; - width?: number; - height?: number; - bitrate?: number; - selected?: boolean; - }> - >; -}>; - -export type OnPlaybackData = Readonly<{ - playbackRate: number; -}>; - -export type onVolumeChangeData = Readonly<{ - volume: number; -}>; - -export type OnExternalPlaybackChangeData = Readonly<{ - isExternalPlaybackActive: boolean; -}>; - -export type OnGetLicenseData = Readonly<{ - licenseUrl: string; - contentId: string; - spcBase64: string; -}>; - -export type OnPictureInPictureStatusChangedData = Readonly<{ - isActive: boolean; -}>; - -export type OnReceiveAdEventData = Readonly<{ - data?: Record; - event: AdEvent; -}>; - -export type OnVideoErrorData = Readonly<{ - error: OnVideoErrorDataDetails; - target?: number; // ios -}>; - -export type OnVideoErrorDataDetails = Readonly<{ - errorString?: string; // android - errorException?: string; // android - errorStackTrace?: string; // android - errorCode?: string; // android - error?: string; // ios - code?: number; // ios - localizedDescription?: string; // ios - localizedFailureReason?: string; // ios - localizedRecoverySuggestion?: string; // ios - domain?: string; // ios -}>; - -export type OnAudioFocusChangedData = Readonly<{ - hasAudioFocus: boolean; -}>; - -export interface VideoNativeProps extends ViewProps { - src?: VideoSrc; - drm?: Drm; - adTagUrl?: string; - allowsExternalPlayback?: boolean; // ios, true - maxBitRate?: number; - resizeMode?: EnumValues; - repeat?: boolean; - automaticallyWaitsToMinimizeStalling?: boolean; - textTracks?: TextTracks; - selectedTextTrack?: SelectedTextTrack; - selectedAudioTrack?: SelectedAudioTrack; - paused?: boolean; - muted?: boolean; - controls?: boolean; - filter?: EnumValues; - filterEnabled?: boolean; - volume?: number; // default 1.0 - playInBackground?: boolean; - preventsDisplaySleepDuringVideoPlayback?: boolean; - preferredForwardBufferDuration?: number; //ios, 0 - playWhenInactive?: boolean; // ios, false - pictureInPicture?: boolean; // ios, false - ignoreSilentSwitch?: 'inherit' | 'ignore' | 'obey'; // ios, 'inherit' - mixWithOthers?: 'inherit' | 'mix' | 'duck'; // ios, 'inherit' - rate?: number; - fullscreen?: boolean; // ios, false - fullscreenAutorotate?: boolean; - fullscreenOrientation?: 'all' | 'landscape' | 'portrait'; - progressUpdateInterval?: number; - restoreUserInterfaceForPIPStopCompletionHandler?: boolean; - localSourceEncryptionKeyScheme?: string; - debug?: DebugConfig; - - backBufferDurationMs?: number; // Android - bufferConfig?: BufferConfig; // Android - contentStartTime?: number; // Android - currentPlaybackTime?: number; // Android - disableDisconnectError?: boolean; // Android - focusable?: boolean; // Android - hideShutterView?: boolean; // Android - minLoadRetryCount?: number; // Android - reportBandwidth?: boolean; //Android - selectedVideoTrack?: SelectedVideoTrack; // android - subtitleStyle?: SubtitleStyle; // android - trackId?: string; // Android - useTextureView?: boolean; // Android - useSecureView?: boolean; // Android - onVideoLoad?: (event: NativeSyntheticEvent) => void; - onVideoLoadStart?: (event: NativeSyntheticEvent) => void; - onVideoAspectRatio?: ( - event: NativeSyntheticEvent, - ) => void; - onVideoBuffer?: (event: NativeSyntheticEvent) => void; - onVideoError?: (event: NativeSyntheticEvent) => void; - onVideoProgress?: (event: NativeSyntheticEvent) => void; - onVideoBandwidthUpdate?: ( - event: NativeSyntheticEvent, - ) => void; - onVideoSeek?: (event: NativeSyntheticEvent) => void; - onVideoEnd?: (event: NativeSyntheticEvent>) => void; // all - onVideoAudioBecomingNoisy?: ( - event: NativeSyntheticEvent>, - ) => void; - onVideoFullscreenPlayerWillPresent?: ( - event: NativeSyntheticEvent>, - ) => void; // ios, android - onVideoFullscreenPlayerDidPresent?: ( - event: NativeSyntheticEvent>, - ) => void; // ios, android - onVideoFullscreenPlayerWillDismiss?: ( - event: NativeSyntheticEvent>, - ) => void; // ios, android - onVideoFullscreenPlayerDidDismiss?: ( - event: NativeSyntheticEvent>, - ) => void; // ios, android - onReadyForDisplay?: (event: NativeSyntheticEvent>) => void; - onPlaybackRateChange?: (event: NativeSyntheticEvent) => void; // all - onVolumeChange?: (event: NativeSyntheticEvent) => void; // android, ios - onVideoExternalPlaybackChange?: ( - event: NativeSyntheticEvent, - ) => void; - onGetLicense?: (event: NativeSyntheticEvent) => void; - onPictureInPictureStatusChanged?: ( - event: NativeSyntheticEvent, - ) => void; - onRestoreUserInterfaceForPictureInPictureStop?: ( - event: NativeSyntheticEvent>, - ) => void; - onReceiveAdEvent?: ( - event: NativeSyntheticEvent, - ) => void; - onVideoPlaybackStateChanged?: ( - event: NativeSyntheticEvent, - ) => void; // android only - onVideoIdle?: (event: NativeSyntheticEvent) => void; // android only (nowhere in document, so do not use as props. just type declaration) - onAudioFocusChanged?: ( - event: NativeSyntheticEvent, - ) => void; // android only (nowhere in document, so do not use as props. just type declaration) - onTimedMetadata?: (event: NativeSyntheticEvent) => void; // ios, android - onAudioTracks?: (event: NativeSyntheticEvent) => void; // android - onTextTracks?: (event: NativeSyntheticEvent) => void; // android - onTextTrackDataChanged?: ( - event: NativeSyntheticEvent, - ) => void; // iOS - onVideoTracks?: (event: NativeSyntheticEvent) => void; // android -} - -export type VideoComponentType = HostComponent; - -export type VideoSaveData = { - uri: string; -}; - -export interface VideoManagerType { - save: (option: object, reactTag: number) => Promise; - setPlayerPauseState: (paused: boolean, reactTag: number) => Promise; - setLicenseResult: ( - result: string, - licenseUrl: string, - reactTag: number, - ) => Promise; - setLicenseResultError: ( - error: string, - licenseUrl: string, - reactTag: number, - ) => Promise; -} - -export interface VideoDecoderPropertiesType { - getWidevineLevel: () => Promise; - isCodecSupported: ( - mimeType: string, - width: number, - height: number, - ) => Promise<'unsupported' | 'hardware' | 'software'>; - isHEVCSupported: () => Promise<'unsupported' | 'hardware' | 'software'>; -} - -export const VideoManager = NativeModules.VideoManager as VideoManagerType; -export const VideoDecoderProperties = - NativeModules.VideoDecoderProperties as VideoDecoderPropertiesType; - -export default requireNativeComponent( - 'RCTVideo', -) as VideoComponentType; From 426d08c58cc3a81b244755f6caa89eb94b705722 Mon Sep 17 00:00:00 2001 From: lovegaoshi <106490582+lovegaoshi@users.noreply.github.com> Date: Mon, 11 Mar 2024 13:45:35 -0700 Subject: [PATCH 10/14] fix: lint --- .../main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/android/src/main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt b/android/src/main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt index c0e923c711..56f952e95f 100644 --- a/android/src/main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt +++ b/android/src/main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt @@ -10,11 +10,11 @@ import androidx.media3.datasource.cache.SimpleCache import java.io.File object RNVSimpleCache { - // TODO: when to release? hwo to check if cache is released? + // TODO: when to release? how to check if cache is released? var simpleCache: SimpleCache? = null var cacheDataSourceFactory: DataSource.Factory? = null - fun setSimpleCache(context: Context, cacheSize: Int, factory: HttpDataSource.Factory) { + fun setSimpleCache(context: Context, cacheSize: Int, factory: HttpDataSource.Factory) { if (cacheDataSourceFactory != null || cacheSize == 0) return simpleCache = SimpleCache( File(context.cacheDir, "RNVCache"), From f41ebd6de5f20a53268ed59cba5be57d0ec5f4a3 Mon Sep 17 00:00:00 2001 From: lovegaoshi <106490582+lovegaoshi@users.noreply.github.com> Date: Mon, 1 Apr 2024 09:11:02 -0700 Subject: [PATCH 11/14] chore: useCache button --- .../ReactExoplayerSimpleCache.kt} | 2 +- .../com/brentvatne/exoplayer/ReactExoplayerView.java | 2 -- examples/basic/src/VideoPlayer.tsx | 10 +++++++++- 3 files changed, 10 insertions(+), 4 deletions(-) rename android/src/main/java/com/brentvatne/{common/toolbox/RNVSimpleCache.kt => exoplayer/ReactExoplayerSimpleCache.kt} (96%) diff --git a/android/src/main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerSimpleCache.kt similarity index 96% rename from android/src/main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt rename to android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerSimpleCache.kt index 56f952e95f..f41c897245 100644 --- a/android/src/main/java/com/brentvatne/common/toolbox/RNVSimpleCache.kt +++ b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerSimpleCache.kt @@ -1,4 +1,4 @@ -package com.brentvatne.common.toolbox +package com.brentvatne.exoplayer import android.content.Context import androidx.media3.database.StandaloneDatabaseProvider diff --git a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java index d0136bcb8a..d76a3f5ed8 100644 --- a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java +++ b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java @@ -99,11 +99,9 @@ import com.brentvatne.common.api.VideoTrack; import com.brentvatne.common.react.VideoEventEmitter; import com.brentvatne.common.toolbox.DebugLog; -import com.brentvatne.common.toolbox.RNVSimpleCache; import com.brentvatne.react.R; import com.brentvatne.receiver.AudioBecomingNoisyReceiver; import com.brentvatne.receiver.BecomingNoisyListener; -import com.facebook.react.bridge.Dynamic; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; diff --git a/examples/basic/src/VideoPlayer.tsx b/examples/basic/src/VideoPlayer.tsx index 9203cd6d80..a868674a5f 100644 --- a/examples/basic/src/VideoPlayer.tsx +++ b/examples/basic/src/VideoPlayer.tsx @@ -66,6 +66,7 @@ interface StateType { srcListId: number; loop: boolean; showRNVControls: boolean; + useCache: boolean; } class VideoPlayer extends Component { @@ -93,6 +94,7 @@ class VideoPlayer extends Component { srcListId: 0, loop: false, showRNVControls: false, + useCache: false, }; seekerWidth = 0; @@ -622,6 +624,12 @@ class VideoPlayer extends Component { }} text="decoderInfo" /> + { + this.state.useCache = !this.state.useCache; + }} + text="use Cache" + /> ) : null} From 67c78f9f59ed27c43e1868aa76fa8ed14c79548a Mon Sep 17 00:00:00 2001 From: Olivier Bouillet Date: Tue, 16 Apr 2024 10:12:31 +0200 Subject: [PATCH 12/14] chore: fix state in the sample --- examples/basic/src/VideoPlayer.tsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/basic/src/VideoPlayer.tsx b/examples/basic/src/VideoPlayer.tsx index 20ab14ffff..b05f0868d9 100644 --- a/examples/basic/src/VideoPlayer.tsx +++ b/examples/basic/src/VideoPlayer.tsx @@ -654,10 +654,12 @@ class VideoPlayer extends Component { text="decoderInfo" /> { - this.state.useCache = !this.state.useCache; + this.setState({useCache: !this.state.useCache}); }} - text="use Cache" + selectedText="enable cache" + unselectedText="disable cache" /> ) : null} From 51aac8c457240afc3f2cf8517dd62294fcd9e01d Mon Sep 17 00:00:00 2001 From: lovegaoshi <106490582+lovegaoshi@users.noreply.github.com> Date: Thu, 18 Apr 2024 09:00:05 -0700 Subject: [PATCH 13/14] fix: cache factory --- .../exoplayer/ReactExoplayerSimpleCache.kt | 2 +- .../exoplayer/ReactExoplayerView.java | 25 ++++++++++++------- docs/pages/other/caching.md | 2 +- 3 files changed, 18 insertions(+), 11 deletions(-) diff --git a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerSimpleCache.kt b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerSimpleCache.kt index f41c897245..cec4b898ff 100644 --- a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerSimpleCache.kt +++ b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerSimpleCache.kt @@ -11,7 +11,7 @@ import java.io.File object RNVSimpleCache { // TODO: when to release? how to check if cache is released? - var simpleCache: SimpleCache? = null + private var simpleCache: SimpleCache? = null var cacheDataSourceFactory: DataSource.Factory? = null fun setSimpleCache(context: Context, cacheSize: Int, factory: HttpDataSource.Factory) { diff --git a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java index d76a3f5ed8..a5852a13db 100644 --- a/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java +++ b/android/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java @@ -195,6 +195,7 @@ public class ReactExoplayerView extends FrameLayout implements private double minBufferMemoryReservePercent = ReactExoplayerView.DEFAULT_MIN_BUFFER_MEMORY_RESERVE; private Handler mainHandler; private Runnable mainRunnable; + private DataSource.Factory cacheDataSourceFactory; // Props from React private Uri srcUri; @@ -635,8 +636,8 @@ private void initializePlayerCore(ReactExoplayerView self) { .setAdErrorListener(this) .build(); DefaultMediaSourceFactory mediaSourceFactory = new DefaultMediaSourceFactory(mediaDataSourceFactory); - if (RNVSimpleCache.INSTANCE.getCacheDataSourceFactory() != null) { - mediaSourceFactory.setDataSourceFactory(RNVSimpleCache.INSTANCE.getCacheDataSourceFactory()); + if (cacheDataSourceFactory != null) { + mediaSourceFactory.setDataSourceFactory(cacheDataSourceFactory); } if (adsLoader != null) { @@ -834,13 +835,13 @@ private MediaSource buildMediaSource(Uri uri, String overrideExtension, DrmSessi break; case CONTENT_TYPE_OTHER: if (uri.toString().startsWith("file://") || - RNVSimpleCache.INSTANCE.getCacheDataSourceFactory() == null) { + cacheDataSourceFactory == null) { mediaSourceFactory = new ProgressiveMediaSource.Factory( mediaDataSourceFactory ); } else { mediaSourceFactory = new ProgressiveMediaSource.Factory( - RNVSimpleCache.INSTANCE.getCacheDataSourceFactory() + cacheDataSourceFactory ); } @@ -2032,11 +2033,17 @@ public void setBufferConfig(int newMinBufferMs, int newMaxBufferMs, int newBuffe maxHeapAllocationPercent = newMaxHeapAllocationPercent; minBackBufferMemoryReservePercent = newMinBackBufferMemoryReservePercent; minBufferMemoryReservePercent = newMinBufferMemoryReservePercent; - RNVSimpleCache.INSTANCE.setSimpleCache( - this.getContext(), - cacheSize, - buildHttpDataSourceFactory(false) - ); + if (cacheSize > 0) { + RNVSimpleCache.INSTANCE.setSimpleCache( + this.getContext(), + cacheSize, + buildHttpDataSourceFactory(false) + ); + cacheDataSourceFactory = RNVSimpleCache.INSTANCE.getCacheDataSourceFactory(); + } else { + cacheDataSourceFactory = null; + } + backBufferDurationMs = newBackBufferDurationMs; releasePlayer(); initializePlayer(); diff --git a/docs/pages/other/caching.md b/docs/pages/other/caching.md index f157d752d0..34361e66a8 100644 --- a/docs/pages/other/caching.md +++ b/docs/pages/other/caching.md @@ -4,7 +4,7 @@ Caching is supported on `iOS` platforms with a CocoaPods setup, and on `android` ## Android -Android uses a LRU `SimpleCache` with a variable cache size that can be specified by bufferConfig - cacheSizeMB. This creates a folder named `RNVCache` in the app's `cache` folder. Do note RNV does not yet offer a native call to flush the cache yet, users can expect the cache to be flushed by cleaning the app's cache. +Android uses a LRU `SimpleCache` with a variable cache size that can be specified by bufferConfig - cacheSizeMB. This creates a folder named `RNVCache` in the app's `cache` folder. Do note RNV does not yet offer a native call to flush the cache, it can be flushed by clearing the app's cache. In addition, this resolves RNV6's repeated source URI call problem when looping a video on Android. From 629349e1b7ab79fc7d9317ad5cb08f6d0cdc733c Mon Sep 17 00:00:00 2001 From: lovegaoshi <106490582+lovegaoshi@users.noreply.github.com> Date: Fri, 26 Apr 2024 18:52:31 -0700 Subject: [PATCH 14/14] chore: update cacheSizeMB docs --- docs/pages/component/props.mdx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/pages/component/props.mdx b/docs/pages/component/props.mdx index bf719e7980..0b116f8a12 100644 --- a/docs/pages/component/props.mdx +++ b/docs/pages/component/props.mdx @@ -63,7 +63,7 @@ Adjust the buffer settings. This prop takes an object with one or more of the pr | maxHeapAllocationPercent | number | The percentage of available heap that the video can use to buffer, between 0 and 1 | | minBackBufferMemoryReservePercent | number | The percentage of available app memory at which during startup the back buffer will be disabled, between 0 and 1 | | minBufferMemoryReservePercent | number | The percentage of available app memory to keep in reserve that prevents buffer from using it, between 0 and 1 | -| cacheSizeMB | number | Cache size in MB, it will allow applications to store video data for a while in the cache folder, it is useful to decrease bandwidth usage when repeating small videos. Android only. | +| cacheSizeMB | number | Cache size in MB, enabling this to prevent new src requests and save bandwidth while repeating videos, or 0 to disable. Android only. | Example with default values: @@ -78,6 +78,8 @@ bufferConfig={{ }} ``` +Please note that the Android cache is a global cache that is shared among all components; individual components can still opt out of caching behavior by setting cacheSizeMB to 0, but multiple components with a positive cacheSizeMB will be sharing the same one, and the cache size will always be the first value set; it will not change during the app's lifecycle. + ### `chapters`