| 1 | /* |
| 2 | * Copyright 2013 The WebRTC project authors. All Rights Reserved. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license |
| 5 | * that can be found in the LICENSE file in the root of the source |
| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 | |
| 11 | package org.webrtc; |
| 12 | |
| 13 | /** Java wrapper for a C++ MediaSourceInterface. */ |
| 14 | public class MediaSource { |
| 15 | /** Tracks MediaSourceInterface.SourceState */ |
| 16 | public enum State { |
| 17 | INITIALIZING, |
| 18 | LIVE, |
| 19 | ENDED, |
| 20 | MUTED; |
| 21 | |
| 22 | @CalledByNative("State") |
| 23 | static State fromNativeIndex(int nativeIndex) { |
| 24 | return values()[nativeIndex]; |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | private final RefCountDelegate refCountDelegate; |
| 29 | private long nativeSource; |
| 30 | |
| 31 | public MediaSource(long nativeSource) { |
| 32 | refCountDelegate = new RefCountDelegate(() -> JniCommon.nativeReleaseRef(nativeSource)); |
| 33 | this.nativeSource = nativeSource; |
| 34 | } |
| 35 | |
| 36 | public State state() { |
| 37 | checkMediaSourceExists(); |
| 38 | return nativeGetState(nativeSource); |
| 39 | } |
| 40 | |
| 41 | public void dispose() { |
| 42 | checkMediaSourceExists(); |
| 43 | refCountDelegate.release(); |
| 44 | nativeSource = 0; |
| 45 | } |
| 46 | |
| 47 | /** Returns a pointer to webrtc::MediaSourceInterface. */ |
| 48 | protected long getNativeMediaSource() { |
| 49 | checkMediaSourceExists(); |
| 50 | return nativeSource; |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Runs code in {@code runnable} holding a reference to the media source. If the object has |
| 55 | * already been released, does nothing. |
| 56 | */ |
| 57 | void runWithReference(Runnable runnable) { |
| 58 | if (refCountDelegate.safeRetain()) { |
| 59 | try { |
| 60 | runnable.run(); |
| 61 | } finally { |
| 62 | refCountDelegate.release(); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | private void checkMediaSourceExists() { |
| 68 | if (nativeSource == 0) { |
| 69 | throw new IllegalStateException("MediaSource has been disposed."); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | private static native State nativeGetState(long pointer); |
| 74 | } |
| 75 | |