-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathTvheadendPlayer.java
584 lines (481 loc) · 21.5 KB
/
TvheadendPlayer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
/*
* Copyright (c) 2017 Kiall Mac Innes <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ie.macinnes.tvheadend.player;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.media.PlaybackParams;
import android.media.tv.TvContract;
import android.media.tv.TvTrackInfo;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.util.SparseArray;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.CaptioningManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.RendererCapabilities;
import com.google.android.exoplayer2.RenderersFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.TrackGroup;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.text.CaptionStyleCompat;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.MappingTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.ui.DebugTextViewHelper;
import com.google.android.exoplayer2.ui.SubtitleView;
import com.google.android.exoplayer2.upstream.DefaultAllocator;
import com.google.android.exoplayer2.util.MimeTypes;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import ie.macinnes.htsp.SimpleHtspConnection;
import ie.macinnes.tvheadend.Constants;
import ie.macinnes.tvheadend.R;
import ie.macinnes.tvheadend.TvContractUtils;
public class TvheadendPlayer implements Player.EventListener {
private static final String TAG = TvheadendPlayer.class.getName();
private static final float CAPTION_LINE_HEIGHT_RATIO = 0.0533f;
private static final int TEXT_UNIT_PIXELS = 0;
private static final long INVALID_TIMESHIFT_TIME = HtspDataSource.INVALID_TIMESHIFT_TIME;
public interface Listener {
/**
* Called when ther player state changes.
*
* @param playWhenReady Whether playback will proceed when ready.
* @param playbackState One of the {@code STATE} constants defined in the {@link ExoPlayer}
* interface.
*/
void onPlayerStateChanged(boolean playWhenReady, int playbackState);
/**
* Called when an error occurs.
*
* @param error The error.
*/
void onPlayerError(ExoPlaybackException error);
/**
* Called when the available or selected tracks change.
*
* @param tracks a list of tracks
*/
void onTracksChanged(List<TvTrackInfo> tracks, SparseArray<String> selectedTracks);
}
private final Context mContext;
private final SimpleHtspConnection mConnection;
private final Listener mListener;
private final SharedPreferences mSharedPreferences;
private SimpleExoPlayer mExoPlayer;
private RenderersFactory mRenderersFactory;
private TvheadendTrackSelector mTrackSelector;
private LoadControl mLoadControl;
private EventLogger mEventLogger;
private HtspDataSource.Factory mHtspSubscriptionDataSourceFactory;
private HtspDataSource.Factory mHtspFileInputStreamDataSourceFactory;
private HtspDataSource mDataSource;
private ExtractorsFactory mExtractorsFactory;
private View mOverlayView;
private DebugTextViewHelper mDebugViewHelper;
private SubtitleView mSubtitleView;
private LinearLayout mRadioInfoView;
private MediaSource mMediaSource;
private Uri mCurrentChannelUri;
public TvheadendPlayer(Context context, SimpleHtspConnection connection, Listener listener) {
mContext = context;
mConnection = connection;
mListener = listener;
mSharedPreferences = mContext.getSharedPreferences(
Constants.PREFERENCE_TVHEADEND, Context.MODE_PRIVATE);
buildExoPlayer();
}
public void open(Uri channelUri) {
// Stop any existing playback
stop();
mCurrentChannelUri = channelUri;
// Create the media source
if (channelUri.getHost().equals("channel")) {
buildHtspChannelMediaSource(channelUri);
} else {
buildHtspRecordingMediaSource(channelUri);
}
// Prepare the media source
mExoPlayer.prepare(mMediaSource);
}
public void release() {
// Stop any existing playback
stop();
if (mDebugViewHelper != null) {
mDebugViewHelper.stop();
mDebugViewHelper = null;
}
mSubtitleView = null;
mOverlayView = null;
// Release ExoPlayer
mExoPlayer.removeListener(this);
mExoPlayer.release();
}
public void setSurface(Surface surface) {
mExoPlayer.setVideoSurface(surface);
}
public void setVolume(float volume) {
mExoPlayer.setVolume(volume);
}
public boolean selectTrack(int type, String trackId) {
return mTrackSelector.selectTrack(type, trackId);
}
public void play() {
// Start playback when ready
mExoPlayer.setPlayWhenReady(true);
}
public void resume() {
mExoPlayer.setPlayWhenReady(true);
if (mDataSource != null) {
Log.d(TAG, "Resuming HtspDataSource");
mDataSource.resume();
} else {
Log.w(TAG, "Unable to resume, no HtspDataSource available");
}
}
public void pause() {
mExoPlayer.setPlayWhenReady(false);
if (mDataSource != null) {
Log.d(TAG, "Pausing HtspDataSource");
mDataSource.pause();
} else {
Log.w(TAG, "Unable to pause, no HtspDataSource available");
}
}
public void seek(long timeMs) {
if (mDataSource != null) {
Log.d(TAG, "Seeking to time: " + timeMs);
long seekPts = (timeMs * 1000) - mDataSource.getTimeshiftStartTime();
seekPts = Math.max(seekPts, mDataSource.getTimeshiftStartPts()) / 1000;
Log.d(TAG, "Seeking to PTS: " + seekPts);
mExoPlayer.seekTo(seekPts);
} else {
Log.w(TAG, "Unable to seek, no HtspDataSource available");
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
public void setPlaybackParams(PlaybackParams params) {
float rawSpeed = params.getSpeed();
int speed = (int) rawSpeed;
Log.d(TAG, "Speed: " + params.getSpeed());
if (mDataSource != null) {
mDataSource.setSpeed(speed);
mExoPlayer.setPlaybackParameters(new PlaybackParameters(speed, 1));
}
}
private void stop() {
mExoPlayer.stop();
mTrackSelector.clearSelectionOverrides();
mHtspSubscriptionDataSourceFactory.releaseCurrentDataSource();
mHtspFileInputStreamDataSourceFactory.releaseCurrentDataSource();
if (mMediaSource != null) {
mMediaSource.releaseSource();
}
}
public long getTimeshiftStartPosition() {
if (mDataSource != null) {
long startTime = mDataSource.getTimeshiftStartTime();
if (startTime != INVALID_TIMESHIFT_TIME) {
// For live content
return startTime / 1000;
} else {
// For recorded content
return 0;
}
} else {
Log.w(TAG, "Unable to getTimeshiftStartPosition, no HtspDataSource available");
}
return INVALID_TIMESHIFT_TIME;
}
public long getTimeshiftCurrentPosition() {
if (mDataSource != null) {
long offset = mDataSource.getTimeshiftOffsetPts();
if (offset != INVALID_TIMESHIFT_TIME) {
// For live content
return System.currentTimeMillis() + (offset / 1000);
} else {
// For recorded content
mExoPlayer.getCurrentPosition();
}
} else {
Log.w(TAG, "Unable to getTimeshiftCurrentPosition, no HtspDataSource available");
}
return INVALID_TIMESHIFT_TIME;
}
public View getOverlayView(CaptioningManager.CaptionStyle captionStyle, float fontScale) {
if (mOverlayView == null) {
LayoutInflater lI = (LayoutInflater) mContext.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mOverlayView = lI.inflate(R.layout.player_overlay_view, null);
}
if (mDebugViewHelper == null) {
mDebugViewHelper = getDebugTextView();
if (mDebugViewHelper != null) {
mDebugViewHelper.start();
}
}
if (mSubtitleView == null) {
mSubtitleView = getSubtitleView(captionStyle, fontScale);
if (mSubtitleView != null) {
mExoPlayer.setTextOutput(mSubtitleView);
}
}
if (mRadioInfoView == null) {
mRadioInfoView = mOverlayView.findViewById(R.id.radio_info_view);
}
return mOverlayView;
}
private DebugTextViewHelper getDebugTextView() {
final boolean enableDebugTextView = mSharedPreferences.getBoolean(
Constants.KEY_DEBUG_TEXT_VIEW_ENABLED,
mContext.getResources().getBoolean(R.bool.pref_default_debug_text_view_enabled)
);
if (enableDebugTextView) {
TextView textView = mOverlayView.findViewById(R.id.debug_text_view);
textView.setVisibility(View.VISIBLE);
return new DebugTextViewHelper(
mExoPlayer, textView);
} else {
return null;
}
}
private SubtitleView getSubtitleView(CaptioningManager.CaptionStyle captionStyle, float fontScale) {
SubtitleView view = mOverlayView.findViewById(R.id.subtitle_view);
CaptionStyleCompat captionStyleCompat = CaptionStyleCompat.createFromCaptionStyle(captionStyle);
float captionTextSize = getCaptionFontSize();
captionTextSize *= fontScale;
final boolean applyEmbeddedStyles = mSharedPreferences.getBoolean(
Constants.KEY_CAPTIONS_APPLY_EMBEDDED_STYLES,
mContext.getResources().getBoolean(R.bool.pref_default_captions_apply_embedded_styles)
);
view.setStyle(captionStyleCompat);
view.setVisibility(View.VISIBLE);
view.setFixedTextSize(TEXT_UNIT_PIXELS, captionTextSize);
view.setApplyEmbeddedStyles(applyEmbeddedStyles);
return view;
}
// Misc Internal Methods
private void buildExoPlayer() {
mRenderersFactory = new TvheadendRenderersFactory(mContext);
mTrackSelector = buildTrackSelector();
mLoadControl = buildLoadControl();
mExoPlayer = ExoPlayerFactory.newSimpleInstance(mRenderersFactory, mTrackSelector, mLoadControl);
mExoPlayer.addListener(this);
// Add the EventLogger
mEventLogger = new EventLogger(mTrackSelector);
mExoPlayer.addListener(mEventLogger);
mExoPlayer.setAudioDebugListener(mEventLogger);
mExoPlayer.setVideoDebugListener(mEventLogger);
final String streamProfile = mSharedPreferences.getString(
Constants.KEY_HTSP_STREAM_PROFILE,
mContext.getResources().getString(R.string.pref_default_htsp_stream_profile)
);
// Produces DataSource instances through which media data is loaded.
mHtspSubscriptionDataSourceFactory = new HtspSubscriptionDataSource.Factory(mContext, mConnection, streamProfile);
mHtspFileInputStreamDataSourceFactory = new HtspFileInputStreamDataSource.Factory(mContext, mConnection);
// Produces Extractor instances for parsing the media data.
mExtractorsFactory = new TvheadendExtractorsFactory(mContext);
}
private TvheadendTrackSelector buildTrackSelector() {
TrackSelection.Factory trackSelectionFactory =
new AdaptiveTrackSelection.Factory(null);
TvheadendTrackSelector trackSelector = new TvheadendTrackSelector(trackSelectionFactory);
final boolean enableAudioTunneling = mSharedPreferences.getBoolean(
Constants.KEY_AUDIO_TUNNELING_ENABLED,
mContext.getResources().getBoolean(R.bool.pref_default_audio_tunneling_enabled)
);
if (enableAudioTunneling) {
trackSelector.setTunnelingAudioSessionId(C.generateAudioSessionIdV21(mContext));
}
return trackSelector;
}
private LoadControl buildLoadControl() {
int bufferForPlaybackMs = Integer.parseInt(
mSharedPreferences.getString(
Constants.KEY_BUFFER_PLAYBACK_MS,
mContext.getResources().getString(R.string.pref_default_buffer_playback_ms)
)
);
return new DefaultLoadControl(
new DefaultAllocator(true, C.DEFAULT_BUFFER_SEGMENT_SIZE),
DefaultLoadControl.DEFAULT_MIN_BUFFER_MS,
DefaultLoadControl.DEFAULT_MAX_BUFFER_MS,
bufferForPlaybackMs,
DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS
);
}
private void buildHtspChannelMediaSource(Uri channelUri) {
// This is the MediaSource representing the media to be played.
mMediaSource = new ExtractorMediaSource(channelUri,
mHtspSubscriptionDataSourceFactory, mExtractorsFactory, null, mEventLogger);
}
private void buildHtspRecordingMediaSource(Uri recordingUri) {
// This is the MediaSource representing the media to be played.
mMediaSource = new ExtractorMediaSource(recordingUri,
mHtspFileInputStreamDataSourceFactory, mExtractorsFactory, null, mEventLogger);
}
private float getCaptionFontSize() {
Display display = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
Point displaySize = new Point();
display.getSize(displaySize);
return Math.max(mContext.getResources().getDimension(R.dimen.subtitle_minimum_font_size),
CAPTION_LINE_HEIGHT_RATIO * Math.min(displaySize.x, displaySize.y));
}
private boolean getTrackStatusBoolean(TrackSelection selection, TrackGroup group,
int trackIndex) {
return selection != null && selection.getTrackGroup() == group
&& selection.indexOf(trackIndex) != C.INDEX_UNSET;
}
// ExoPlayer.EventListener Methods
@Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
// Don't care about this event here
}
@Override
public void onRepeatModeChanged(int i) {
// Don't care about this event here
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
MappingTrackSelector.MappedTrackInfo mappedTrackInfo = mTrackSelector.getCurrentMappedTrackInfo();
if (mappedTrackInfo == null) {
return;
}
// Process Tracks
List<TvTrackInfo> tracks = new ArrayList<>();
SparseArray<String> selectedTracks = new SparseArray<>();
// Keep track of weather we have a video track available
boolean hasVideoTrack = false;
for (int rendererIndex = 0; rendererIndex < mappedTrackInfo.length; rendererIndex++) {
TrackGroupArray rendererTrackGroups = mappedTrackInfo.getTrackGroups(rendererIndex);
TrackSelection trackSelection = trackSelections.get(rendererIndex);
if (rendererTrackGroups.length > 0) {
for (int groupIndex = 0; groupIndex < rendererTrackGroups.length; groupIndex++) {
TrackGroup trackGroup = rendererTrackGroups.get(groupIndex);
for (int trackIndex = 0; trackIndex < trackGroup.length; trackIndex++) {
int formatSupport = mappedTrackInfo.getTrackFormatSupport(rendererIndex, groupIndex, trackIndex);
if (formatSupport == RendererCapabilities.FORMAT_HANDLED) {
Format format = trackGroup.getFormat(trackIndex);
TvTrackInfo tvTrackInfo = ExoPlayerUtils.buildTvTrackInfo(format);
if (tvTrackInfo != null) {
tracks.add(tvTrackInfo);
Boolean selected = getTrackStatusBoolean(trackSelection, trackGroup, trackIndex);
if (selected) {
int trackType = MimeTypes.getTrackType(format.sampleMimeType);
switch (trackType) {
case C.TRACK_TYPE_VIDEO:
hasVideoTrack = true;
selectedTracks.put(TvTrackInfo.TYPE_VIDEO, format.id);
break;
case C.TRACK_TYPE_AUDIO:
selectedTracks.put(TvTrackInfo.TYPE_AUDIO, format.id);
break;
case C.TRACK_TYPE_TEXT:
selectedTracks.put(TvTrackInfo.TYPE_SUBTITLE, format.id);
break;
}
}
}
}
}
}
}
}
if(hasVideoTrack) {
disableRadioInfoScreen();
} else {
enableRadioInfoScreen();
}
mListener.onTracksChanged(tracks, selectedTracks);
}
private void enableRadioInfoScreen() {
// No video track available, use the channel logo as a substitute
Log.i(TAG, "No video track available");
try {
String channelName = TvContractUtils.getChannelName(mContext, Integer.parseInt(mCurrentChannelUri.getPath().substring(1)));
TextView radioChannelName = mRadioInfoView.findViewById(R.id.radio_channel_name);
radioChannelName.setText(channelName);
ImageView radioChannelIcon = mRadioInfoView.findViewById(R.id.radio_channel_icon);
long androidChannelId = TvContractUtils.getChannelId(mContext, Integer.parseInt(mCurrentChannelUri.getPath().substring(1)));
Uri channelIconUri = TvContract.buildChannelLogoUri(androidChannelId);
InputStream is = mContext.getContentResolver().openInputStream(channelIconUri);
BitmapDrawable iconImage = new BitmapDrawable(mContext.getResources(), is);
radioChannelIcon.setImageDrawable(iconImage);
mRadioInfoView.setVisibility(View.VISIBLE);
} catch (IOException e) {
Log.e(TAG, "Failed to fetch logo", e);
}
}
private void disableRadioInfoScreen() {
Log.d(TAG, "Video track is available");
mRadioInfoView.setVisibility(View.INVISIBLE);
}
@Override
public void onLoadingChanged(boolean isLoading) {
if (isLoading) {
// Fetch the current DataSource for later use
// TODO: Hold a WeakReference to the DataSource instead...
// TODO: We should know if we're playing a channel or a recording...
mDataSource = mHtspSubscriptionDataSourceFactory.getCurrentDataSource();
if (mDataSource == null) {
mDataSource = mHtspFileInputStreamDataSourceFactory.getCurrentDataSource();
}
}
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
mListener.onPlayerStateChanged(playWhenReady, playbackState);
}
@Override
public void onPlayerError(ExoPlaybackException error) {
mListener.onPlayerError(error);
}
@Override
public void onPositionDiscontinuity() {
// Don't care about this event here
}
@Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
// Don't care about this event here
}
}