├── .gitignore ├── .idea ├── .name ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── gradle.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── README.md ├── app ├── .gitignore ├── app.iml ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── yschi │ │ └── castscreen │ │ └── ApplicationTest.java │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── yschi │ │ └── castscreen │ │ ├── CastService.java │ │ ├── Common.java │ │ ├── IvfWriter.java │ │ ├── MainActivity.java │ │ └── Utils.java │ └── res │ ├── layout │ └── activity_main.xml │ ├── menu │ └── menu_main.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── mipmap-xxxhdpi │ └── ic_launcher.png │ ├── values-v21 │ └── styles.xml │ ├── values-w820dp │ └── dimens.xml │ └── values │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── castscreen.iml ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── receiver ├── Makefile ├── cs_receiver.c ├── cs_receiver.py ├── cs_receiver_conn.py ├── wait_adb.sh ├── wait_adb_arm.sh └── wait_adb_conn.sh └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea/workspace.xml 4 | /.idea/libraries 5 | .DS_Store 6 | /build 7 | /captures 8 | -------------------------------------------------------------------------------- /.idea/.name: -------------------------------------------------------------------------------- 1 | castscreen -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 19 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 46 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CastScreen 2 | Cast Android screen via WiFi or USB 3 | 4 | Demo video: https://youtu.be/D_DSuvFz_sg 5 | 6 | ## Requirments 7 | * Gstreamer 1.0 with H264 decoder (h264parse, avdec_h264) 8 | * adb for mirror via USB 9 | 10 | ## With native receiver 11 | * If you are not on an ARM machine, ignore outputs from *_arm targets, or remove them from the Makefile. 12 | * Compile the receiver 13 | ``` 14 | $ cd receiver 15 | $ make 16 | ``` 17 | ### Via WiFi 18 | 1. Launch receiver 19 | ``` 20 | $ cd receiver 21 | $ ./cs_receiver autovideosink 22 | ``` 23 | 2. Open CastScreen APP 24 | 3. Wait the receiver to appear on the list 25 | 4. Select the receiver 26 | 5. Tap **Start** on right corner 27 | 28 | ### Via USB 29 | 1. Enable debug mode on the Android device 30 | 2. Make sure adb is available on your PC 31 | 3. Open CastScreen APP 32 | 4. Select **Server mode** 33 | 5. Tap **Start** on right corner 34 | 6. Launch receiver 35 | ``` 36 | $ cd receiver 37 | $ ./wait_adb.sh 38 | ``` 39 | 40 | ## With python receiver 41 | ### Via WiFi 42 | 1. Launch receiver 43 | ``` 44 | $ cd receiver 45 | $ python cs_receiver.py 46 | ``` 47 | 2. Open CastScreen APP 48 | 3. Wait the receiver to appear on the list 49 | 4. Select the receiver 50 | 5. Tap **Start** on right corner 51 | 52 | ### Via USB 53 | 1. Enable debug mode on the Android device 54 | 2. Make sure adb is available on your PC 55 | 3. Open CastScreen APP 56 | 4. Select **Server mode** 57 | 5. Tap **Start** on right corner 58 | 6. Launch receiver 59 | ``` 60 | $ cd receiver 61 | $ adb forward tcp:53516 tcp:53515 62 | $ python cs_receiver_conn.py 63 | ``` 64 | 65 | ## Closing receivers 66 | ### Ubuntu 67 | Open system monitor, look up using the word receiver, and kill the process. 68 | 69 | ## Using an alternative app. 70 | You can use the receiver with the [All Cast Receiver App](https://play.google.com/store/apps/details?id=com.koushikdutta.cast.receiver&rdid=com.koushikdutta.cast.receiver) as well. Just start a receiver as described above (the native receiver is faster than the python one). 71 | 72 | ## License 73 | Copyright (c) 2015-2016 Jones Chi. Code released under the Apache License. 74 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/app.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 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 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 26 5 | 6 | defaultConfig { 7 | applicationId "com.yschi.castscreen" 8 | minSdkVersion 21 9 | targetSdkVersion 26 10 | versionCode 1 11 | versionName "1.0" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | compile fileTree(dir: 'libs', include: ['*.jar']) 23 | } 24 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /opt/AndroidSDK/adt-bundle-linux-x86_64-20131030/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/yschi/castscreen/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.yschi.castscreen; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 14 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/java/com/yschi/castscreen/CastService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Jones Chi 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yschi.castscreen; 18 | 19 | import android.app.Activity; 20 | import android.app.Notification; 21 | import android.app.NotificationManager; 22 | import android.app.PendingIntent; 23 | import android.app.Service; 24 | import android.content.BroadcastReceiver; 25 | import android.content.Context; 26 | import android.content.Intent; 27 | import android.content.IntentFilter; 28 | import android.hardware.display.VirtualDisplay; 29 | import android.media.MediaCodec; 30 | import android.media.MediaCodecInfo; 31 | import android.media.MediaFormat; 32 | import android.media.projection.MediaProjection; 33 | import android.media.projection.MediaProjectionManager; 34 | import android.os.Handler; 35 | import android.os.IBinder; 36 | import android.os.Message; 37 | import android.os.Messenger; 38 | import android.util.Log; 39 | import android.view.Surface; 40 | 41 | import java.io.BufferedReader; 42 | import java.io.IOException; 43 | import java.io.InputStreamReader; 44 | import java.io.OutputStream; 45 | import java.io.OutputStreamWriter; 46 | import java.net.InetAddress; 47 | import java.net.ServerSocket; 48 | import java.net.Socket; 49 | import java.net.UnknownHostException; 50 | import java.nio.ByteBuffer; 51 | import java.util.ArrayList; 52 | 53 | public class CastService extends Service { 54 | private final String TAG = "CastService"; 55 | private final int NT_ID_CASTING = 0; 56 | private Handler mHandler = new Handler(new ServiceHandlerCallback()); 57 | private Messenger mMessenger = new Messenger(mHandler); 58 | private ArrayList mClients = new ArrayList(); 59 | private IntentFilter mBroadcastIntentFilter; 60 | 61 | private static final String HTTP_MESSAGE_TEMPLATE = "POST /api/v1/h264 HTTP/1.1\r\n" + 62 | "Connection: close\r\n" + 63 | "X-WIDTH: %1$d\r\n" + 64 | "X-HEIGHT: %2$d\r\n" + 65 | "\r\n"; 66 | 67 | // 1280x720@25 68 | private static final byte[] H264_PREDEFINED_HEADER_1280x720 = { 69 | (byte)0x21, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, 70 | (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, 71 | (byte)0x67, (byte)0x42, (byte)0x80, (byte)0x20, (byte)0xda, (byte)0x01, (byte)0x40, (byte)0x16, 72 | (byte)0xe8, (byte)0x06, (byte)0xd0, (byte)0xa1, (byte)0x35, (byte)0x00, (byte)0x00, (byte)0x00, 73 | (byte)0x01, (byte)0x68, (byte)0xce, (byte)0x06, (byte)0xe2, (byte)0x32, (byte)0x24, (byte)0x00, 74 | (byte)0x00, (byte)0x7a, (byte)0x83, (byte)0x3d, (byte)0xae, (byte)0x37, (byte)0x00, (byte)0x00}; 75 | 76 | // 800x480@25 77 | private static final byte[] H264_PREDEFINED_HEADER_800x480 = { 78 | (byte)0x21, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, 79 | (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, 80 | (byte)0x67, (byte)0x42, (byte)0x80, (byte)0x20, (byte)0xda, (byte)0x03, (byte)0x20, (byte)0xf6, 81 | (byte)0x80, (byte)0x6d, (byte)0x0a, (byte)0x13, (byte)0x50, (byte)0x00, (byte)0x00, (byte)0x00, 82 | (byte)0x01, (byte)0x68, (byte)0xce, (byte)0x06, (byte)0xe2, (byte)0x32, (byte)0x24, (byte)0x00, 83 | (byte)0x00, (byte)0x7a, (byte)0x83, (byte)0x3d, (byte)0xae, (byte)0x37, (byte)0x00, (byte)0x00}; 84 | 85 | private MediaProjectionManager mMediaProjectionManager; 86 | private String mReceiverIp; 87 | private int mResultCode; 88 | private Intent mResultData; 89 | private String mSelectedFormat; 90 | private int mSelectedWidth; 91 | private int mSelectedHeight; 92 | private int mSelectedDpi; 93 | private int mSelectedBitrate; 94 | //private boolean mMuxerStarted = false; 95 | private MediaProjection mMediaProjection; 96 | private VirtualDisplay mVirtualDisplay; 97 | private Surface mInputSurface; 98 | //private MediaMuxer mMuxer; 99 | private MediaCodec mVideoEncoder; 100 | private MediaCodec.BufferInfo mVideoBufferInfo; 101 | //private int mTrackIndex = -1; 102 | private ServerSocket mServerSocket; 103 | private Socket mSocket; 104 | private OutputStream mSocketOutputStream; 105 | private IvfWriter mIvfWriter; 106 | private Handler mDrainHandler = new Handler(); 107 | private Runnable mStartEncodingRunnable = new Runnable() { 108 | @Override 109 | public void run() { 110 | if (!startScreenCapture()) { 111 | Log.e(TAG, "Failed to start capturing screen"); 112 | } 113 | } 114 | }; 115 | private Runnable mDrainEncoderRunnable = new Runnable() { 116 | @Override 117 | public void run() { 118 | drainEncoder(); 119 | } 120 | }; 121 | 122 | private class ServiceHandlerCallback implements Handler.Callback { 123 | @Override 124 | public boolean handleMessage(Message msg) { 125 | Log.d(TAG, "Handler got event, what: " + msg.what); 126 | switch (msg.what) { 127 | case Common.MSG_REGISTER_CLIENT: { 128 | mClients.add(msg.replyTo); 129 | break; 130 | } 131 | case Common.MSG_UNREGISTER_CLIENT: { 132 | mClients.remove(msg.replyTo); 133 | break; 134 | } 135 | case Common.MSG_STOP_CAST: { 136 | stopScreenCapture(); 137 | closeSocket(true); 138 | stopSelf(); 139 | } 140 | } 141 | return false; 142 | } 143 | } 144 | 145 | private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { 146 | @Override 147 | public void onReceive(Context context, Intent intent) { 148 | String action = intent.getAction(); 149 | Log.d(TAG, "Service receive broadcast action: " + action); 150 | if (action == null) { 151 | return; 152 | } 153 | if (Common.ACTION_STOP_CAST.equals(action)) { 154 | stopScreenCapture(); 155 | closeSocket(true); 156 | stopSelf(); 157 | } 158 | } 159 | }; 160 | 161 | @Override 162 | public void onCreate() { 163 | super.onCreate(); 164 | mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE); 165 | mBroadcastIntentFilter = new IntentFilter(); 166 | mBroadcastIntentFilter.addAction(Common.ACTION_STOP_CAST); 167 | registerReceiver(mBroadcastReceiver, mBroadcastIntentFilter); 168 | } 169 | 170 | @Override 171 | public void onDestroy() { 172 | super.onDestroy(); 173 | Log.d(TAG, "Destroy service"); 174 | stopScreenCapture(); 175 | closeSocket(true); 176 | unregisterReceiver(mBroadcastReceiver); 177 | } 178 | 179 | @Override 180 | public int onStartCommand(Intent intent, int flags, int startId) { 181 | if (intent == null) { 182 | return START_NOT_STICKY; 183 | } 184 | mReceiverIp = intent.getStringExtra(Common.EXTRA_RECEIVER_IP); 185 | mResultCode = intent.getIntExtra(Common.EXTRA_RESULT_CODE, -1); 186 | mResultData = intent.getParcelableExtra(Common.EXTRA_RESULT_DATA); 187 | Log.d(TAG, "Remove IP: " + mReceiverIp); 188 | if (mReceiverIp == null) { 189 | return START_NOT_STICKY; 190 | } 191 | //if (mResultCode != Activity.RESULT_OK || mResultData == null) { 192 | // Log.e(TAG, "Failed to start service, mResultCode: " + mResultCode + ", mResultData: " + mResultData); 193 | // return START_NOT_STICKY; 194 | //} 195 | mSelectedWidth = intent.getIntExtra(Common.EXTRA_SCREEN_WIDTH, Common.DEFAULT_SCREEN_WIDTH); 196 | mSelectedHeight = intent.getIntExtra(Common.EXTRA_SCREEN_HEIGHT, Common.DEFAULT_SCREEN_HEIGHT); 197 | mSelectedDpi = intent.getIntExtra(Common.EXTRA_SCREEN_DPI, Common.DEFAULT_SCREEN_DPI); 198 | mSelectedBitrate = intent.getIntExtra(Common.EXTRA_VIDEO_BITRATE, Common.DEFAULT_VIDEO_BITRATE); 199 | mSelectedFormat = intent.getStringExtra(Common.EXTRA_VIDEO_FORMAT); 200 | if (mSelectedFormat == null) { 201 | mSelectedFormat = Common.DEFAULT_VIDEO_MIME_TYPE; 202 | } 203 | if (mReceiverIp.length() <= 0) { 204 | Log.d(TAG, "Start with listen mode"); 205 | if (!createServerSocket()) { 206 | Log.e(TAG, "Failed to create socket to receiver, ip: " + mReceiverIp); 207 | return START_NOT_STICKY; 208 | } 209 | } else { 210 | Log.d(TAG, "Start with client mode"); 211 | if (!createSocket()) { 212 | Log.e(TAG, "Failed to create socket to receiver, ip: " + mReceiverIp); 213 | return START_NOT_STICKY; 214 | } 215 | if (!startScreenCapture()) { 216 | Log.e(TAG, "Failed to start capture screen"); 217 | return START_NOT_STICKY; 218 | } 219 | } 220 | return START_STICKY; 221 | } 222 | 223 | @Override 224 | public IBinder onBind(Intent intent) { 225 | return mMessenger.getBinder(); 226 | } 227 | 228 | private void showNotification() { 229 | final Intent notificationIntent = new Intent(Common.ACTION_STOP_CAST); 230 | PendingIntent notificationPendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 231 | Notification.Builder builder = new Notification.Builder(this); 232 | builder.setSmallIcon(R.mipmap.ic_launcher) 233 | .setDefaults(Notification.DEFAULT_ALL) 234 | .setOnlyAlertOnce(true) 235 | .setOngoing(true) 236 | .setContentTitle(getString(R.string.app_name)) 237 | .setContentText(getString(R.string.casting_screen)) 238 | .addAction(android.R.drawable.ic_menu_close_clear_cancel, getString(R.string.action_stop), notificationPendingIntent); 239 | NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 240 | notificationManager.notify(NT_ID_CASTING, builder.build()); 241 | } 242 | 243 | private void dismissNotification() { 244 | NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 245 | notificationManager.cancel(NT_ID_CASTING); 246 | } 247 | 248 | private boolean startScreenCapture() { 249 | Log.d(TAG, "mResultCode: " + mResultCode + ", mResultData: " + mResultData); 250 | if (mResultCode != 0 && mResultData != null) { 251 | setUpMediaProjection(); 252 | startRecording(); 253 | showNotification(); 254 | return true; 255 | } 256 | return false; 257 | } 258 | 259 | private void setUpMediaProjection() { 260 | mMediaProjection = mMediaProjectionManager.getMediaProjection(mResultCode, mResultData); 261 | } 262 | 263 | private void startRecording() { 264 | Log.d(TAG, "startRecording"); 265 | prepareVideoEncoder(); 266 | 267 | //try { 268 | // mMuxer = new MediaMuxer("/sdcard/video.mp4", MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4); 269 | //} catch (IOException ioe) { 270 | // throw new RuntimeException("MediaMuxer creation failed", ioe); 271 | //} 272 | 273 | // Start the video input. 274 | mVirtualDisplay = mMediaProjection.createVirtualDisplay("Recording Display", mSelectedWidth, 275 | mSelectedHeight, mSelectedDpi, 0 /* flags */, mInputSurface, 276 | null /* callback */, null /* handler */); 277 | 278 | // Start the encoders 279 | drainEncoder(); 280 | } 281 | 282 | private void prepareVideoEncoder() { 283 | mVideoBufferInfo = new MediaCodec.BufferInfo(); 284 | MediaFormat format = MediaFormat.createVideoFormat(mSelectedFormat, mSelectedWidth, mSelectedHeight); 285 | int frameRate = Common.DEFAULT_VIDEO_FPS; 286 | 287 | // Set some required properties. The media codec may fail if these aren't defined. 288 | format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); 289 | format.setInteger(MediaFormat.KEY_BIT_RATE, mSelectedBitrate); 290 | format.setInteger(MediaFormat.KEY_FRAME_RATE, frameRate); 291 | format.setInteger(MediaFormat.KEY_CAPTURE_RATE, frameRate); 292 | format.setInteger(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, 1000000 / frameRate); 293 | format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1); 294 | format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1); // 1 seconds between I-frames 295 | 296 | // Create a MediaCodec encoder and configure it. Get a Surface we can use for recording into. 297 | try { 298 | mVideoEncoder = MediaCodec.createEncoderByType(mSelectedFormat); 299 | mVideoEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); 300 | mInputSurface = mVideoEncoder.createInputSurface(); 301 | mVideoEncoder.start(); 302 | } catch (IOException e) { 303 | Log.e(TAG, "Failed to initial encoder, e: " + e); 304 | releaseEncoders(); 305 | } 306 | } 307 | 308 | private boolean drainEncoder() { 309 | mDrainHandler.removeCallbacks(mDrainEncoderRunnable); 310 | while (true) { 311 | int bufferIndex = mVideoEncoder.dequeueOutputBuffer(mVideoBufferInfo, 0); 312 | 313 | if (bufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) { 314 | // nothing available yet 315 | break; 316 | } else if (bufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { 317 | // should happen before receiving buffers, and should only happen once 318 | //if (mTrackIndex >= 0) { 319 | // throw new RuntimeException("format changed twice"); 320 | //} 321 | //mTrackIndex = mMuxer.addTrack(mVideoEncoder.getOutputFormat()); 322 | //if (!mMuxerStarted && mTrackIndex >= 0) { 323 | // mMuxer.start(); 324 | // mMuxerStarted = true; 325 | //} 326 | } else if (bufferIndex < 0) { 327 | // not sure what's going on, ignore it 328 | } else { 329 | ByteBuffer encodedData = mVideoEncoder.getOutputBuffer(bufferIndex); 330 | if (encodedData == null) { 331 | throw new RuntimeException("couldn't fetch buffer at index " + bufferIndex); 332 | } 333 | // Fixes playability issues on certain h264 decoders including omxh264dec on raspberry pi 334 | // See http://stackoverflow.com/a/26684736/4683709 for explanation 335 | //if ((mVideoBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) { 336 | // mVideoBufferInfo.size = 0; 337 | //} 338 | 339 | //Log.d(TAG, "Video buffer offset: " + mVideoBufferInfo.offset + ", size: " + mVideoBufferInfo.size); 340 | if (mVideoBufferInfo.size != 0) { 341 | encodedData.position(mVideoBufferInfo.offset); 342 | encodedData.limit(mVideoBufferInfo.offset + mVideoBufferInfo.size); 343 | if (mSocketOutputStream != null) { 344 | try { 345 | byte[] b = new byte[encodedData.remaining()]; 346 | encodedData.get(b); 347 | if (mIvfWriter != null) { 348 | mIvfWriter.writeFrame(b, mVideoBufferInfo.presentationTimeUs); 349 | } else { 350 | mSocketOutputStream.write(b); 351 | } 352 | } catch (IOException e) { 353 | Log.d(TAG, "Failed to write data to socket, stop casting"); 354 | e.printStackTrace(); 355 | stopScreenCapture(); 356 | return false; 357 | } 358 | } 359 | /* 360 | if (mMuxerStarted) { 361 | encodedData.position(mVideoBufferInfo.offset); 362 | encodedData.limit(mVideoBufferInfo.offset + mVideoBufferInfo.size); 363 | try { 364 | if (mSocketOutputStream != null) { 365 | byte[] b = new byte[encodedData.remaining()]; 366 | encodedData.get(b); 367 | mSocketOutputStream.write(b); 368 | } 369 | } catch (IOException e) { 370 | e.printStackTrace(); 371 | } 372 | mMuxer.writeSampleData(mTrackIndex, encodedData, mVideoBufferInfo); 373 | } else { 374 | // muxer not started 375 | } 376 | */ 377 | } 378 | 379 | mVideoEncoder.releaseOutputBuffer(bufferIndex, false); 380 | 381 | if ((mVideoBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { 382 | break; 383 | } 384 | } 385 | } 386 | 387 | mDrainHandler.postDelayed(mDrainEncoderRunnable, 10); 388 | return true; 389 | } 390 | 391 | private void stopScreenCapture() { 392 | dismissNotification(); 393 | releaseEncoders(); 394 | closeSocket(); 395 | if (mVirtualDisplay == null) { 396 | return; 397 | } 398 | mVirtualDisplay.release(); 399 | mVirtualDisplay = null; 400 | } 401 | 402 | private void releaseEncoders() { 403 | mDrainHandler.removeCallbacks(mDrainEncoderRunnable); 404 | /* 405 | if (mMuxer != null) { 406 | if (mMuxerStarted) { 407 | mMuxer.stop(); 408 | } 409 | mMuxer.release(); 410 | mMuxer = null; 411 | mMuxerStarted = false; 412 | } 413 | */ 414 | if (mVideoEncoder != null) { 415 | mVideoEncoder.stop(); 416 | mVideoEncoder.release(); 417 | mVideoEncoder = null; 418 | } 419 | if (mInputSurface != null) { 420 | mInputSurface.release(); 421 | mInputSurface = null; 422 | } 423 | if (mMediaProjection != null) { 424 | mMediaProjection.stop(); 425 | mMediaProjection = null; 426 | } 427 | if (mIvfWriter != null) { 428 | mIvfWriter = null; 429 | } 430 | //mResultCode = 0; 431 | //mResultData = null; 432 | mVideoBufferInfo = null; 433 | //mTrackIndex = -1; 434 | } 435 | 436 | private boolean createServerSocket() { 437 | Thread th = new Thread(new Runnable() { 438 | @Override 439 | public void run() { 440 | try { 441 | mServerSocket = new ServerSocket(Common.VIEWER_PORT); 442 | while (!Thread.currentThread().isInterrupted() && !mServerSocket.isClosed()) { 443 | mSocket = mServerSocket.accept(); 444 | CommunicationThread commThread = new CommunicationThread(mSocket); 445 | new Thread(commThread).start(); 446 | } 447 | } catch (IOException e) { 448 | Log.e(TAG, "Failed to create server socket or server socket error"); 449 | e.printStackTrace(); 450 | } 451 | } 452 | }); 453 | th.start(); 454 | return true; 455 | } 456 | 457 | class CommunicationThread implements Runnable { 458 | private Socket mClientSocket; 459 | 460 | public CommunicationThread(Socket clientSocket) { 461 | mClientSocket = clientSocket; 462 | } 463 | 464 | public void run() { 465 | while (!Thread.currentThread().isInterrupted()) { 466 | try { 467 | BufferedReader input = new BufferedReader(new InputStreamReader(mClientSocket.getInputStream())); 468 | String data = input.readLine(); 469 | Log.d(TAG, "Got data from socket: " + data); 470 | if (data == null || !data.equalsIgnoreCase("mirror")) { 471 | mClientSocket.close(); 472 | return; 473 | } 474 | mSocketOutputStream = mClientSocket.getOutputStream(); 475 | OutputStreamWriter osw = new OutputStreamWriter(mSocketOutputStream); 476 | osw.write(String.format(HTTP_MESSAGE_TEMPLATE, mSelectedWidth, mSelectedHeight)); 477 | osw.flush(); 478 | mSocketOutputStream.flush(); 479 | if (mSelectedFormat.equals(MediaFormat.MIMETYPE_VIDEO_AVC)) { 480 | if (mSelectedWidth == 1280 && mSelectedHeight == 720) { 481 | mSocketOutputStream.write(H264_PREDEFINED_HEADER_1280x720); 482 | } else if (mSelectedWidth == 800 && mSelectedHeight == 480) { 483 | mSocketOutputStream.write(H264_PREDEFINED_HEADER_800x480); 484 | } else { 485 | Log.e(TAG, "Unknown width: " + mSelectedWidth + ", height: " + mSelectedHeight); 486 | mSocketOutputStream.close(); 487 | mClientSocket.close(); 488 | mClientSocket = null; 489 | mSocketOutputStream = null; 490 | } 491 | } else if (mSelectedFormat.equals(MediaFormat.MIMETYPE_VIDEO_VP8)) { 492 | mIvfWriter = new IvfWriter(mSocketOutputStream, mSelectedWidth, mSelectedHeight); 493 | mIvfWriter.writeHeader(); 494 | } else { 495 | Log.e(TAG, "Unknown format: " + mSelectedFormat); 496 | mSocketOutputStream.close(); 497 | mClientSocket.close(); 498 | mClientSocket = null; 499 | mSocketOutputStream = null; 500 | } 501 | if (mSocketOutputStream != null) { 502 | mHandler.post(mStartEncodingRunnable); 503 | } 504 | return; 505 | } catch (UnknownHostException e) { 506 | e.printStackTrace(); 507 | } catch (IOException e) { 508 | e.printStackTrace(); 509 | } 510 | mClientSocket = null; 511 | mSocketOutputStream = null; 512 | } 513 | } 514 | } 515 | 516 | private boolean createSocket() { 517 | Thread th = new Thread(new Runnable() { 518 | @Override 519 | public void run() { 520 | try { 521 | InetAddress serverAddr = InetAddress.getByName(mReceiverIp); 522 | mSocket = new Socket(serverAddr, Common.VIEWER_PORT); 523 | mSocketOutputStream = mSocket.getOutputStream(); 524 | OutputStreamWriter osw = new OutputStreamWriter(mSocketOutputStream); 525 | osw.write(String.format(HTTP_MESSAGE_TEMPLATE, mSelectedWidth, mSelectedHeight)); 526 | osw.flush(); 527 | mSocketOutputStream.flush(); 528 | if (mSelectedFormat.equals(MediaFormat.MIMETYPE_VIDEO_AVC)) { 529 | if (mSelectedWidth == 1280 && mSelectedHeight == 720) { 530 | mSocketOutputStream.write(H264_PREDEFINED_HEADER_1280x720); 531 | } else if (mSelectedWidth == 800 && mSelectedHeight == 480) { 532 | mSocketOutputStream.write(H264_PREDEFINED_HEADER_800x480); 533 | } else { 534 | Log.e(TAG, "Unknown width: " + mSelectedWidth + ", height: " + mSelectedHeight); 535 | mSocketOutputStream.close(); 536 | mSocket.close(); 537 | mSocket = null; 538 | mSocketOutputStream = null; 539 | } 540 | } else if (mSelectedFormat.equals(MediaFormat.MIMETYPE_VIDEO_VP8)) { 541 | mIvfWriter = new IvfWriter(mSocketOutputStream, mSelectedWidth, mSelectedHeight); 542 | mIvfWriter.writeHeader(); 543 | } else { 544 | Log.e(TAG, "Unknown format: " + mSelectedFormat); 545 | mSocketOutputStream.close(); 546 | mSocket.close(); 547 | mSocket = null; 548 | mSocketOutputStream = null; 549 | } 550 | return; 551 | } catch (UnknownHostException e) { 552 | e.printStackTrace(); 553 | } catch (IOException e) { 554 | e.printStackTrace(); 555 | } 556 | mSocket = null; 557 | mSocketOutputStream = null; 558 | } 559 | }); 560 | th.start(); 561 | try { 562 | th.join(); 563 | if (mSocket != null && mSocketOutputStream != null) { 564 | return true; 565 | } 566 | } catch (InterruptedException e) { 567 | e.printStackTrace(); 568 | } 569 | return false; 570 | } 571 | 572 | private void closeSocket() { 573 | closeSocket(false); 574 | } 575 | 576 | private void closeSocket(boolean closeServerSocket) { 577 | if (mSocket != null) { 578 | try { 579 | mSocket.close(); 580 | } catch (IOException e) { 581 | e.printStackTrace(); 582 | } 583 | } 584 | if (closeServerSocket) { 585 | if (mServerSocket != null) { 586 | try { 587 | mServerSocket.close(); 588 | } catch (IOException e) { 589 | e.printStackTrace(); 590 | } 591 | } 592 | mServerSocket = null; 593 | } 594 | mSocket = null; 595 | mSocketOutputStream = null; 596 | } 597 | } 598 | -------------------------------------------------------------------------------- /app/src/main/java/com/yschi/castscreen/Common.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Jones Chi 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yschi.castscreen; 18 | 19 | import android.media.MediaFormat; 20 | 21 | /** 22 | * Created by yschi on 2015/5/28. 23 | */ 24 | public class Common { 25 | public static final int VIEWER_PORT = 53515; 26 | 27 | public static final int DISCOVER_PORT = 53515; 28 | public static final String DISCOVER_MESSAGE = "hello"; 29 | 30 | public static final int DEFAULT_SCREEN_WIDTH = 1280; 31 | public static final int DEFAULT_SCREEN_HEIGHT = 720; 32 | public static final int DEFAULT_SCREEN_DPI = 320; 33 | public static final int DEFAULT_VIDEO_BITRATE = 6144000; 34 | public static final int DEFAULT_VIDEO_FPS = 25; 35 | public static final String DEFAULT_VIDEO_MIME_TYPE = MediaFormat.MIMETYPE_VIDEO_AVC; 36 | 37 | // Activity to service 38 | public static final int MSG_REGISTER_CLIENT = 200; 39 | public static final int MSG_UNREGISTER_CLIENT = 201; 40 | public static final int MSG_STOP_CAST = 301; 41 | 42 | public static final String EXTRA_RESULT_CODE = "result_code"; 43 | public static final String EXTRA_RESULT_DATA = "result_data"; 44 | public static final String EXTRA_RECEIVER_IP = "receiver_ip"; 45 | 46 | public static final String EXTRA_SCREEN_WIDTH = "screen_width"; 47 | public static final String EXTRA_SCREEN_HEIGHT = "screen_height"; 48 | public static final String EXTRA_SCREEN_DPI = "screen_dpi"; 49 | public static final String EXTRA_VIDEO_FORMAT = "video_format"; 50 | public static final String EXTRA_VIDEO_BITRATE = "video_bitrate"; 51 | 52 | public static final String ACTION_STOP_CAST = "com.yschi.castscreen.ACTION_STOP_CAST"; 53 | } 54 | -------------------------------------------------------------------------------- /app/src/main/java/com/yschi/castscreen/IvfWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yschi.castscreen; 18 | 19 | import java.io.IOException; 20 | import java.io.OutputStream; 21 | import java.io.RandomAccessFile; 22 | 23 | /** 24 | * Writes an IVF file. 25 | * 26 | * IVF format is a simple container format for VP8 encoded frames defined at 27 | * http://wiki.multimedia.cx/index.php?title=IVF. 28 | */ 29 | 30 | public class IvfWriter { 31 | private static final byte HEADER_END = 32; 32 | //private RandomAccessFile mOutputFile; 33 | private OutputStream mOutputStream; 34 | private int mWidth; 35 | private int mHeight; 36 | private int mScale; 37 | private int mRate; 38 | private int mFrameCount; 39 | 40 | /** 41 | * Initializes the IVF file writer. 42 | * 43 | * Timebase fraction is in format scale/rate, e.g. 1/1000 44 | * Timestamp values supplied while writing frames should be in accordance 45 | * with this timebase value. 46 | * 47 | * @param filename name of the IVF file 48 | * @param width frame width 49 | * @param height frame height 50 | * @param scale timebase scale (or numerator of the timebase fraction) 51 | * @param rate timebase rate (or denominator of the timebase fraction) 52 | */ 53 | public IvfWriter(OutputStream outputStream, 54 | int width, int height, 55 | int scale, int rate) throws IOException { 56 | //mOutputFile = new RandomAccessFile(filename, "rw"); 57 | mOutputStream = outputStream; 58 | mWidth = width; 59 | mHeight = height; 60 | mScale = scale; 61 | mRate = rate; 62 | mFrameCount = 0; 63 | //mOutputFile.setLength(0); 64 | //mOutputFile.seek(HEADER_END); // Skip the header for now, as framecount is unknown 65 | } 66 | 67 | /** 68 | * Initializes the IVF file writer with a microsecond timebase. 69 | * 70 | * Microsecond timebase is default for OMX thus stagefright. 71 | * 72 | * @param filename name of the IVF file 73 | * @param width frame width 74 | * @param height frame height 75 | */ 76 | public IvfWriter(OutputStream outputStream, int width, int height) throws IOException { 77 | this(outputStream, width, height, 1, 1000000); 78 | } 79 | 80 | /** 81 | * Finalizes the IVF header and closes the file. 82 | */ 83 | public void close() throws IOException{ 84 | // Write header now 85 | //mOutputFile.seek(0); 86 | //mOutputFile.write(makeIvfHeader(mFrameCount, mWidth, mHeight, mScale, mRate)); 87 | //mOutputFile.close(); 88 | mOutputStream.close(); 89 | } 90 | 91 | 92 | public void writeHeader() throws IOException { 93 | mOutputStream.write(makeIvfHeader(mFrameCount, mWidth, mHeight, mScale, mRate)); 94 | } 95 | 96 | /** 97 | * Writes a single encoded VP8 frame with its frame header. 98 | * 99 | * @param frame actual contents of the encoded frame data 100 | * @param timeStamp timestamp of the frame (in accordance to specified timebase) 101 | */ 102 | public void writeFrame(byte[] frame, long timeStamp) throws IOException { 103 | mOutputStream.write(makeIvfFrameHeader(frame.length, timeStamp)); 104 | mOutputStream.write(frame); 105 | mFrameCount++; 106 | } 107 | 108 | /** 109 | * Makes a 32 byte file header for IVF format. 110 | * 111 | * Timebase fraction is in format scale/rate, e.g. 1/1000 112 | * 113 | * @param frameCount total number of frames file contains 114 | * @param width frame width 115 | * @param height frame height 116 | * @param scale timebase scale (or numerator of the timebase fraction) 117 | * @param rate timebase rate (or denominator of the timebase fraction) 118 | */ 119 | public static byte[] makeIvfHeader(int frameCount, int width, int height, int scale, int rate){ 120 | byte[] ivfHeader = new byte[32]; 121 | ivfHeader[0] = 'D'; 122 | ivfHeader[1] = 'K'; 123 | ivfHeader[2] = 'I'; 124 | ivfHeader[3] = 'F'; 125 | lay16Bits(ivfHeader, 4, 0); // version 126 | lay16Bits(ivfHeader, 6, 32); // header size 127 | ivfHeader[8] = 'V'; // fourcc 128 | ivfHeader[9] = 'P'; 129 | ivfHeader[10] = '8'; 130 | ivfHeader[11] = '0'; 131 | lay16Bits(ivfHeader, 12, width); 132 | lay16Bits(ivfHeader, 14, height); 133 | lay32Bits(ivfHeader, 16, rate); // scale/rate 134 | lay32Bits(ivfHeader, 20, scale); 135 | lay32Bits(ivfHeader, 24, frameCount); 136 | lay32Bits(ivfHeader, 28, 0); // unused 137 | return ivfHeader; 138 | } 139 | 140 | /** 141 | * Makes a 12 byte header for an encoded frame. 142 | * 143 | * @param size frame size 144 | * @param timestamp presentation timestamp of the frame 145 | */ 146 | private static byte[] makeIvfFrameHeader(int size, long timestamp){ 147 | byte[] frameHeader = new byte[12]; 148 | lay32Bits(frameHeader, 0, size); 149 | lay64bits(frameHeader, 4, timestamp); 150 | return frameHeader; 151 | } 152 | 153 | 154 | /** 155 | * Lays least significant 16 bits of an int into 2 items of a byte array. 156 | * 157 | * Note that ordering is little-endian. 158 | * 159 | * @param array the array to be modified 160 | * @param index index of the array to start laying down 161 | * @param value the integer to use least significant 16 bits 162 | */ 163 | private static void lay16Bits(byte[] array, int index, int value){ 164 | array[index] = (byte) (value); 165 | array[index + 1] = (byte) (value >> 8); 166 | } 167 | 168 | /** 169 | * Lays an int into 4 items of a byte array. 170 | * 171 | * Note that ordering is little-endian. 172 | * 173 | * @param array the array to be modified 174 | * @param index index of the array to start laying down 175 | * @param value the integer to use 176 | */ 177 | private static void lay32Bits(byte[] array, int index, int value){ 178 | for (int i = 0; i < 4; i++){ 179 | array[index + i] = (byte) (value >> (i * 8)); 180 | } 181 | } 182 | 183 | /** 184 | * Lays a long int into 8 items of a byte array. 185 | * 186 | * Note that ordering is little-endian. 187 | * 188 | * @param array the array to be modified 189 | * @param index index of the array to start laying down 190 | * @param value the integer to use 191 | */ 192 | private static void lay64bits(byte[] array, int index, long value){ 193 | for (int i = 0; i < 8; i++){ 194 | array[index + i] = (byte) (value >> (i * 8)); 195 | } 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /app/src/main/java/com/yschi/castscreen/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Jones Chi 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yschi.castscreen; 18 | 19 | import android.app.Activity; 20 | import android.content.ComponentName; 21 | import android.content.Context; 22 | import android.content.Intent; 23 | import android.content.ServiceConnection; 24 | import android.media.MediaFormat; 25 | import android.media.projection.MediaProjectionManager; 26 | import android.os.AsyncTask; 27 | import android.os.Bundle; 28 | import android.os.Handler; 29 | import android.os.IBinder; 30 | import android.os.Message; 31 | import android.os.Messenger; 32 | import android.os.RemoteException; 33 | import android.util.Log; 34 | import android.view.Menu; 35 | import android.view.MenuItem; 36 | import android.view.View; 37 | import android.widget.AdapterView; 38 | import android.widget.ArrayAdapter; 39 | import android.widget.Button; 40 | import android.widget.EditText; 41 | import android.widget.ListView; 42 | import android.widget.Spinner; 43 | import android.widget.TextView; 44 | import android.widget.Toast; 45 | 46 | import org.json.JSONException; 47 | import org.json.JSONObject; 48 | 49 | import java.io.IOException; 50 | import java.net.DatagramPacket; 51 | import java.net.DatagramSocket; 52 | import java.net.SocketException; 53 | import java.net.SocketTimeoutException; 54 | import java.util.Arrays; 55 | import java.util.HashMap; 56 | 57 | 58 | public class MainActivity extends Activity { 59 | private static final String TAG = "MainActivity"; 60 | 61 | private static final String PREF_COMMON = "common"; 62 | private static final String PREF_KEY_INPUT_RECEIVER = "input_receiver"; 63 | private static final String PREF_KEY_FORMAT = "format"; 64 | private static final String PREF_KEY_RECEIVER = "receiver"; 65 | private static final String PREF_KEY_RESOLUTION = "resolution"; 66 | private static final String PREF_KEY_BITRATE = "bitrate"; 67 | 68 | private static final String[] FORMAT_OPTIONS = { 69 | MediaFormat.MIMETYPE_VIDEO_AVC, 70 | MediaFormat.MIMETYPE_VIDEO_VP8 71 | }; 72 | 73 | private static final int[][] RESOLUTION_OPTIONS = { 74 | {1280, 720, 320}, 75 | {800, 480, 160} 76 | }; 77 | 78 | private static final int[] BITRATE_OPTIONS = { 79 | 6144000, // 6 Mbps 80 | 4096000, // 4 Mbps 81 | 2048000, // 2 Mbps 82 | 1024000 // 1 Mbps 83 | }; 84 | 85 | private static final int REQUEST_MEDIA_PROJECTION = 100; 86 | private static final String STATE_RESULT_CODE = "result_code"; 87 | private static final String STATE_RESULT_DATA = "result_data"; 88 | 89 | private Context mContext; 90 | private MediaProjectionManager mMediaProjectionManager; 91 | private Handler mHandler = new Handler(new HandlerCallback()); 92 | private Messenger mMessenger = new Messenger(mHandler); 93 | private Messenger mServiceMessenger = null; 94 | private TextView mReceiverTextView; 95 | private ListView mDiscoverListView; 96 | private ArrayAdapter mDiscoverAdapter; 97 | private HashMap mDiscoverdMap; 98 | private String mSelectedFormat = FORMAT_OPTIONS[0]; 99 | private int mSelectedWidth = RESOLUTION_OPTIONS[0][0]; 100 | private int mSelectedHeight = RESOLUTION_OPTIONS[0][1]; 101 | private int mSelectedDpi = RESOLUTION_OPTIONS[0][2]; 102 | private int mSelectedBitrate = BITRATE_OPTIONS[0]; 103 | private String mReceiverIp = ""; 104 | private DiscoveryTask mDiscoveryTask; 105 | private int mResultCode; 106 | private Intent mResultData; 107 | 108 | private class HandlerCallback implements Handler.Callback { 109 | public boolean handleMessage(Message msg) { 110 | Log.d(TAG, "Handler got event, what: " + msg.what); 111 | return false; 112 | } 113 | } 114 | 115 | private ServiceConnection mServiceConnection = new ServiceConnection() { 116 | @Override 117 | public void onServiceConnected(ComponentName name, IBinder service) { 118 | Log.d(TAG, "Service connected, name: " + name); 119 | mServiceMessenger = new Messenger(service); 120 | try { 121 | Message msg = Message.obtain(null, Common.MSG_REGISTER_CLIENT); 122 | msg.replyTo = mMessenger; 123 | mServiceMessenger.send(msg); 124 | Log.d(TAG, "Connected to service, send register client back"); 125 | } catch (RemoteException e) { 126 | Log.d(TAG, "Failed to send message back to service, e: " + e.toString()); 127 | e.printStackTrace(); 128 | } 129 | } 130 | 131 | @Override 132 | public void onServiceDisconnected(ComponentName name) { 133 | Log.d(TAG, "Service disconnected, name: " + name); 134 | mServiceMessenger = null; 135 | } 136 | }; 137 | 138 | 139 | @Override 140 | protected void onCreate(Bundle savedInstanceState) { 141 | super.onCreate(savedInstanceState); 142 | setContentView(R.layout.activity_main); 143 | 144 | if (savedInstanceState != null) { 145 | mResultCode = savedInstanceState.getInt(STATE_RESULT_CODE); 146 | mResultData = savedInstanceState.getParcelable(STATE_RESULT_DATA); 147 | } 148 | 149 | mContext = this; 150 | mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE); 151 | 152 | mDiscoverdMap = new HashMap<>(); 153 | mDiscoverListView = (ListView) findViewById(R.id.discover_listview); 154 | mDiscoverAdapter = new ArrayAdapter<>(this, 155 | android.R.layout.simple_list_item_1); 156 | mDiscoverAdapter.addAll(mDiscoverdMap.keySet()); 157 | mDiscoverListView.setAdapter(mDiscoverAdapter); 158 | mDiscoverListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 159 | @Override 160 | public void onItemClick(AdapterView adapterView, View view, int i, long l) { 161 | String name = mDiscoverAdapter.getItem(i); 162 | String ip = mDiscoverdMap.get(name); 163 | Log.d(TAG, "Select receiver name: " + name + ", ip: " + ip); 164 | mReceiverIp = ip; 165 | updateReceiverStatus(); 166 | mContext.getSharedPreferences(PREF_COMMON, 0).edit().putString(PREF_KEY_RECEIVER, mReceiverIp).commit(); 167 | } 168 | }); 169 | 170 | // add server mode option 171 | mDiscoverAdapter.add(mContext.getString(R.string.server_mode)); 172 | mDiscoverdMap.put(mContext.getString(R.string.server_mode), ""); 173 | 174 | mReceiverTextView = (TextView) findViewById(R.id.receiver_textview); 175 | final EditText ipEditText = (EditText) findViewById(R.id.ip_edittext); 176 | final Button selectButton = (Button) findViewById(R.id.select_button); 177 | selectButton.setOnClickListener(new View.OnClickListener() { 178 | @Override 179 | public void onClick(View view) { 180 | if (ipEditText.getText().length() > 0) { 181 | mReceiverIp = ipEditText.getText().toString(); 182 | Log.d(TAG, "Using ip: " + mReceiverIp); 183 | updateReceiverStatus(); 184 | mContext.getSharedPreferences(PREF_COMMON, 0).edit().putString(PREF_KEY_INPUT_RECEIVER, mReceiverIp).commit(); 185 | mContext.getSharedPreferences(PREF_COMMON, 0).edit().putString(PREF_KEY_RECEIVER, mReceiverIp).commit(); 186 | } 187 | } 188 | }); 189 | ipEditText.setText(mContext.getSharedPreferences(PREF_COMMON, 0).getString(PREF_KEY_INPUT_RECEIVER, "")); 190 | 191 | Spinner formatSpinner = (Spinner) findViewById(R.id.format_spinner); 192 | ArrayAdapter formatAdapter = ArrayAdapter.createFromResource(this, 193 | R.array.format_options, android.R.layout.simple_spinner_item); 194 | formatAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 195 | formatSpinner.setAdapter(formatAdapter); 196 | formatSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 197 | @Override 198 | public void onItemSelected(AdapterView adapterView, View view, int i, long l) { 199 | mSelectedFormat = FORMAT_OPTIONS[i]; 200 | mContext.getSharedPreferences(PREF_COMMON, 0).edit().putInt(PREF_KEY_FORMAT, i).commit(); 201 | } 202 | 203 | @Override 204 | public void onNothingSelected(AdapterView adapterView) { 205 | mSelectedFormat = FORMAT_OPTIONS[0]; 206 | mContext.getSharedPreferences(PREF_COMMON, 0).edit().putInt(PREF_KEY_FORMAT, 0).commit(); 207 | } 208 | }); 209 | formatSpinner.setSelection(mContext.getSharedPreferences(PREF_COMMON, 0).getInt(PREF_KEY_FORMAT, 0)); 210 | 211 | Spinner resolutionSpinner = (Spinner) findViewById(R.id.resolution_spinner); 212 | ArrayAdapter resolutionAdapter = ArrayAdapter.createFromResource(this, 213 | R.array.resolution_options, android.R.layout.simple_spinner_item); 214 | resolutionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 215 | resolutionSpinner.setAdapter(resolutionAdapter); 216 | resolutionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 217 | @Override 218 | public void onItemSelected(AdapterView adapterView, View view, int i, long l) { 219 | mSelectedWidth = RESOLUTION_OPTIONS[i][0]; 220 | mSelectedHeight = RESOLUTION_OPTIONS[i][1]; 221 | mSelectedDpi = RESOLUTION_OPTIONS[i][2]; 222 | mContext.getSharedPreferences(PREF_COMMON, 0).edit().putInt(PREF_KEY_RESOLUTION, i).commit(); 223 | } 224 | 225 | @Override 226 | public void onNothingSelected(AdapterView adapterView) { 227 | mSelectedWidth = RESOLUTION_OPTIONS[0][0]; 228 | mSelectedHeight = RESOLUTION_OPTIONS[0][1]; 229 | mSelectedDpi = RESOLUTION_OPTIONS[0][2]; 230 | mContext.getSharedPreferences(PREF_COMMON, 0).edit().putInt(PREF_KEY_RESOLUTION, 0).commit(); 231 | } 232 | }); 233 | resolutionSpinner.setSelection(mContext.getSharedPreferences(PREF_COMMON, 0).getInt(PREF_KEY_RESOLUTION, 0)); 234 | 235 | Spinner bitrateSpinner = (Spinner) findViewById(R.id.bitrate_spinner); 236 | ArrayAdapter bitrateAdapter = ArrayAdapter.createFromResource(this, 237 | R.array.bitrate_options, android.R.layout.simple_spinner_item); 238 | bitrateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 239 | bitrateSpinner.setAdapter(bitrateAdapter); 240 | bitrateSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 241 | @Override 242 | public void onItemSelected(AdapterView adapterView, View view, int i, long l) { 243 | mSelectedBitrate = BITRATE_OPTIONS[i]; 244 | mContext.getSharedPreferences(PREF_COMMON, 0).edit().putInt(PREF_KEY_BITRATE, i).commit(); 245 | } 246 | 247 | @Override 248 | public void onNothingSelected(AdapterView adapterView) { 249 | mSelectedBitrate = BITRATE_OPTIONS[0]; 250 | mContext.getSharedPreferences(PREF_COMMON, 0).edit().putInt(PREF_KEY_BITRATE, 0).commit(); 251 | } 252 | }); 253 | bitrateSpinner.setSelection(mContext.getSharedPreferences(PREF_COMMON, 0).getInt(PREF_KEY_BITRATE, 0)); 254 | 255 | mReceiverIp = mContext.getSharedPreferences(PREF_COMMON, 0).getString(PREF_KEY_RECEIVER, ""); 256 | updateReceiverStatus(); 257 | startService(); 258 | } 259 | 260 | @Override 261 | public void onResume() { 262 | super.onResume(); 263 | 264 | // start discovery task 265 | mDiscoveryTask = new DiscoveryTask(); 266 | mDiscoveryTask.execute(); 267 | } 268 | 269 | @Override 270 | public void onPause() { 271 | super.onPause(); 272 | mDiscoveryTask.cancel(true); 273 | } 274 | @Override 275 | protected void onDestroy() { 276 | super.onDestroy(); 277 | doUnbindService(); 278 | } 279 | 280 | @Override 281 | public boolean onCreateOptionsMenu(Menu menu) { 282 | // Inflate the menu; this adds items to the action bar if it is present. 283 | getMenuInflater().inflate(R.menu.menu_main, menu); 284 | //if (mInputSurface != null) { 285 | // menu.findItem(R.id.action_start).setVisible(false); 286 | // menu.findItem(R.id.action_stop).setVisible(true); 287 | //} else { 288 | // menu.findItem(R.id.action_start).setVisible(true); 289 | // menu.findItem(R.id.action_stop).setVisible(false); 290 | //} 291 | return true; 292 | } 293 | 294 | @Override 295 | public boolean onOptionsItemSelected(MenuItem item) { 296 | // Handle action bar item clicks here. The action bar will 297 | // automatically handle clicks on the Home/Up button, so long 298 | // as you specify a parent activity in AndroidManifest.xml. 299 | int id = item.getItemId(); 300 | 301 | //noinspection SimplifiableIfStatement 302 | if (id == R.id.action_start) { 303 | Log.d(TAG, "==== start ===="); 304 | if (mReceiverIp != null) { 305 | startCaptureScreen(); 306 | //invalidateOptionsMenu(); 307 | } else { 308 | Toast.makeText(mContext, R.string.no_receiver, Toast.LENGTH_SHORT).show(); 309 | } 310 | return true; 311 | } else if (id == R.id.action_stop) { 312 | Log.d(TAG, "==== stop ===="); 313 | stopScreenCapture(); 314 | //invalidateOptionsMenu(); 315 | return true; 316 | } 317 | 318 | return super.onOptionsItemSelected(item); 319 | } 320 | 321 | @Override 322 | public void onActivityResult(int requestCode, int resultCode, Intent data) { 323 | if (requestCode == REQUEST_MEDIA_PROJECTION) { 324 | if (resultCode != Activity.RESULT_OK) { 325 | Log.d(TAG, "User cancelled"); 326 | Toast.makeText(mContext, R.string.user_cancelled, Toast.LENGTH_SHORT).show(); 327 | return; 328 | } 329 | Log.d(TAG, "Starting screen capture"); 330 | mResultCode = resultCode; 331 | mResultData = data; 332 | startCaptureScreen(); 333 | } 334 | } 335 | 336 | @Override 337 | public void onSaveInstanceState(Bundle outState) { 338 | super.onSaveInstanceState(outState); 339 | if (mResultData != null) { 340 | outState.putInt(STATE_RESULT_CODE, mResultCode); 341 | outState.putParcelable(STATE_RESULT_DATA, mResultData); 342 | } 343 | } 344 | 345 | private void updateReceiverStatus() { 346 | if (mReceiverIp.length() > 0) { 347 | mReceiverTextView.setText(String.format(mContext.getString(R.string.receiver), mReceiverIp)); 348 | } else { 349 | mReceiverTextView.setText(R.string.no_receiver); 350 | } 351 | } 352 | 353 | private void startCaptureScreen() { 354 | if (mResultCode != 0 && mResultData != null) { 355 | startService(); 356 | } else { 357 | Log.d(TAG, "Requesting confirmation"); 358 | // This initiates a prompt dialog for the user to confirm screen projection. 359 | startActivityForResult( 360 | mMediaProjectionManager.createScreenCaptureIntent(), 361 | REQUEST_MEDIA_PROJECTION); 362 | } 363 | } 364 | 365 | private void stopScreenCapture() { 366 | if (mServiceMessenger == null) { 367 | return; 368 | } 369 | final Intent stopCastIntent = new Intent(Common.ACTION_STOP_CAST); 370 | sendBroadcast(stopCastIntent); 371 | /* 372 | try { 373 | Message msg = Message.obtain(null, Common.MSG_STOP_CAST); 374 | mServiceMessenger.send(msg); 375 | } catch (RemoteException e) { 376 | Log.e(TAG, "Failed to send stop message to service"); 377 | e.printStackTrace(); 378 | }*/ 379 | } 380 | 381 | private void startService() { 382 | if (mResultCode != 0 && mResultData != null && mReceiverIp != null) { 383 | Intent intent = new Intent(this, CastService.class); 384 | intent.putExtra(Common.EXTRA_RESULT_CODE, mResultCode); 385 | intent.putExtra(Common.EXTRA_RESULT_DATA, mResultData); 386 | intent.putExtra(Common.EXTRA_RECEIVER_IP, mReceiverIp); 387 | intent.putExtra(Common.EXTRA_VIDEO_FORMAT, mSelectedFormat); 388 | intent.putExtra(Common.EXTRA_SCREEN_WIDTH, mSelectedWidth); 389 | intent.putExtra(Common.EXTRA_SCREEN_HEIGHT, mSelectedHeight); 390 | intent.putExtra(Common.EXTRA_SCREEN_DPI, mSelectedDpi); 391 | intent.putExtra(Common.EXTRA_VIDEO_BITRATE, mSelectedBitrate); 392 | Log.d(TAG, "===== start service ====="); 393 | startService(intent); 394 | bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE); 395 | } else { 396 | Intent intent = new Intent(this, CastService.class); 397 | startService(intent); 398 | bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE); 399 | } 400 | } 401 | 402 | private void doUnbindService() { 403 | if (mServiceMessenger != null) { 404 | try { 405 | Message msg = Message.obtain(null, Common.MSG_UNREGISTER_CLIENT); 406 | msg.replyTo = mMessenger; 407 | mServiceMessenger.send(msg); 408 | } catch (RemoteException e) { 409 | Log.d(TAG, "Failed to send unregister message to service, e: " + e.toString()); 410 | e.printStackTrace(); 411 | } 412 | unbindService(mServiceConnection); 413 | } 414 | } 415 | 416 | private class DiscoveryTask extends AsyncTask { 417 | @Override 418 | protected Void doInBackground(Void... voids) { 419 | try { 420 | DatagramSocket discoverUdpSocket = new DatagramSocket(); 421 | Log.d(TAG, "Bind local port: " + discoverUdpSocket.getLocalPort()); 422 | discoverUdpSocket.setSoTimeout(3000); 423 | byte[] buf = new byte[1024]; 424 | while (true) { 425 | if (!Utils.sendBroadcastMessage(mContext, discoverUdpSocket, Common.DISCOVER_PORT, Common.DISCOVER_MESSAGE)) { 426 | Log.w(TAG, "Failed to send discovery message"); 427 | } 428 | Arrays.fill(buf, (byte)0); 429 | DatagramPacket receivePacket = new DatagramPacket(buf, buf.length); 430 | try { 431 | discoverUdpSocket.receive(receivePacket); 432 | String ip = receivePacket.getAddress().getHostAddress(); 433 | Log.d(TAG, "Receive discover response from " + ip + ", length: " + receivePacket.getLength()); 434 | if (receivePacket.getLength() > 9) { 435 | String respMsg = new String(receivePacket.getData()); 436 | Log.d(TAG, "Discover response message: " + respMsg); 437 | try { 438 | JSONObject json = new JSONObject(respMsg); 439 | String name = json.getString("name"); 440 | //String id = json.getString("id"); 441 | String width = json.getString("width"); 442 | String height = json.getString("height"); 443 | mDiscoverdMap.put(name, ip); 444 | mHandler.post(new Runnable() { 445 | @Override 446 | public void run() { 447 | mDiscoverAdapter.clear(); 448 | mDiscoverAdapter.addAll(mDiscoverdMap.keySet()); 449 | } 450 | }); 451 | Log.d(TAG, "Got receiver name: " + name + ", ip: " + ip + ", width: " + width + ", height: " + height); 452 | } catch (JSONException e) { 453 | e.printStackTrace(); 454 | } 455 | } 456 | } catch (SocketTimeoutException e) { 457 | } 458 | 459 | Thread.sleep(3000); 460 | } 461 | } catch (SocketException e) { 462 | Log.d(TAG, "Failed to create socket for discovery"); 463 | e.printStackTrace(); 464 | } catch (IOException e) { 465 | e.printStackTrace(); 466 | } catch (InterruptedException e) { 467 | e.printStackTrace(); 468 | } 469 | return null; 470 | } 471 | } 472 | } 473 | -------------------------------------------------------------------------------- /app/src/main/java/com/yschi/castscreen/Utils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Jones Chi 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yschi.castscreen; 18 | 19 | import android.content.Context; 20 | import android.net.DhcpInfo; 21 | import android.net.wifi.WifiManager; 22 | 23 | import java.io.IOException; 24 | import java.net.DatagramPacket; 25 | import java.net.DatagramSocket; 26 | import java.net.InetAddress; 27 | 28 | /** 29 | * Created by yschi on 2015/5/27. 30 | */ 31 | public class Utils { 32 | static public InetAddress getBroadcastAddress(Context context) throws IOException { 33 | WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 34 | DhcpInfo dhcp = wifi.getDhcpInfo(); 35 | if (dhcp == null) { 36 | return null; 37 | } 38 | 39 | int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask; 40 | byte[] quads = new byte[4]; 41 | for (int k = 0; k < 4; k++) { 42 | quads[k] = (byte) ((broadcast >> k * 8) & 0xFF); 43 | } 44 | return InetAddress.getByAddress(quads); 45 | } 46 | 47 | static public boolean sendBroadcastMessage(Context context, DatagramSocket socket, int port, String message) { 48 | 49 | try { 50 | InetAddress broadcastAddr = getBroadcastAddress(context); 51 | if (broadcastAddr == null) { 52 | return false; 53 | } 54 | socket.setBroadcast(true); 55 | DatagramPacket packet = new DatagramPacket(message.getBytes(), message.length(), 56 | broadcastAddr, port); 57 | socket.send(packet); 58 | return true; 59 | } catch (IOException e) { 60 | e.printStackTrace(); 61 | } 62 | return false; 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 8 | 9 | 13 | 14 | 18 | 19 | 23 | 24 | 29 | 35 |