Allow audio output via earpiece

This commit is contained in:
Craig Martin 2023-04-02 14:02:56 -04:00
parent 05864dc64a
commit daabb91475
8 changed files with 331 additions and 198 deletions

8
API.md
View File

@ -294,6 +294,7 @@ var styles = StyleSheet.create({
| [adTagUrl](#adTagUrl) | Android, iOS |
| [allowsExternalPlayback](#allowsexternalplayback) | iOS |
| [audioOnly](#audioonly) | All |
| [audioOutput](#audioOutput) | Android, iOS |
| [automaticallyWaitsToMinimizeStalling](#automaticallyWaitsToMinimizeStalling) | iOS |
| [backBufferDurationMs](#backBufferDurationMs) | Android |
| [bufferConfig](#bufferconfig) | Android |
@ -417,6 +418,13 @@ 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
Platforms: Android, iOS
#### 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

View File

@ -1,5 +1,7 @@
## Changelog
- Feature: playing audio over earpiece [#2887](https://github.com/react-native-video/react-native-video/issues/2887)
### Version 6.0.0-alpha.5
- iOS: ensure controls are not displayed when disabled by user [#3017](https://github.com/react-native-video/react-native-video/pull/3017)

View File

@ -520,6 +520,7 @@ Video.propTypes = {
disableBuffering: PropTypes.bool,
controls: PropTypes.bool,
audioOnly: PropTypes.bool,
audioOutput: PropTypes.oneOf(['earpiece', 'speaker']),
currentTime: PropTypes.number,
fullscreenAutorotate: PropTypes.bool,
fullscreenOrientation: PropTypes.oneOf(['all', 'landscape', 'portrait']),

View File

@ -47,6 +47,7 @@ import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.Tracks;
import com.google.android.exoplayer2.audio.AudioAttributes;
import com.google.android.exoplayer2.drm.DefaultDrmSessionManager;
import com.google.android.exoplayer2.drm.DefaultDrmSessionManagerProvider;
import com.google.android.exoplayer2.drm.DrmSessionEventListener;
@ -135,6 +136,33 @@ class ReactExoplayerView extends FrameLayout implements
DEFAULT_COOKIE_MANAGER.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
}
@SuppressLint("InlinedApi")
public enum AudioOutput {
SPEAKER("speaker", C.STREAM_TYPE_MUSIC),
EARPIECE("earpiece", C.STREAM_TYPE_VOICE_CALL);
private final int streamType;
private final String mName;
AudioOutput(final String name, int stream) {
mName = name;
streamType = stream;
}
public static AudioOutput get(String name) {
for (AudioOutput d : values()) {
if (d.mName.equalsIgnoreCase(name))
return d;
}
return SPEAKER;
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + this.mName + ", " + streamType + ")";
}
}
private final VideoEventEmitter eventEmitter;
private final ReactExoplayerConfig config;
private final DefaultBandwidthMeter bandwidthMeter;
@ -161,6 +189,7 @@ class ReactExoplayerView extends FrameLayout implements
private boolean muted = false;
private boolean hasAudioFocus = false;
private float rate = 1f;
private AudioOutput audioOutput = AudioOutput.SPEAKER;
private float audioVolume = 1f;
private int minLoadRetryCount = 3;
private int maxBitRate = 0;
@ -236,7 +265,8 @@ class ReactExoplayerView extends FrameLayout implements
lastPos = pos;
lastBufferDuration = bufferedDuration;
lastDuration = duration;
eventEmitter.progressChanged(pos, bufferedDuration, player.getDuration(), getPositionInFirstPeriodMsForCurrentWindow(pos));
eventEmitter.progressChanged(pos, bufferedDuration, player.getDuration(),
getPositionInFirstPeriodMsForCurrentWindow(pos));
}
msg = obtainMessage(SHOW_PROGRESS);
sendMessageDelayed(msg, Math.round(mProgressUpdateInterval));
@ -307,7 +337,8 @@ class ReactExoplayerView extends FrameLayout implements
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
/* We want to be able to continue playing audio when switching tabs.
/*
* We want to be able to continue playing audio when switching tabs.
* Leave this here in case it causes issues.
*/
// stopPlayback();
@ -363,7 +394,8 @@ class ReactExoplayerView extends FrameLayout implements
* Toggling the visibility of the player control view
*/
private void togglePlayerControlVisibility() {
if(player == null) return;
if (player == null)
return;
reLayout(playerControlView);
if (playerControlView.isVisible()) {
playerControlView.hide();
@ -381,7 +413,8 @@ class ReactExoplayerView extends FrameLayout implements
}
if (fullScreenPlayerView == null) {
fullScreenPlayerView = new FullScreenPlayerView(getContext(), exoPlayerView, playerControlView, new OnBackPressedCallback(true) {
fullScreenPlayerView = new FullScreenPlayerView(getContext(), exoPlayerView, playerControlView,
new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
setFullscreen(false);
@ -442,14 +475,16 @@ class ReactExoplayerView extends FrameLayout implements
pauseButton.setVisibility(INVISIBLE);
}
reLayout(playPauseControlContainer);
//Remove this eventListener once its executed. since UI will work fine once after the reLayout is done
// Remove this eventListener once its executed. since UI will work fine once
// after the reLayout is done
player.removeListener(eventListener);
}
@Override
public void onPlayWhenReadyChanged(boolean playWhenReady, int reason) {
reLayout(playPauseControlContainer);
//Remove this eventListener once its executed. since UI will work fine once after the reLayout is done
// Remove this eventListener once its executed. since UI will work fine once
// after the reLayout is done
player.removeListener(eventListener);
}
};
@ -460,7 +495,8 @@ class ReactExoplayerView extends FrameLayout implements
* Adding Player control to the frame layout
*/
private void addPlayerControl() {
if(playerControlView == null) return;
if (playerControlView == null)
return;
LayoutParams layoutParams = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
@ -475,12 +511,15 @@ class ReactExoplayerView extends FrameLayout implements
/**
* Update the layout
*
* @param view view needs to update layout
*
* This is a workaround for the open bug in react-native: https://github.com/facebook/react-native/issues/17968
* This is a workaround for the open bug in react-native:
* https://github.com/facebook/react-native/issues/17968
*/
private void reLayout(View view) {
if (view == null) return;
if (view == null)
return;
view.measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
view.layout(view.getLeft(), view.getTop(), view.getMeasuredWidth(), view.getMeasuredHeight());
@ -489,7 +528,10 @@ class ReactExoplayerView extends FrameLayout implements
private class RNVLoadControl extends DefaultLoadControl {
private int availableHeapInBytes = 0;
private Runtime runtime;
public RNVLoadControl(DefaultAllocator allocator, int minBufferMs, int maxBufferMs, int bufferForPlaybackMs, int bufferForPlaybackAfterRebufferMs, int targetBufferBytes, boolean prioritizeTimeOverSizeThresholds, int backBufferDurationMs, boolean retainBackBufferFromKeyframe) {
public RNVLoadControl(DefaultAllocator allocator, int minBufferMs, int maxBufferMs, int bufferForPlaybackMs,
int bufferForPlaybackAfterRebufferMs, int targetBufferBytes, boolean prioritizeTimeOverSizeThresholds,
int backBufferDurationMs, boolean retainBackBufferFromKeyframe) {
super(allocator,
minBufferMs,
maxBufferMs,
@ -500,8 +542,10 @@ class ReactExoplayerView extends FrameLayout implements
backBufferDurationMs,
retainBackBufferFromKeyframe);
runtime = Runtime.getRuntime();
ActivityManager activityManager = (ActivityManager) themedReactContext.getSystemService(themedReactContext.ACTIVITY_SERVICE);
availableHeapInBytes = (int) Math.floor(activityManager.getMemoryClass() * maxHeapAllocationPercent * 1024 * 1024);
ActivityManager activityManager = (ActivityManager) themedReactContext
.getSystemService(themedReactContext.ACTIVITY_SERVICE);
availableHeapInBytes = (int) Math
.floor(activityManager.getMemoryClass() * maxHeapAllocationPercent * 1024 * 1024);
}
@Override
@ -519,7 +563,8 @@ class ReactExoplayerView extends FrameLayout implements
long reserveMemory = (long) minBufferMemoryReservePercent * runtime.maxMemory();
long bufferedMs = bufferedDurationUs / (long) 1000;
if (reserveMemory > freeMemory && bufferedMs > 2000) {
// We don't have enough memory in reserve so we stop buffering to allow other components to use it instead
// We don't have enough memory in reserve so we stop buffering to allow other
// components to use it instead
return false;
}
if (runtime.freeMemory() == 0) {
@ -552,7 +597,8 @@ class ReactExoplayerView extends FrameLayout implements
}
if (playerNeedsSource && srcUri != null) {
exoPlayerView.invalidateAspectRatio();
// DRM session manager creation must be done on a different thread to prevent crashes so we start a new thread
// DRM session manager creation must be done on a different thread to prevent
// crashes so we start a new thread
ExecutorService es = Executors.newSingleThreadExecutor();
es.execute(new Runnable() {
@Override
@ -562,13 +608,15 @@ class ReactExoplayerView extends FrameLayout implements
if (drmSessionManager == null && self.drmUUID != null) {
// Failed to intialize DRM session manager - cannot continue
Log.e("ExoPlayer Exception", "Failed to initialize DRM Session Manager Framework!");
eventEmitter.error("Failed to initialize DRM Session Manager Framework!", new Exception("DRM Session Manager Framework failure!"), "3003");
eventEmitter.error("Failed to initialize DRM Session Manager Framework!",
new Exception("DRM Session Manager Framework failure!"), "3003");
return;
}
if (activity == null) {
Log.e("ExoPlayer Exception", "Failed to initialize Player!");
eventEmitter.error("Failed to initialize Player!", new Exception("Current Activity is null!"), "1001");
eventEmitter.error("Failed to initialize Player!",
new Exception("Current Activity is null!"), "1001");
return;
}
@ -618,10 +666,8 @@ class ReactExoplayerView extends FrameLayout implements
-1,
true,
backBufferDurationMs,
DefaultLoadControl.DEFAULT_RETAIN_BACK_BUFFER_FROM_KEYFRAME
);
DefaultRenderersFactory renderersFactory =
new DefaultRenderersFactory(getContext())
DefaultLoadControl.DEFAULT_RETAIN_BACK_BUFFER_FROM_KEYFRAME);
DefaultRenderersFactory renderersFactory = new DefaultRenderersFactory(getContext())
.setExtensionRendererMode(DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF);
// Create an AdsLoader.
@ -659,7 +705,8 @@ class ReactExoplayerView extends FrameLayout implements
} catch (UnsupportedDrmException e) {
int errorStringId = Util.SDK_INT < 18 ? R.string.error_drm_not_supported
: (e.reason == UnsupportedDrmException.REASON_UNSUPPORTED_SCHEME
? R.string.error_drm_unsupported_scheme : R.string.error_drm_unknown);
? R.string.error_drm_unsupported_scheme
: R.string.error_drm_unknown);
eventEmitter.error(getResources().getString(errorStringId), e, "3003");
return null;
}
@ -675,7 +722,8 @@ class ReactExoplayerView extends FrameLayout implements
MediaSource.Factory mediaSourceFactory = new DefaultMediaSourceFactory(mediaDataSourceFactory)
.setLocalAdInsertionComponents(unusedAdTagUri -> adsLoader, exoPlayerView);
DataSpec adTagDataSpec = new DataSpec(adTagUrl);
mediaSourceWithAds = new AdsMediaSource(videoSource, adTagDataSpec, ImmutableList.of(srcUri, adTagUrl), mediaSourceFactory, adsLoader, exoPlayerView);
mediaSourceWithAds = new AdsMediaSource(videoSource, adTagDataSpec, ImmutableList.of(srcUri, adTagUrl),
mediaSourceFactory, adsLoader, exoPlayerView);
}
MediaSource mediaSource;
if (mediaSourceList.size() == 0) {
@ -691,8 +739,7 @@ class ReactExoplayerView extends FrameLayout implements
mediaSourceList.add(0, videoSource);
}
MediaSource[] textSourceArray = mediaSourceList.toArray(
new MediaSource[mediaSourceList.size()]
);
new MediaSource[mediaSourceList.size()]);
mediaSource = new MergingMediaSource(textSourceArray);
}
@ -728,11 +775,13 @@ class ReactExoplayerView extends FrameLayout implements
startBufferCheckTimer();
}
private DrmSessionManager buildDrmSessionManager(UUID uuid, String licenseUrl, String[] keyRequestPropertiesArray) throws UnsupportedDrmException {
private DrmSessionManager buildDrmSessionManager(UUID uuid, String licenseUrl, String[] keyRequestPropertiesArray)
throws UnsupportedDrmException {
return buildDrmSessionManager(uuid, licenseUrl, keyRequestPropertiesArray, 0);
}
private DrmSessionManager buildDrmSessionManager(UUID uuid, String licenseUrl, String[] keyRequestPropertiesArray, int retryCount) throws UnsupportedDrmException {
private DrmSessionManager buildDrmSessionManager(UUID uuid, String licenseUrl, String[] keyRequestPropertiesArray,
int retryCount) throws UnsupportedDrmException {
if (Util.SDK_INT < 18) {
return null;
}
@ -755,7 +804,8 @@ class ReactExoplayerView extends FrameLayout implements
throw ex;
} catch (Exception ex) {
if (retryCount < 3) {
// Attempt retry 3 times in case where the OS Media DRM Framework fails for whatever reason
// Attempt retry 3 times in case where the OS Media DRM Framework fails for
// whatever reason
return buildDrmSessionManager(uuid, licenseUrl, keyRequestPropertiesArray, ++retryCount);
}
// Handle the unknow exception and emit to JS
@ -776,8 +826,7 @@ class ReactExoplayerView extends FrameLayout implements
if (adTagUrl != null) {
mediaItemBuilder.setAdsConfiguration(
new MediaItem.AdsConfiguration.Builder(adTagUrl).build()
);
new MediaItem.AdsConfiguration.Builder(adTagUrl).build());
}
MediaItem mediaItem = mediaItemBuilder.build();
@ -797,33 +846,29 @@ class ReactExoplayerView extends FrameLayout implements
case CONTENT_TYPE_SS:
return new SsMediaSource.Factory(
new DefaultSsChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false)
).setDrmSessionManagerProvider(drmProvider)
buildDataSourceFactory(false)).setDrmSessionManagerProvider(drmProvider)
.setLoadErrorHandlingPolicy(
config.buildLoadErrorHandlingPolicy(minLoadRetryCount)
).createMediaSource(mediaItem);
config.buildLoadErrorHandlingPolicy(minLoadRetryCount))
.createMediaSource(mediaItem);
case CONTENT_TYPE_DASH:
return new DashMediaSource.Factory(
new DefaultDashChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false)
).setDrmSessionManagerProvider(drmProvider)
buildDataSourceFactory(false)).setDrmSessionManagerProvider(drmProvider)
.setLoadErrorHandlingPolicy(
config.buildLoadErrorHandlingPolicy(minLoadRetryCount)
).createMediaSource(mediaItem);
config.buildLoadErrorHandlingPolicy(minLoadRetryCount))
.createMediaSource(mediaItem);
case CONTENT_TYPE_HLS:
return new HlsMediaSource.Factory(
mediaDataSourceFactory
).setDrmSessionManagerProvider(drmProvider)
mediaDataSourceFactory).setDrmSessionManagerProvider(drmProvider)
.setLoadErrorHandlingPolicy(
config.buildLoadErrorHandlingPolicy(minLoadRetryCount)
).createMediaSource(mediaItem);
config.buildLoadErrorHandlingPolicy(minLoadRetryCount))
.createMediaSource(mediaItem);
case CONTENT_TYPE_OTHER:
return new ProgressiveMediaSource.Factory(
mediaDataSourceFactory
).setDrmSessionManagerProvider(drmProvider)
mediaDataSourceFactory).setDrmSessionManagerProvider(drmProvider)
.setLoadErrorHandlingPolicy(
config.buildLoadErrorHandlingPolicy(minLoadRetryCount)
).createMediaSource(mediaItem);
config.buildLoadErrorHandlingPolicy(minLoadRetryCount))
.createMediaSource(mediaItem);
default: {
throw new IllegalStateException("Unsupported type: " + type);
}
@ -840,7 +885,8 @@ class ReactExoplayerView extends FrameLayout implements
ReadableMap textTrack = textTracks.getMap(i);
String language = textTrack.getString("language");
String title = textTrack.hasKey("title")
? textTrack.getString("title") : language + " " + i;
? textTrack.getString("title")
: language + " " + i;
Uri uri = Uri.parse(textTrack.getString("uri"));
MediaSource textSource = buildTextSource(title, uri, textTrack.getString("type"),
language);
@ -971,7 +1017,8 @@ class ReactExoplayerView extends FrameLayout implements
/**
* Returns a new DataSource factory.
*
* @param useBandwidthMeter Whether to set {@link #bandwidthMeter} as a listener to the new
* @param useBandwidthMeter Whether to set {@link #bandwidthMeter} as a listener
* to the new
* DataSource factory.
* @return A new DataSource factory.
*/
@ -983,15 +1030,16 @@ class ReactExoplayerView extends FrameLayout implements
/**
* Returns a new HttpDataSource factory.
*
* @param useBandwidthMeter Whether to set {@link #bandwidthMeter} as a listener to the new
* @param useBandwidthMeter Whether to set {@link #bandwidthMeter} as a listener
* to the new
* DataSource factory.
* @return A new HttpDataSource factory.
*/
private HttpDataSource.Factory buildHttpDataSourceFactory(boolean useBandwidthMeter) {
return DataSourceUtil.getDefaultHttpDataSourceFactory(this.themedReactContext, useBandwidthMeter ? bandwidthMeter : null, requestHeaders);
return DataSourceUtil.getDefaultHttpDataSourceFactory(this.themedReactContext,
useBandwidthMeter ? bandwidthMeter : null, requestHeaders);
}
// AudioManager.OnAudioFocusChangeListener implementation
@Override
@ -1045,7 +1093,8 @@ class ReactExoplayerView extends FrameLayout implements
@Override
public void onEvents(Player player, Player.Events events) {
if (events.contains(Player.EVENT_PLAYBACK_STATE_CHANGED) || events.contains(Player.EVENT_PLAY_WHEN_READY_CHANGED)) {
if (events.contains(Player.EVENT_PLAYBACK_STATE_CHANGED)
|| events.contains(Player.EVENT_PLAY_WHEN_READY_CHANGED)) {
int playbackState = player.getPlaybackState();
boolean playWhenReady = player.getPlayWhenReady();
String text = "onStateChanged: playWhenReady=" + playWhenReady + ", playbackState=";
@ -1100,9 +1149,11 @@ class ReactExoplayerView extends FrameLayout implements
}
/*
The progress message handler will duplicate recursions of the onProgressMessage handler
on change of player state from any state to STATE_READY with playWhenReady is true (when
the video is not paused). This clears all existing messages.
* The progress message handler will duplicate recursions of the
* onProgressMessage handler
* on change of player state from any state to STATE_READY with playWhenReady is
* true (when
* the video is not paused). This clears all existing messages.
*/
private void clearProgressMessageHandler() {
progressHandler.removeMessages(SHOW_PROGRESS);
@ -1136,7 +1187,8 @@ class ReactExoplayerView extends FrameLayout implements
es.execute(new Runnable() {
@Override
public void run() {
// To prevent ANRs caused by getVideoTrackInfo we run this on a different thread and notify the player only when we're done
// To prevent ANRs caused by getVideoTrackInfo we run this on a different thread
// and notify the player only when we're done
ArrayList<VideoTrack> videoTracks = getVideoTrackInfoFromManifest();
if (videoTracks != null) {
isUsingContentResolution = true;
@ -1229,7 +1281,8 @@ class ReactExoplayerView extends FrameLayout implements
return this.getVideoTrackInfoFromManifest(0);
}
// We need retry count to in case where minefest request fails from poor network conditions
// We need retry count to in case where minefest request fails from poor network
// conditions
@WorkerThread
private ArrayList<VideoTrack> getVideoTrackInfoFromManifest(int retryCount) {
ExecutorService es = Executors.newSingleThreadExecutor();
@ -1249,13 +1302,15 @@ class ReactExoplayerView extends FrameLayout implements
int periodCount = manifest.getPeriodCount();
for (int i = 0; i < periodCount; i++) {
Period period = manifest.getPeriod(i);
for (int adaptationIndex = 0; adaptationIndex < period.adaptationSets.size(); adaptationIndex++) {
for (int adaptationIndex = 0; adaptationIndex < period.adaptationSets
.size(); adaptationIndex++) {
AdaptationSet adaptation = period.adaptationSets.get(adaptationIndex);
if (adaptation.type != C.TRACK_TYPE_VIDEO) {
continue;
}
boolean hasFoundContentPeriod = false;
for (int representationIndex = 0; representationIndex < adaptation.representations.size(); representationIndex++) {
for (int representationIndex = 0; representationIndex < adaptation.representations
.size(); representationIndex++) {
Representation representation = adaptation.representations.get(representationIndex);
Format format = representation.format;
if (isFormatSupported(format)) {
@ -1268,7 +1323,8 @@ class ReactExoplayerView extends FrameLayout implements
videoTrack.m_height = format.height == Format.NO_VALUE ? 0 : format.height;
videoTrack.m_bitrate = format.bitrate == Format.NO_VALUE ? 0 : format.bitrate;
videoTrack.m_codecs = format.codecs != null ? format.codecs : "";
videoTrack.m_trackId = format.id == null ? String.valueOf(representationIndex) : format.id;
videoTrack.m_trackId = format.id == null ? String.valueOf(representationIndex)
: format.id;
videoTracks.add(videoTrack);
}
}
@ -1277,7 +1333,8 @@ class ReactExoplayerView extends FrameLayout implements
}
}
}
} catch (Exception e) {}
} catch (Exception e) {
}
return null;
}
});
@ -1289,7 +1346,8 @@ class ReactExoplayerView extends FrameLayout implements
}
es.shutdown();
return results;
} catch (Exception e) {}
} catch (Exception e) {
}
return null;
}
@ -1339,17 +1397,21 @@ class ReactExoplayerView extends FrameLayout implements
@Override
public void onPositionDiscontinuity(Player.PositionInfo oldPosition, Player.PositionInfo newPosition, int reason) {
if (playerNeedsSource) {
// This will only occur if the user has performed a seek whilst in the error state. Update the
// resume position so that if the user then retries, playback will resume from the position to
// This will only occur if the user has performed a seek whilst in the error
// state. Update the
// resume position so that if the user then retries, playback will resume from
// the position to
// which they seeked.
updateResumePosition();
}
if (isUsingContentResolution) {
// Discontinuity events might have a different track list so we update the selected track
// Discontinuity events might have a different track list so we update the
// selected track
setSelectedTrack(C.TRACK_TYPE_VIDEO, videoTrackType, videoTrackValue);
selectTrackWhenReady = true;
}
// When repeat is turned on, reaching the end of the video will not cause a state change
// When repeat is turned on, reaching the end of the video will not cause a
// state change
// so we need to explicitly detect it.
if (reason == Player.DISCONTINUITY_REASON_AUTO_TRANSITION
&& player.getRepeatMode() == Player.REPEAT_MODE_ONE) {
@ -1369,7 +1431,8 @@ class ReactExoplayerView extends FrameLayout implements
eventEmitter.seek(player.getCurrentPosition(), seekTime);
seekTime = C.TIME_UNSET;
if (isUsingContentResolution) {
// We need to update the selected track to make sure that it still matches user selection if track list has changed in this period
// We need to update the selected track to make sure that it still matches user
// selection if track list has changed in this period
setSelectedTrack(C.TRACK_TYPE_VIDEO, videoTrackType, videoTrackValue);
}
}
@ -1417,7 +1480,8 @@ class ReactExoplayerView extends FrameLayout implements
case PlaybackException.ERROR_CODE_DRM_SYSTEM_ERROR:
case PlaybackException.ERROR_CODE_DRM_UNSPECIFIED:
if (!hasDrmFailed) {
// When DRM fails to reach the app level certificate server it will fail with a source error so we assume that it is DRM related and try one more time
// When DRM fails to reach the app level certificate server it will fail with a
// source error so we assume that it is DRM related and try one more time
hasDrmFailed = true;
playerNeedsSource = true;
updateResumePosition();
@ -1472,8 +1536,8 @@ class ReactExoplayerView extends FrameLayout implements
this.srcUri = uri;
this.extension = extension;
this.requestHeaders = headers;
this.mediaDataSourceFactory =
DataSourceUtil.getDefaultDataSourceFactory(this.themedReactContext, bandwidthMeter,
this.mediaDataSourceFactory = DataSourceUtil.getDefaultDataSourceFactory(this.themedReactContext,
bandwidthMeter,
this.requestHeaders);
if (!isSourceEqual) {
@ -1562,7 +1626,8 @@ class ReactExoplayerView extends FrameLayout implements
}
public void setSelectedTrack(int trackType, String type, Dynamic value) {
if (player == null) return;
if (player == null)
return;
int rendererIndex = getTrackRendererIndex(trackType);
if (rendererIndex == C.INDEX_UNSET) {
return;
@ -1621,9 +1686,11 @@ class ReactExoplayerView extends FrameLayout implements
usingExactMatch = true;
break;
} else if (isUsingContentResolution) {
// When using content resolution rather than ads, we need to try and find the closest match if there is no exact match
// When using content resolution rather than ads, we need to try and find the
// closest match if there is no exact match
if (closestFormat != null) {
if ((format.bitrate > closestFormat.bitrate || format.height > closestFormat.height) && format.height < height) {
if ((format.bitrate > closestFormat.bitrate || format.height > closestFormat.height)
&& format.height < height) {
// Higher quality match
closestFormat = format;
closestTrackIndex = j;
@ -1634,7 +1701,8 @@ class ReactExoplayerView extends FrameLayout implements
}
}
}
// This is a fallback if the new period contains only higher resolutions than the user has selected
// This is a fallback if the new period contains only higher resolutions than
// the user has selected
if (closestFormat == null && isUsingContentResolution && !usingExactMatch) {
// No close match found - so we pick the lowest quality
int minHeight = Integer.MAX_VALUE;
@ -1656,8 +1724,8 @@ class ReactExoplayerView extends FrameLayout implements
}
} else if (trackType == C.TRACK_TYPE_TEXT && Util.SDK_INT > 18) { // Text default
// Use system settings if possible
CaptioningManager captioningManager
= (CaptioningManager)themedReactContext.getSystemService(Context.CAPTIONING_SERVICE);
CaptioningManager captioningManager = (CaptioningManager) themedReactContext
.getSystemService(Context.CAPTIONING_SERVICE);
if (captioningManager != null && captioningManager.isEnabled()) {
groupIndex = getGroupIndexForDefaultLocale(groups);
}
@ -1789,6 +1857,21 @@ class ReactExoplayerView extends FrameLayout implements
}
}
public void setAudioOutput(AudioOutput output) {
if (audioOutput != output && player != null) {
this.audioOutput = output;
int usage = Util.getAudioUsageForStreamType(audioOutput.streamType);
int contentType = Util.getAudioContentTypeForStreamType(audioOutput.streamType);
AudioAttributes audioAttributes = new AudioAttributes.Builder().setUsage(usage).setContentType(contentType)
.build();
player.setAudioAttributes(audioAttributes, false);
AudioManager audioManager = (AudioManager) themedReactContext.getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(
audioOutput == AudioOutput.SPEAKER ? AudioManager.MODE_NORMAL : AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(audioOutput == AudioOutput.SPEAKER);
}
}
public void setVolumeModifier(float volume) {
audioVolume = volume;
if (player != null) {
@ -1846,7 +1929,8 @@ class ReactExoplayerView extends FrameLayout implements
long reserveMemory = (long) minBackBufferMemoryReservePercent * runtime.maxMemory();
if (reserveMemory > freeMemory) {
// We don't have enough memory in reserve so we will
Log.w("ExoPlayer Warning", "Not enough reserve memory, setting back buffer to 0ms to reduce memory pressure!");
Log.w("ExoPlayer Warning",
"Not enough reserve memory, setting back buffer to 0ms to reduce memory pressure!");
this.backBufferDurationMs = 0;
return;
}
@ -1924,7 +2008,8 @@ class ReactExoplayerView extends FrameLayout implements
eventEmitter.fullscreenDidDismiss();
});
}
// need to be done at the end to avoid hiding fullscreen control button when fullScreenPlayerView is shown
// need to be done at the end to avoid hiding fullscreen control button when
// fullScreenPlayerView is shown
updateFullScreenButtonVisbility();
}
@ -1941,7 +2026,9 @@ class ReactExoplayerView extends FrameLayout implements
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) {
minBufferMs = newMinBufferMs;
maxBufferMs = newMaxBufferMs;
bufferForPlaybackMs = newBufferForPlaybackMs;
@ -1965,7 +2052,6 @@ class ReactExoplayerView extends FrameLayout implements
this.drmLicenseHeader = header;
}
@Override
public void onDrmKeysLoaded(int windowIndex, MediaSource.MediaPeriodId mediaPeriodId) {
Log.d("DRM Info", "onDrmKeysLoaded");

View File

@ -49,6 +49,7 @@ public class ReactExoplayerViewManager extends ViewGroupManager<ReactExoplayerVi
private static final String PROP_TEXT_TRACKS = "textTracks";
private static final String PROP_PAUSED = "paused";
private static final String PROP_MUTED = "muted";
private static final String PROP_AUDIO_OUTPUT = "audioOutput";
private static final String PROP_VOLUME = "volume";
private static final String PROP_BACK_BUFFER_DURATION_MS = "backBufferDurationMs";
private static final String PROP_BUFFER_CONFIG = "bufferConfig";
@ -119,8 +120,7 @@ public class ReactExoplayerViewManager extends ViewGroupManager<ReactExoplayerVi
"ScaleNone", Integer.toString(ResizeMode.RESIZE_MODE_FIT),
"ScaleAspectFit", Integer.toString(ResizeMode.RESIZE_MODE_FIT),
"ScaleToFill", Integer.toString(ResizeMode.RESIZE_MODE_FILL),
"ScaleAspectFill", Integer.toString(ResizeMode.RESIZE_MODE_CENTER_CROP)
);
"ScaleAspectFill", Integer.toString(ResizeMode.RESIZE_MODE_CENTER_CROP));
}
@ReactProp(name = PROP_DRM)
@ -170,14 +170,12 @@ public class ReactExoplayerViewManager extends ViewGroupManager<ReactExoplayerVi
int identifier = context.getResources().getIdentifier(
uriString,
"drawable",
context.getPackageName()
);
context.getPackageName());
if (identifier == 0) {
identifier = context.getResources().getIdentifier(
uriString,
"raw",
context.getPackageName()
);
context.getPackageName());
}
if (identifier > 0) {
Uri srcUri = RawResourceDataSource.buildRawResourceUri(identifier);
@ -201,7 +199,6 @@ public class ReactExoplayerViewManager extends ViewGroupManager<ReactExoplayerVi
videoView.setAdTagUrl(adTagUrl);
}
@ReactProp(name = PROP_RESIZE_MODE)
public void setResizeMode(final ReactExoplayerView videoView, final String resizeModeOrdinalString) {
videoView.setResizeModeModifier(convertToIntDef(resizeModeOrdinalString));
@ -213,7 +210,8 @@ public class ReactExoplayerViewManager extends ViewGroupManager<ReactExoplayerVi
}
@ReactProp(name = PROP_PREVENTS_DISPLAY_SLEEP_DURING_VIDEO_PLAYBACK, defaultBoolean = false)
public void setPreventsDisplaySleepDuringVideoPlayback(final ReactExoplayerView videoView, final boolean preventsSleep) {
public void setPreventsDisplaySleepDuringVideoPlayback(final ReactExoplayerView videoView,
final boolean preventsSleep) {
videoView.setPreventsDisplaySleepDuringVideoPlayback(preventsSleep);
}
@ -224,9 +222,11 @@ public class ReactExoplayerViewManager extends ViewGroupManager<ReactExoplayerVi
Dynamic value = null;
if (selectedVideoTrack != null) {
typeString = selectedVideoTrack.hasKey(PROP_SELECTED_VIDEO_TRACK_TYPE)
? selectedVideoTrack.getString(PROP_SELECTED_VIDEO_TRACK_TYPE) : null;
? selectedVideoTrack.getString(PROP_SELECTED_VIDEO_TRACK_TYPE)
: null;
value = selectedVideoTrack.hasKey(PROP_SELECTED_VIDEO_TRACK_VALUE)
? selectedVideoTrack.getDynamic(PROP_SELECTED_VIDEO_TRACK_VALUE) : null;
? selectedVideoTrack.getDynamic(PROP_SELECTED_VIDEO_TRACK_VALUE)
: null;
}
videoView.setSelectedVideoTrack(typeString, value);
}
@ -238,9 +238,11 @@ public class ReactExoplayerViewManager extends ViewGroupManager<ReactExoplayerVi
Dynamic value = null;
if (selectedAudioTrack != null) {
typeString = selectedAudioTrack.hasKey(PROP_SELECTED_AUDIO_TRACK_TYPE)
? selectedAudioTrack.getString(PROP_SELECTED_AUDIO_TRACK_TYPE) : null;
? selectedAudioTrack.getString(PROP_SELECTED_AUDIO_TRACK_TYPE)
: null;
value = selectedAudioTrack.hasKey(PROP_SELECTED_AUDIO_TRACK_VALUE)
? selectedAudioTrack.getDynamic(PROP_SELECTED_AUDIO_TRACK_VALUE) : null;
? selectedAudioTrack.getDynamic(PROP_SELECTED_AUDIO_TRACK_VALUE)
: null;
}
videoView.setSelectedAudioTrack(typeString, value);
}
@ -252,9 +254,11 @@ public class ReactExoplayerViewManager extends ViewGroupManager<ReactExoplayerVi
Dynamic value = null;
if (selectedTextTrack != null) {
typeString = selectedTextTrack.hasKey(PROP_SELECTED_TEXT_TRACK_TYPE)
? selectedTextTrack.getString(PROP_SELECTED_TEXT_TRACK_TYPE) : null;
? selectedTextTrack.getString(PROP_SELECTED_TEXT_TRACK_TYPE)
: null;
value = selectedTextTrack.hasKey(PROP_SELECTED_TEXT_TRACK_VALUE)
? selectedTextTrack.getDynamic(PROP_SELECTED_TEXT_TRACK_VALUE) : null;
? selectedTextTrack.getDynamic(PROP_SELECTED_TEXT_TRACK_VALUE)
: null;
}
videoView.setSelectedTextTrack(typeString, value);
}
@ -275,6 +279,11 @@ public class ReactExoplayerViewManager extends ViewGroupManager<ReactExoplayerVi
videoView.setMutedModifier(muted);
}
@ReactProp(name = PROP_AUDIO_OUTPUT)
public void setAudioOutput(final ReactExoplayerView videoView, final String audioOutput) {
videoView.setAudioOutput(ReactExoplayerView.AudioOutput.get(audioOutput));
}
@ReactProp(name = PROP_VOLUME, defaultFloat = 1.0f)
public void setVolume(final ReactExoplayerView videoView, final float volume) {
videoView.setVolumeModifier(volume);
@ -387,20 +396,30 @@ public class ReactExoplayerViewManager extends ViewGroupManager<ReactExoplayerVi
if (bufferConfig != null) {
minBufferMs = bufferConfig.hasKey(PROP_BUFFER_CONFIG_MIN_BUFFER_MS)
? bufferConfig.getInt(PROP_BUFFER_CONFIG_MIN_BUFFER_MS) : minBufferMs;
? bufferConfig.getInt(PROP_BUFFER_CONFIG_MIN_BUFFER_MS)
: minBufferMs;
maxBufferMs = bufferConfig.hasKey(PROP_BUFFER_CONFIG_MAX_BUFFER_MS)
? bufferConfig.getInt(PROP_BUFFER_CONFIG_MAX_BUFFER_MS) : maxBufferMs;
? bufferConfig.getInt(PROP_BUFFER_CONFIG_MAX_BUFFER_MS)
: maxBufferMs;
bufferForPlaybackMs = bufferConfig.hasKey(PROP_BUFFER_CONFIG_BUFFER_FOR_PLAYBACK_MS)
? bufferConfig.getInt(PROP_BUFFER_CONFIG_BUFFER_FOR_PLAYBACK_MS) : bufferForPlaybackMs;
bufferForPlaybackAfterRebufferMs = bufferConfig.hasKey(PROP_BUFFER_CONFIG_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS)
? bufferConfig.getInt(PROP_BUFFER_CONFIG_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS) : bufferForPlaybackAfterRebufferMs;
? bufferConfig.getInt(PROP_BUFFER_CONFIG_BUFFER_FOR_PLAYBACK_MS)
: bufferForPlaybackMs;
bufferForPlaybackAfterRebufferMs = bufferConfig
.hasKey(PROP_BUFFER_CONFIG_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS)
? bufferConfig.getInt(PROP_BUFFER_CONFIG_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS)
: bufferForPlaybackAfterRebufferMs;
maxHeapAllocationPercent = bufferConfig.hasKey(PROP_BUFFER_CONFIG_MAX_HEAP_ALLOCATION_PERCENT)
? bufferConfig.getDouble(PROP_BUFFER_CONFIG_MAX_HEAP_ALLOCATION_PERCENT) : maxHeapAllocationPercent;
minBackBufferMemoryReservePercent = bufferConfig.hasKey(PROP_BUFFER_CONFIG_MIN_BACK_BUFFER_MEMORY_RESERVE_PERCENT)
? bufferConfig.getDouble(PROP_BUFFER_CONFIG_MIN_BACK_BUFFER_MEMORY_RESERVE_PERCENT) : minBackBufferMemoryReservePercent;
? bufferConfig.getDouble(PROP_BUFFER_CONFIG_MAX_HEAP_ALLOCATION_PERCENT)
: maxHeapAllocationPercent;
minBackBufferMemoryReservePercent = bufferConfig
.hasKey(PROP_BUFFER_CONFIG_MIN_BACK_BUFFER_MEMORY_RESERVE_PERCENT)
? bufferConfig.getDouble(PROP_BUFFER_CONFIG_MIN_BACK_BUFFER_MEMORY_RESERVE_PERCENT)
: minBackBufferMemoryReservePercent;
minBufferMemoryReservePercent = bufferConfig.hasKey(PROP_BUFFER_CONFIG_MIN_BUFFER_MEMORY_RESERVE_PERCENT)
? bufferConfig.getDouble(PROP_BUFFER_CONFIG_MIN_BUFFER_MEMORY_RESERVE_PERCENT) : minBufferMemoryReservePercent;
videoView.setBufferConfig(minBufferMs, maxBufferMs, bufferForPlaybackMs, bufferForPlaybackAfterRebufferMs, maxHeapAllocationPercent, minBackBufferMemoryReservePercent, minBufferMemoryReservePercent);
? bufferConfig.getDouble(PROP_BUFFER_CONFIG_MIN_BUFFER_MEMORY_RESERVE_PERCENT)
: minBufferMemoryReservePercent;
videoView.setBufferConfig(minBufferMs, maxBufferMs, bufferForPlaybackMs, bufferForPlaybackAfterRebufferMs,
maxHeapAllocationPercent, minBackBufferMemoryReservePercent, minBufferMemoryReservePercent);
}
}
@ -426,7 +445,8 @@ public class ReactExoplayerViewManager extends ViewGroupManager<ReactExoplayerVi
*
* @param readableMap The ReadableMap to be conveted.
* @return A HashMap containing the data that was in the ReadableMap.
* @see 'Adapted from https://github.com/artemyarulin/react-native-eval/blob/master/android/src/main/java/com/evaluator/react/ConversionUtil.java'
* @see 'Adapted from
* https://github.com/artemyarulin/react-native-eval/blob/master/android/src/main/java/com/evaluator/react/ConversionUtil.java'
*/
public static Map<String, String> toStringMap(@Nullable ReadableMap readableMap) {
if (readableMap == null)

View File

@ -197,7 +197,7 @@ enum RCTPlayerOperations {
var options:AVAudioSession.CategoryOptions? = nil
if (ignoreSilentSwitch == "ignore") {
category = AVAudioSession.Category.playback
category = AVAudioSession.Category.playAndRecord
} else if (ignoreSilentSwitch == "obey") {
category = AVAudioSession.Category.ambient
}

View File

@ -35,6 +35,7 @@ class RCTVideo: UIView, RCTVideoPlayerViewControllerDelegate, RCTPlayerObserverH
private var _controls:Bool = false
/* Keep track of any modifiers, need to be applied after each play */
private var _audioOutput: String = "speaker"
private var _volume:Float = 1.0
private var _rate:Float = 1.0
private var _maxBitRate:Float?
@ -515,6 +516,20 @@ class RCTVideo: UIView, RCTVideoPlayerViewControllerDelegate, RCTPlayerObserverH
applyModifiers()
}
@objc
func setAudioOutput(_ audioOutput:String) {
_audioOutput = audioOutput
do {
if audioOutput == "speaker" {
try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
} else if audioOutput == "earpiece" {
try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSession.PortOverride.none)
}
} catch {
print("Error occurred: \(error.localizedDescription)")
}
}
@objc
func setVolume(_ volume:Float) {
_volume = volume

View File

@ -17,6 +17,7 @@ RCT_EXPORT_VIEW_PROPERTY(selectedAudioTrack, NSDictionary);
RCT_EXPORT_VIEW_PROPERTY(paused, BOOL);
RCT_EXPORT_VIEW_PROPERTY(muted, BOOL);
RCT_EXPORT_VIEW_PROPERTY(controls, BOOL);
RCT_EXPORT_VIEW_PROPERTY(audioOutput, NSString);
RCT_EXPORT_VIEW_PROPERTY(volume, float);
RCT_EXPORT_VIEW_PROPERTY(playInBackground, BOOL);
RCT_EXPORT_VIEW_PROPERTY(preventsDisplaySleepDuringVideoPlayback, BOOL);