├── .github └── FUNDING.yml ├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── alexvas │ │ └── rtsp │ │ └── demo │ │ ├── MainActivity.kt │ │ └── live │ │ ├── LiveFragment.kt │ │ ├── LiveViewModel.kt │ │ └── RawFragment.kt │ └── res │ ├── drawable │ ├── ic_camera_black_24dp.xml │ ├── ic_cctv_black_24dp.xml │ ├── ic_launcher_background.xml │ ├── ic_launcher_foreground.xml │ └── ic_text_subject_black_24dp.xml │ ├── layout │ ├── activity_main.xml │ ├── fragment_live.xml │ ├── fragment_logs.xml │ ├── fragment_raw.xml │ └── layout_rtsp_params.xml │ ├── menu │ └── bottom_nav_menu.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.xml │ ├── navigation │ └── mobile_navigation.xml │ └── values │ ├── colors.xml │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── docs └── images │ └── rtsp-demo-app.webp ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── jitpack.yml ├── library-client-rtsp ├── .gitignore ├── build.gradle ├── proguard-rules.txt └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── com │ ├── alexvas │ ├── rtsp │ │ ├── RtspClient.java │ │ ├── codec │ │ │ ├── AudioDecodeThread.kt │ │ │ ├── FrameQueue.kt │ │ │ ├── VideoDecodeThread.kt │ │ │ ├── VideoDecoderBitmapThread.kt │ │ │ ├── VideoDecoderSurfaceThread.kt │ │ │ └── color │ │ │ │ ├── ColorConverter.kt │ │ │ │ └── ColorConverterImage.kt │ │ ├── parser │ │ │ ├── AacParser.java │ │ │ ├── RtpH264Parser.kt │ │ │ ├── RtpH265Parser.kt │ │ │ ├── RtpHeaderParser.java │ │ │ └── RtpParser.kt │ │ └── widget │ │ │ ├── RtspImageView.kt │ │ │ ├── RtspListeners.kt │ │ │ ├── RtspProcessor.kt │ │ │ └── RtspSurfaceView.kt │ └── utils │ │ ├── ByteUtils.java │ │ ├── MediaCodecUtils.kt │ │ ├── NetUtils.java │ │ └── VideoCodecUtils.kt │ └── limelight │ └── binding │ └── video │ └── MediaCodecHelper.java └── settings.gradle /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: alexeyvasilyev -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | /build 6 | .DS_Store 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rtsp-client-android 2 | Lightweight RTSP client library for Android with almost zero lag video decoding (achieved 20 msec video decoding latency on some RTSP streams). Designed for lag criticial applications (e.g. video surveillance from drones, car rear view cameras, etc.). 3 | 4 | Unlike [AndroidX Media ExoPlayer](https://github.com/androidx/media) which also supports RTSP, this library does not make any video buffering. Video frames are shown immidiately when they arrive. 5 | 6 | [![Release](https://jitpack.io/v/alexeyvasilyev/rtsp-client-android.svg)](https://jitpack.io/#alexeyvasilyev/rtsp-client-android) 7 | 8 | ![Screenshot](docs/images/rtsp-demo-app.webp?raw=true "Screenshot") 9 | 10 | ## Features: 11 | - RTSP/RTSPS over TCP. 12 | - Supports majority of RTSP IP cameras. 13 | - Video H.264/H.265. 14 | - Audio AAC LC only. 15 | - Support for application specific data sent via RTP, e.g. GPS data (`m=application`, see [RFC 4566 sec.5.14](https://datatracker.ietf.org/doc/html/rfc4566#section-5.14)) 16 | - Basic/Digest authentication. 17 | - Uses Android's [Low-Latency MediaCodec](https://source.android.com/docs/core/media/low-latency-media) by default if available. 18 | - Ability to select hardware or software video decoder. 19 | - Ability to [rewrite SPS frame](https://github.com/alexeyvasilyev/rtsp-client-android/blob/dbea741548307b1b0e1ead0ccc6294e811fbf6fd/library-client-rtsp/src/main/java/com/alexvas/rtsp/widget/RtspProcessor.kt#L106C9-L106C55) with low-latency parameters (EXPERIMENTAL). 20 | - Video rotation (90, 180, 270 degrees). 21 | - Android min API 24. 22 | 23 | ## Upcoming features: 24 | - PCM and G.711 aLaw/uLaw audio streams. 25 | - 2-w talk. 26 | 27 | ## Permissions: 28 | 29 | ```xml 30 | 31 | ``` 32 | 33 | ## Compile 34 | 35 | To use this library in your project add this to your build.gradle: 36 | ```gradle 37 | allprojects { 38 | repositories { 39 | maven { url 'https://jitpack.io' } 40 | } 41 | } 42 | dependencies { 43 | implementation 'com.github.alexeyvasilyev:rtsp-client-android:x.x.x' 44 | } 45 | ``` 46 | 47 | ## How to use: 48 | Easiest way is just to use `RtspSurfaceView` (recommended) or `RtspImageView` classes for showing video stream in UI. 49 | 50 | Use [RtspSurfaceView](https://github.com/alexeyvasilyev/rtsp-client-android/blob/master/library-client-rtsp/src/main/java/com/alexvas/rtsp/widget/RtspSurfaceView.kt) if you need best performance and less battery usage. To get bitmap from SurfaceView use [PixelCopy.request](https://developer.android.com/reference/android/view/PixelCopy) (on Pixel 8 Pro with 1440p @ 20 fps video stream, you can get 12 fps only via PixelCopy) 51 | 52 | Use [RtspImageView](https://github.com/alexeyvasilyev/rtsp-client-android/blob/master/library-client-rtsp/src/main/java/com/alexvas/rtsp/widget/RtspImageView.kt) if you need better performance than PixelCopy for getting bitmaps for further processing (e.g. for AI). 53 | 54 | ```xml 55 | 59 | 60 | 64 | ``` 65 | 66 | Then in code use: 67 | ```kotlin 68 | val uri = Uri.parse("rtsps://10.0.1.3/test.sdp") 69 | val username = "admin" 70 | val password = "secret" 71 | svVideo.init(uri, username, password) 72 | svVideo.start( 73 | requestVideo = true, 74 | requestAudio = true, 75 | requestApplication = false) 76 | // ... 77 | svVideo.stop() 78 | ``` 79 | 80 | You can still use library without any decoding (just for obtaining raw frames from RTSP source), e.g. for writing video stream into MP4 via muxer. 81 | 82 | ```kotlin 83 | val rtspClientListener = object: RtspClient.RtspClientListener { 84 | override fun onRtspConnecting() {} 85 | override fun onRtspConnected(sdpInfo: SdpInfo) {} 86 | override fun onRtspVideoNalUnitReceived(data: ByteArray, offset: Int, length: Int, timestamp: Long) { 87 | // Send raw H264/H265 NAL unit to decoder 88 | } 89 | override fun onRtspAudioSampleReceived(data: ByteArray, offset: Int, length: Int, timestamp: Long) { 90 | // Send raw audio to decoder 91 | } 92 | override fun onRtspApplicationDataReceived(data: ByteArray, offset: Int, length: Int, timestamp: Long) { 93 | // Send raw application data to app specific parser 94 | } 95 | override fun onRtspDisconnected() {} 96 | override fun onRtspFailedUnauthorized() { 97 | Log.e(TAG, "RTSP failed unauthorized"); 98 | } 99 | override fun onRtspFailed(message: String?) { 100 | Log.e(TAG, "RTSP failed with message '$message'") 101 | } 102 | } 103 | 104 | val uri = Uri.parse("rtsps://10.0.1.3/test.sdp") 105 | val username = "admin" 106 | val password = "secret" 107 | val stopped = new AtomicBoolean(false) 108 | val sslSocket = NetUtils.createSslSocketAndConnect(uri.getHost(), uri.getPort(), 5000) 109 | 110 | val rtspClient = RtspClient.Builder(sslSocket, uri.toString(), stopped, rtspClientListener) 111 | .requestVideo(true) 112 | .requestAudio(true) 113 | .withDebug(false) 114 | .withUserAgent("RTSP client") 115 | .withCredentials(username, password) 116 | .build() 117 | // Blocking call until stopped variable is true or connection failed 118 | rtspClient.execute() 119 | 120 | NetUtils.closeSocket(sslSocket) 121 | ``` 122 | 123 | ## How to get lowest possible latency: 124 | There are two types of latencies: 125 | 126 | ### Network latency 127 | If you want the lowest possible network latency, be sure that both Android device and RTSP camera are connected to the same network by the Ethernet cable (not WiFi). 128 | 129 | Another option to try is to decrease stream bitrate on RTSP camera. Less frame size leads to less time needed for frame transfer. 130 | 131 | ### Video decoder latency 132 | Video decoder latency can vary significantly on different Android devices and on different RTSP camera streams. 133 | 134 | For the same profile/level and resolution (but different cameras) the latency in best cases can can be 20 msec, in worst cases 1200 msec. 135 | 136 | To decrease latency be sure you use the lowest possible H.264 video stream profile and level (enable `debug` in the library and check SPS frame params `profile_idc` and `level_idc` in the log). `Baseline profile` should have the lowest possible decoder latency. 137 | Check `max_num_reorder_frames` param as well. For best latency it's value should be `0`. 138 | 139 | You can also try to use [experimentalUpdateSpsFrameWithLowLatencyParams](https://github.com/alexeyvasilyev/rtsp-client-android/blob/master/library-client-rtsp/src/main/java/com/alexvas/rtsp/widget/RtspProcessor.kt#L106) library feature which rewrites config frame on runtime with low-latency parameters. 140 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/android,java,intellij 2 | 3 | ### Android ### 4 | # Built application files 5 | *.apk 6 | *.ap_ 7 | 8 | # Files for the Dalvik VM 9 | *.dex 10 | 11 | # Java class files 12 | *.class 13 | 14 | # Generated files 15 | bin/ 16 | gen/ 17 | 18 | # Gradle files 19 | .gradle/ 20 | build/ 21 | 22 | # Local configuration file (sdk path, etc) 23 | local.properties 24 | 25 | # Proguard folder generated by Eclipse 26 | proguard/ 27 | 28 | xactmobile/class_files.txt 29 | xactmobile/mapping.txt 30 | xactmobile/seeds.txt 31 | 32 | # Log Files 33 | *.log 34 | 35 | # Android Studio Navigation editor temp files 36 | .navigation/ 37 | 38 | ### Android Patch ### 39 | gen-external-apklibs 40 | 41 | 42 | ### Java ### 43 | *.class 44 | 45 | # Mobile Tools for Java (J2ME) 46 | .mtj.tmp/ 47 | 48 | # Package Files # 49 | #*.jar 50 | *.war 51 | *.ear 52 | 53 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 54 | hs_err_pid* 55 | 56 | 57 | ### Intellij ### 58 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio 59 | 60 | *.iml 61 | 62 | ## Directory-based project format: 63 | .idea/ 64 | # if you remove the above rule, at least ignore the following: 65 | 66 | # User-specific stuff: 67 | .idea/workspace.xml 68 | .idea/tasks.xml 69 | .idea/dictionaries 70 | 71 | # Sensitive or high-churn files: 72 | .idea/dataSources.ids 73 | .idea/dataSources.xml 74 | .idea/sqlDataSources.xml 75 | .idea/dynamic.xml 76 | .idea/uiDesigner.xml 77 | 78 | # Gradle: 79 | .idea/gradle.xml 80 | .idea/libraries 81 | 82 | # Mongo Explorer plugin: 83 | .idea/mongoSettings.xml 84 | 85 | ## File-based project format: 86 | *.ipr 87 | *.iws 88 | 89 | ## Plugin-specific files: 90 | 91 | # IntelliJ 92 | /out/ 93 | 94 | # mpeltonen/sbt-idea plugin 95 | .idea_modules/ 96 | 97 | # JIRA plugin 98 | atlassian-ide-plugin.xml 99 | 100 | # Crashlytics plugin (for Android Studio and IntelliJ) 101 | com_crashlytics_export_strings.xml 102 | crashlytics.properties 103 | crashlytics-build.properties 104 | 105 | xactmobile/.DS_Store~64be78fe3602626c61b52bcbfd09e09a6107b50a 106 | xactmobile/.DS_Store~HEAD 107 | oslab-viewpager/._.DS_Store 108 | oslab-viewpager/src/main/.DS_Store 109 | oslab-viewpager/src/main/._.DS_Store 110 | oslab-viewpager/src/main/res/.DS_Store 111 | oslab-viewpager/src/main/res/._.DS_Store 112 | oslab-viewpager/.gitignore 113 | oslab-materialdesign/.DS_Store 114 | oslab-materialdesign/._.DS_Store 115 | oslab-materialdesign/src/.DS_Store 116 | oslab-materialdesign/src/._.DS_Store 117 | oslab-materialdesign/src/main/.DS_Store 118 | oslab-materialdesign/src/main/._.DS_Store 119 | oslab-materialdesign/src/main/res/.DS_Store 120 | oslab-materialdesign/src/main/res/._.DS_Store 121 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | 4 | android { 5 | 6 | compileSdk 35 7 | 8 | defaultConfig { 9 | applicationId "com.alexvas.rtsp.demo" 10 | minSdk 24 11 | targetSdk 34 12 | versionCode 1 13 | versionName "1.0" 14 | } 15 | 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | 23 | // To inline the bytecode built with JVM target 1.8 into 24 | // bytecode that is being built with JVM target 1.6. (e.g. navArgs) 25 | 26 | 27 | compileOptions { 28 | sourceCompatibility JavaVersion.VERSION_17 29 | targetCompatibility JavaVersion.VERSION_17 30 | } 31 | kotlinOptions { 32 | jvmTarget = JavaVersion.VERSION_17.toString() 33 | } 34 | buildFeatures { 35 | viewBinding true 36 | } 37 | namespace 'com.alexvas.rtsp.demo' 38 | } 39 | 40 | dependencies { 41 | implementation fileTree(dir: 'libs', include: ['*.jar']) 42 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 43 | implementation 'androidx.appcompat:appcompat:1.7.0' 44 | implementation 'androidx.core:core-ktx:1.15.0' 45 | implementation 'com.google.android.material:material:1.12.0' 46 | implementation 'androidx.constraintlayout:constraintlayout:2.2.0' 47 | implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' 48 | 49 | def androidx_navigation_version = '2.8.5' 50 | implementation "androidx.navigation:navigation-fragment-ktx:$androidx_navigation_version" 51 | implementation "androidx.navigation:navigation-ui-ktx:$androidx_navigation_version" 52 | implementation "androidx.navigation:navigation-fragment-ktx:$androidx_navigation_version" 53 | implementation "androidx.navigation:navigation-ui-ktx:$androidx_navigation_version" 54 | 55 | def logcat_core_version = '3.3.1' 56 | api "com.github.AppDevNext.Logcat:LogcatCoreLib:$logcat_core_version" 57 | api "com.github.AppDevNext.Logcat:LogcatCoreUI:$logcat_core_version" 58 | 59 | implementation project(':library-client-rtsp') 60 | } 61 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /app/src/main/java/com/alexvas/rtsp/demo/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.alexvas.rtsp.demo 2 | 3 | import android.os.Bundle 4 | import com.google.android.material.bottomnavigation.BottomNavigationView 5 | import androidx.appcompat.app.AppCompatActivity 6 | import androidx.navigation.findNavController 7 | import androidx.navigation.ui.setupWithNavController 8 | 9 | class MainActivity : AppCompatActivity() { 10 | 11 | override fun onCreate(savedInstanceState: Bundle?) { 12 | super.onCreate(savedInstanceState) 13 | setContentView(R.layout.activity_main) 14 | val navView: BottomNavigationView = findViewById(R.id.nav_view) 15 | 16 | val navController = findNavController(R.id.nav_host_fragment) 17 | // Passing each menu ID as a set of Ids because each 18 | // menu should be considered as top level destinations. 19 | // val appBarConfiguration = AppBarConfiguration(setOf( 20 | // R.id.navigation_live, R.id.navigation_logs)) 21 | // setupActionBarWithNavController(navController, appBarConfiguration) 22 | navView.setupWithNavController(navController) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /app/src/main/java/com/alexvas/rtsp/demo/live/LiveFragment.kt: -------------------------------------------------------------------------------- 1 | package com.alexvas.rtsp.demo.live 2 | 3 | import android.annotation.SuppressLint 4 | import android.graphics.Bitmap 5 | import android.net.Uri 6 | import android.os.Bundle 7 | import android.os.Handler 8 | import android.os.HandlerThread 9 | import android.util.Log 10 | import android.view.* 11 | import android.widget.Toast 12 | import androidx.constraintlayout.widget.ConstraintSet 13 | import androidx.fragment.app.Fragment 14 | import androidx.lifecycle.ViewModelProvider 15 | import com.alexvas.rtsp.codec.VideoDecodeThread 16 | import com.alexvas.rtsp.demo.databinding.FragmentLiveBinding 17 | import com.alexvas.rtsp.widget.RtspDataListener 18 | import com.alexvas.rtsp.widget.RtspImageView 19 | import com.alexvas.rtsp.widget.RtspStatusListener 20 | import com.alexvas.rtsp.widget.toHexString 21 | import java.util.Timer 22 | import java.util.TimerTask 23 | import java.util.concurrent.atomic.AtomicBoolean 24 | import kotlin.math.min 25 | 26 | @SuppressLint("LogNotTimber") 27 | class LiveFragment : Fragment() { 28 | 29 | private lateinit var binding: FragmentLiveBinding 30 | private lateinit var liveViewModel: LiveViewModel 31 | 32 | private var statisticsTimer: Timer? = null 33 | private var svVideoSurfaceResolution = Pair(0, 0) 34 | 35 | private val rtspStatusSurfaceListener = object: RtspStatusListener { 36 | override fun onRtspStatusConnecting() { 37 | if (DEBUG) Log.v(TAG, "onRtspStatusConnecting()") 38 | binding.apply { 39 | tvStatusSurface.text = "RTSP connecting" 40 | pbLoadingSurface.visibility = View.VISIBLE 41 | vShutterSurface.visibility = View.VISIBLE 42 | llRtspParams.apply { 43 | etRtspRequest.isEnabled = false 44 | etRtspUsername.isEnabled = false 45 | etRtspPassword.isEnabled = false 46 | cbVideo.isEnabled = false 47 | cbAudio.isEnabled = false 48 | cbApplication.isEnabled = false 49 | cbDebug.isEnabled = false 50 | } 51 | tgRotation.isEnabled = false 52 | } 53 | } 54 | 55 | override fun onRtspStatusConnected() { 56 | if (DEBUG) Log.v(TAG, "onRtspStatusConnected()") 57 | binding.apply { 58 | tvStatusSurface.text = "RTSP connected" 59 | bnStartStopSurface.text = "Stop RTSP" 60 | } 61 | setKeepScreenOn(true) 62 | } 63 | 64 | override fun onRtspStatusDisconnecting() { 65 | if (DEBUG) Log.v(TAG, "onRtspStatusDisconnecting()") 66 | binding.apply { 67 | tvStatusSurface.text = "RTSP disconnecting" 68 | } 69 | } 70 | 71 | override fun onRtspStatusDisconnected() { 72 | if (DEBUG) Log.v(TAG, "onRtspStatusDisconnected()") 73 | binding.apply { 74 | tvStatusSurface.text = "RTSP disconnected" 75 | bnStartStopSurface.text = "Start RTSP" 76 | pbLoadingSurface.visibility = View.GONE 77 | vShutterSurface.visibility = View.VISIBLE 78 | pbLoadingSurface.isEnabled = false 79 | llRtspParams.apply { 80 | cbVideo.isEnabled = true 81 | cbAudio.isEnabled = true 82 | cbApplication.isEnabled = true 83 | cbDebug.isEnabled = true 84 | etRtspRequest.isEnabled = true 85 | etRtspUsername.isEnabled = true 86 | etRtspPassword.isEnabled = true 87 | } 88 | tgRotation.isEnabled = true 89 | } 90 | setKeepScreenOn(false) 91 | } 92 | 93 | override fun onRtspStatusFailedUnauthorized() { 94 | if (DEBUG) Log.e(TAG, "onRtspStatusFailedUnauthorized()") 95 | if (context == null) return 96 | onRtspStatusDisconnected() 97 | binding.apply { 98 | tvStatusSurface.text = "RTSP username or password invalid" 99 | pbLoadingSurface.visibility = View.GONE 100 | } 101 | } 102 | 103 | override fun onRtspStatusFailed(message: String?) { 104 | if (DEBUG) Log.e(TAG, "onRtspStatusFailed(message='$message')") 105 | if (context == null) return 106 | onRtspStatusDisconnected() 107 | binding.apply { 108 | tvStatusSurface.text = "Error: $message" 109 | pbLoadingSurface.visibility = View.GONE 110 | } 111 | } 112 | 113 | override fun onRtspFirstFrameRendered() { 114 | if (DEBUG) Log.v(TAG, "onRtspFirstFrameRendered()") 115 | Log.i(TAG, "First frame rendered") 116 | binding.apply { 117 | pbLoadingSurface.visibility = View.GONE 118 | vShutterSurface.visibility = View.GONE 119 | bnSnapshotSurface.isEnabled = true 120 | } 121 | } 122 | 123 | override fun onRtspFrameSizeChanged(width: Int, height: Int) { 124 | if (DEBUG) Log.v(TAG, "onRtspFrameSizeChanged(width=$width, height=$height)") 125 | Log.i(TAG, "Video resolution changed to ${width}x${height}") 126 | svVideoSurfaceResolution = Pair(width, height) 127 | ConstraintSet().apply { 128 | clone(binding.csVideoSurface) 129 | setDimensionRatio(binding.svVideoSurface.id, "$width:$height") 130 | applyTo(binding.csVideoSurface) 131 | } 132 | } 133 | } 134 | 135 | private val rtspDataListener = object: RtspDataListener { 136 | override fun onRtspDataApplicationDataReceived(data: ByteArray, offset: Int, length: Int, timestamp: Long) { 137 | val numBytesDump = min(length, 25) // dump max 25 bytes 138 | Log.i(TAG, "RTSP app data ($length bytes): ${data.toHexString(offset, offset + numBytesDump)}") 139 | } 140 | } 141 | 142 | private val rtspStatusImageListener = object: RtspStatusListener { 143 | override fun onRtspStatusConnecting() { 144 | if (DEBUG) Log.v(TAG, "onRtspStatusConnecting()") 145 | binding.apply { 146 | tvStatusImage.text = "RTSP connecting" 147 | pbLoadingImage.visibility = View.VISIBLE 148 | vShutterImage.visibility = View.VISIBLE 149 | } 150 | } 151 | 152 | override fun onRtspStatusConnected() { 153 | if (DEBUG) Log.v(TAG, "onRtspStatusConnected()") 154 | binding.apply { 155 | tvStatusImage.text = "RTSP connected" 156 | bnStartStopImage.text = "Stop RTSP" 157 | } 158 | setKeepScreenOn(true) 159 | } 160 | 161 | override fun onRtspStatusDisconnecting() { 162 | if (DEBUG) Log.v(TAG, "onRtspStatusDisconnecting()") 163 | binding.apply { 164 | tvStatusImage.text = "RTSP disconnecting" 165 | } 166 | } 167 | 168 | override fun onRtspStatusDisconnected() { 169 | if (DEBUG) Log.v(TAG, "onRtspStatusDisconnected()") 170 | binding.apply { 171 | tvStatusImage.text = "RTSP disconnected" 172 | bnStartStopImage.text = "Start RTSP" 173 | pbLoadingImage.visibility = View.GONE 174 | vShutterImage.visibility = View.VISIBLE 175 | pbLoadingImage.isEnabled = false 176 | } 177 | setKeepScreenOn(false) 178 | } 179 | 180 | override fun onRtspStatusFailedUnauthorized() { 181 | if (DEBUG) Log.e(TAG, "onRtspStatusFailedUnauthorized()") 182 | if (context == null) return 183 | onRtspStatusDisconnected() 184 | binding.apply { 185 | tvStatusImage.text = "RTSP username or password invalid" 186 | pbLoadingImage.visibility = View.GONE 187 | } 188 | } 189 | 190 | override fun onRtspStatusFailed(message: String?) { 191 | if (DEBUG) Log.e(TAG, "onRtspStatusFailed(message='$message')") 192 | if (context == null) return 193 | onRtspStatusDisconnected() 194 | binding.apply { 195 | tvStatusImage.text = "Error: $message" 196 | pbLoadingImage.visibility = View.GONE 197 | } 198 | } 199 | 200 | override fun onRtspFirstFrameRendered() { 201 | if (DEBUG) Log.v(TAG, "onRtspFirstFrameRendered()") 202 | Log.i(TAG, "First frame rendered") 203 | binding.apply { 204 | vShutterImage.visibility = View.GONE 205 | pbLoadingImage.visibility = View.GONE 206 | } 207 | } 208 | 209 | override fun onRtspFrameSizeChanged(width: Int, height: Int) { 210 | if (DEBUG) Log.v(TAG, "onRtspFrameSizeChanged(width=$width, height=$height)") 211 | Log.i(TAG, "Video resolution changed to ${width}x${height}") 212 | ConstraintSet().apply { 213 | clone(binding.csVideoImage) 214 | setDimensionRatio(binding.ivVideoImage.id, "$width:$height") 215 | applyTo(binding.csVideoImage) 216 | } 217 | } 218 | } 219 | 220 | private fun getSnapshot(): Bitmap? { 221 | if (DEBUG) Log.v(TAG, "getSnapshot()") 222 | val surfaceBitmap = Bitmap.createBitmap(1920, 1080, Bitmap.Config.ARGB_8888) 223 | val lock = Object() 224 | val success = AtomicBoolean(false) 225 | val thread = HandlerThread("PixelCopyHelper") 226 | thread.start() 227 | val sHandler = Handler(thread.looper) 228 | val listener = PixelCopy.OnPixelCopyFinishedListener { copyResult -> 229 | success.set(copyResult == PixelCopy.SUCCESS) 230 | synchronized (lock) { 231 | lock.notify() 232 | } 233 | } 234 | synchronized (lock) { 235 | PixelCopy.request(binding.svVideoSurface.holder.surface, surfaceBitmap, listener, sHandler) 236 | lock.wait() 237 | } 238 | thread.quitSafely() 239 | return if (success.get()) surfaceBitmap else null 240 | } 241 | 242 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { 243 | if (DEBUG) Log.v(TAG, "onCreateView()") 244 | 245 | liveViewModel = ViewModelProvider(this)[LiveViewModel::class.java] 246 | binding = FragmentLiveBinding.inflate(inflater, container, false) 247 | 248 | binding.bnVideoDecoderGroup.check(binding.bnVideoDecoderHardware.id) 249 | 250 | binding.svVideoSurface.setStatusListener(rtspStatusSurfaceListener) 251 | binding.svVideoSurface.setDataListener(rtspDataListener) 252 | binding.ivVideoImage.setStatusListener(rtspStatusImageListener) 253 | binding.ivVideoImage.setDataListener(rtspDataListener) 254 | 255 | liveViewModel.initEditTexts( 256 | binding.llRtspParams.etRtspRequest, 257 | binding.llRtspParams.etRtspUsername, 258 | binding.llRtspParams.etRtspPassword 259 | ) 260 | 261 | liveViewModel.rtspRequest.observe(viewLifecycleOwner) { 262 | if (binding.llRtspParams.etRtspRequest.text.toString() != it) 263 | binding.llRtspParams.etRtspRequest.setText(it) 264 | } 265 | liveViewModel.rtspUsername.observe(viewLifecycleOwner) { 266 | if (binding.llRtspParams.etRtspUsername.text.toString() != it) 267 | binding.llRtspParams.etRtspUsername.setText(it) 268 | } 269 | liveViewModel.rtspPassword.observe(viewLifecycleOwner) { 270 | if (binding.llRtspParams.etRtspPassword.text.toString() != it) 271 | binding.llRtspParams.etRtspPassword.setText(it) 272 | } 273 | 274 | binding.cbExperimentalRewriteSps.setOnCheckedChangeListener { _, isChecked -> 275 | binding.svVideoSurface.experimentalUpdateSpsFrameWithLowLatencyParams = isChecked 276 | } 277 | 278 | binding.bnRotate0.setOnClickListener { 279 | binding.svVideoSurface.videoRotation = 0 280 | binding.ivVideoImage.videoRotation = 0 281 | } 282 | 283 | binding.bnRotate90.setOnClickListener { 284 | binding.svVideoSurface.videoRotation = 90 285 | binding.ivVideoImage.videoRotation = 90 286 | } 287 | 288 | binding.bnRotate180.setOnClickListener { 289 | binding.svVideoSurface.videoRotation = 180 290 | binding.ivVideoImage.videoRotation = 180 291 | } 292 | 293 | binding.bnRotate270.setOnClickListener { 294 | binding.svVideoSurface.videoRotation = 270 295 | binding.ivVideoImage.videoRotation = 270 296 | } 297 | 298 | binding.bnRotate0.performClick() 299 | 300 | binding.bnVideoDecoderHardware.setOnClickListener { 301 | binding.svVideoSurface.videoDecoderType = VideoDecodeThread.DecoderType.HARDWARE 302 | binding.ivVideoImage.videoDecoderType = VideoDecodeThread.DecoderType.HARDWARE 303 | } 304 | 305 | binding.bnVideoDecoderSoftware.setOnClickListener { 306 | binding.svVideoSurface.videoDecoderType = VideoDecodeThread.DecoderType.SOFTWARE 307 | binding.ivVideoImage.videoDecoderType = VideoDecodeThread.DecoderType.SOFTWARE 308 | } 309 | 310 | binding.bnStartStopSurface.setOnClickListener { 311 | if (binding.svVideoSurface.isStarted()) { 312 | binding.svVideoSurface.stop() 313 | stopStatistics() 314 | } else { 315 | val uri = Uri.parse(liveViewModel.rtspRequest.value) 316 | binding.svVideoSurface.apply { 317 | init( 318 | uri, 319 | username = liveViewModel.rtspUsername.value, 320 | password = liveViewModel.rtspPassword.value, 321 | userAgent = "rtsp-client-android") 322 | debug = binding.llRtspParams.cbDebug.isChecked 323 | start( 324 | requestVideo = binding.llRtspParams.cbVideo.isChecked, 325 | requestAudio = binding.llRtspParams.cbAudio.isChecked, 326 | requestApplication = binding.llRtspParams.cbApplication.isChecked 327 | ) 328 | } 329 | startStatistics() 330 | } 331 | } 332 | 333 | binding.bnStartStopImage.setOnClickListener { 334 | if (binding.ivVideoImage.isStarted()) { 335 | binding.ivVideoImage.stop() 336 | stopStatistics() 337 | } else { 338 | val uri = Uri.parse(liveViewModel.rtspRequest.value) 339 | binding.ivVideoImage.apply { 340 | init(uri, liveViewModel.rtspUsername.value, liveViewModel.rtspPassword.value, "rtsp-client-android") 341 | debug = binding.llRtspParams.cbDebug.isChecked 342 | onRtspImageBitmapListener = object : RtspImageView.RtspImageBitmapListener { 343 | override fun onRtspImageBitmapObtained(bitmap: Bitmap) { 344 | // TODO: You can send bitmap for processing 345 | } 346 | } 347 | start( 348 | requestVideo = binding.llRtspParams.cbVideo.isChecked, 349 | requestAudio = binding.llRtspParams.cbAudio.isChecked, 350 | requestApplication = binding.llRtspParams.cbApplication.isChecked 351 | ) 352 | } 353 | startStatistics() 354 | } 355 | } 356 | 357 | binding.bnSnapshotSurface.setOnClickListener { 358 | val bitmap = getSnapshot() 359 | // TODO Save snapshot to DCIM folder 360 | if (bitmap != null) { 361 | Toast.makeText(requireContext(), "Snapshot succeeded", Toast.LENGTH_LONG).show() 362 | } else { 363 | Toast.makeText(requireContext(), "Snapshot failed", Toast.LENGTH_LONG).show() 364 | } 365 | } 366 | return binding.root 367 | } 368 | 369 | override fun onResume() { 370 | if (DEBUG) Log.v(TAG, "onResume()") 371 | super.onResume() 372 | liveViewModel.loadParams(requireContext()) 373 | } 374 | 375 | override fun onPause() { 376 | val started = binding.svVideoSurface.isStarted() 377 | if (DEBUG) Log.v(TAG, "onPause(), started:$started") 378 | super.onPause() 379 | liveViewModel.saveParams(requireContext()) 380 | 381 | if (started) { 382 | binding.svVideoSurface.stop() 383 | stopStatistics() 384 | } 385 | } 386 | 387 | private fun startStatistics() { 388 | if (DEBUG) Log.v(TAG, "startStatistics()") 389 | Log.i(TAG, "Start statistics") 390 | if (statisticsTimer == null) { 391 | val task: TimerTask = object : TimerTask() { 392 | override fun run() { 393 | val statistics = binding.svVideoSurface.statistics 394 | val text = 395 | "Video decoder: ${statistics.videoDecoderType.toString().lowercase()} ${if (statistics.videoDecoderName.isNullOrEmpty()) "" else "(${statistics.videoDecoderName})"}" + 396 | "\nVideo decoder latency: ${statistics.videoDecoderLatencyMsec} ms" + 397 | "\nResolution: ${svVideoSurfaceResolution.first}x${svVideoSurfaceResolution.second}" 398 | // "\nNetwork latency: " 399 | 400 | // // Assume that difference between current Android time and camera time cannot be more than 5 sec. 401 | // // Otherwise time need to be synchronized on both devices. 402 | // text += if (statistics.networkLatencyMsec == -1) { 403 | // "-" 404 | // } else if (statistics.networkLatencyMsec < 0 || statistics.networkLatencyMsec > TimeUnit.SECONDS.toMillis(5)) { 405 | // "[time out of sync]" 406 | // } else { 407 | // "${statistics.networkLatencyMsec} ms" 408 | // } 409 | 410 | binding.tvStatistics.post { 411 | binding.tvStatistics.text = text 412 | } 413 | } 414 | } 415 | statisticsTimer = Timer("${TAG}::Statistics").apply { 416 | schedule(task, 0, 1000) 417 | } 418 | } 419 | } 420 | 421 | private fun stopStatistics() { 422 | if (DEBUG) Log.v(TAG, "stopStatistics()") 423 | statisticsTimer?.apply { 424 | Log.i(TAG, "Stop statistics") 425 | cancel() 426 | } 427 | statisticsTimer = null 428 | } 429 | 430 | private fun setKeepScreenOn(enable: Boolean) { 431 | if (DEBUG) Log.v(TAG, "setKeepScreenOn(enable=$enable)") 432 | if (enable) { 433 | activity?.apply { 434 | window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) 435 | Log.i(TAG, "Enabled keep screen on") 436 | } 437 | } else { 438 | activity?.apply { 439 | window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) 440 | Log.i(TAG, "Disabled keep screen on") 441 | } 442 | } 443 | } 444 | companion object { 445 | private val TAG: String = LiveFragment::class.java.simpleName 446 | private const val DEBUG = true 447 | } 448 | 449 | } 450 | -------------------------------------------------------------------------------- /app/src/main/java/com/alexvas/rtsp/demo/live/LiveViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.alexvas.rtsp.demo.live 2 | 3 | import android.annotation.SuppressLint 4 | import android.content.Context 5 | import android.text.Editable 6 | import android.text.TextWatcher 7 | import android.util.Log 8 | import android.widget.EditText 9 | import androidx.lifecycle.MutableLiveData 10 | import androidx.lifecycle.ViewModel 11 | 12 | private const val RTSP_REQUEST_KEY = "rtsp_request" 13 | private const val RTSP_USERNAME_KEY = "rtsp_username" 14 | private const val RTSP_PASSWORD_KEY = "rtsp_password" 15 | 16 | private const val DEFAULT_RTSP_REQUEST = "rtsp://10.0.1.3:554/axis-media/media.amp" 17 | private const val DEFAULT_RTSP_USERNAME = "" 18 | private const val DEFAULT_RTSP_PASSWORD = "" 19 | 20 | private const val LIVE_PARAMS_FILENAME = "live_params" 21 | 22 | @SuppressLint("LogNotTimber") 23 | class LiveViewModel : ViewModel() { 24 | 25 | val rtspRequest = MutableLiveData().apply { 26 | value = DEFAULT_RTSP_REQUEST 27 | } 28 | val rtspUsername = MutableLiveData().apply { 29 | value = DEFAULT_RTSP_USERNAME 30 | } 31 | val rtspPassword = MutableLiveData().apply { 32 | value = DEFAULT_RTSP_PASSWORD 33 | } 34 | 35 | // private val _text = MutableLiveData().apply { 36 | // value = "This is live Fragment" 37 | // } 38 | // val text: LiveData = _text 39 | 40 | // init { 41 | // // Here you could use the ID to get the user info from the DB or remote server 42 | // rtspRequest.value = "rtsp://10.0.1.3:554/axis-media/media.amp" 43 | // } 44 | 45 | fun loadParams(context: Context) { 46 | if (DEBUG) Log.v(TAG, "loadParams()") 47 | val pref = context.getSharedPreferences(LIVE_PARAMS_FILENAME, Context.MODE_PRIVATE) 48 | try { 49 | rtspRequest.setValue(pref.getString(RTSP_REQUEST_KEY, DEFAULT_RTSP_REQUEST)) 50 | } catch (e: ClassCastException) { 51 | e.printStackTrace() 52 | } 53 | try { 54 | rtspUsername.setValue(pref.getString(RTSP_USERNAME_KEY, DEFAULT_RTSP_USERNAME)) 55 | } catch (e: ClassCastException) { 56 | e.printStackTrace() 57 | } 58 | try { 59 | rtspPassword.setValue(pref.getString(RTSP_PASSWORD_KEY, DEFAULT_RTSP_PASSWORD)) 60 | } catch (e: ClassCastException) { 61 | e.printStackTrace() 62 | } 63 | } 64 | 65 | fun saveParams(context: Context) { 66 | if (DEBUG) Log.v(TAG, "saveParams()") 67 | context.getSharedPreferences(LIVE_PARAMS_FILENAME, Context.MODE_PRIVATE).edit().apply { 68 | putString(RTSP_REQUEST_KEY, rtspRequest.value) 69 | putString(RTSP_USERNAME_KEY, rtspUsername.value) 70 | putString(RTSP_PASSWORD_KEY, rtspPassword.value) 71 | apply() 72 | } 73 | } 74 | 75 | fun initEditTexts(etRtspRequest: EditText, etRtspUsername: EditText, etRtspPassword: EditText) { 76 | if (DEBUG) Log.v(TAG, "initEditTexts()") 77 | etRtspRequest.addTextChangedListener(object : TextWatcher { 78 | override fun afterTextChanged(s: Editable?) { 79 | } 80 | override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { 81 | } 82 | override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { 83 | val text = s.toString() 84 | if (text != rtspRequest.value) { 85 | rtspRequest.value = text 86 | } 87 | } 88 | }) 89 | etRtspUsername.addTextChangedListener(object : TextWatcher { 90 | override fun afterTextChanged(s: Editable?) { 91 | } 92 | override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { 93 | } 94 | override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { 95 | val text = s.toString() 96 | if (text != rtspUsername.value) { 97 | rtspUsername.value = text 98 | } 99 | } 100 | }) 101 | etRtspPassword.addTextChangedListener(object : TextWatcher { 102 | override fun afterTextChanged(s: Editable?) { 103 | } 104 | override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { 105 | } 106 | override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { 107 | val text = s.toString() 108 | if (text != rtspPassword.value) { 109 | rtspPassword.value = text 110 | } 111 | } 112 | }) 113 | } 114 | 115 | companion object { 116 | private val TAG: String = LiveViewModel::class.java.simpleName 117 | private const val DEBUG = false 118 | 119 | 120 | } 121 | 122 | } 123 | -------------------------------------------------------------------------------- /app/src/main/java/com/alexvas/rtsp/demo/live/RawFragment.kt: -------------------------------------------------------------------------------- 1 | package com.alexvas.rtsp.demo.live 2 | 3 | import android.annotation.SuppressLint 4 | import android.net.Uri 5 | import android.os.Bundle 6 | import android.util.Log 7 | import android.view.LayoutInflater 8 | import android.view.View 9 | import android.view.ViewGroup 10 | import androidx.fragment.app.Fragment 11 | import androidx.lifecycle.ViewModelProvider 12 | import com.alexvas.rtsp.RtspClient 13 | import com.alexvas.rtsp.demo.databinding.FragmentRawBinding 14 | import com.alexvas.rtsp.widget.toHexString 15 | import com.alexvas.utils.NetUtils 16 | import kotlinx.coroutines.Runnable 17 | import java.net.Socket 18 | import java.util.Timer 19 | import java.util.TimerTask 20 | import java.util.concurrent.atomic.AtomicBoolean 21 | import kotlin.math.min 22 | 23 | @SuppressLint("LogNotTimber") 24 | class RawFragment : Fragment() { 25 | 26 | private lateinit var binding: FragmentRawBinding 27 | private lateinit var liveViewModel: LiveViewModel 28 | 29 | private var statisticsTimer: Timer? = null 30 | private val rtspStopped = AtomicBoolean(true) 31 | 32 | private var rtspVideoBytesReceived: Long = 0 33 | private var rtspVideoFramesReceived: Long = 0 34 | private var rtspAudioBytesReceived: Long = 0 35 | private var rtspAudioSamplesReceived: Long = 0 36 | private var rtspApplicationBytesReceived: Long = 0 37 | private var rtspApplicationSamplesReceived: Long = 0 38 | 39 | private val rtspClientListener = object: RtspClient.RtspClientListener { 40 | override fun onRtspConnecting() { 41 | if (DEBUG) Log.v(TAG, "onRtspConnecting()") 42 | rtspVideoBytesReceived = 0 43 | rtspVideoFramesReceived = 0 44 | rtspAudioBytesReceived = 0 45 | rtspAudioSamplesReceived = 0 46 | rtspApplicationBytesReceived = 0 47 | rtspApplicationSamplesReceived = 0 48 | 49 | binding.apply { 50 | root.post { 51 | updateStatistics() 52 | llRtspParams.etRtspRequest.isEnabled = false 53 | llRtspParams.etRtspUsername.isEnabled = false 54 | llRtspParams.etRtspPassword.isEnabled = false 55 | llRtspParams.cbVideo.isEnabled = false 56 | llRtspParams.cbAudio.isEnabled = false 57 | llRtspParams.cbApplication.isEnabled = false 58 | llRtspParams.cbDebug.isEnabled = false 59 | tvStatusSurface.text = "RTSP connecting" 60 | bnStartStop.text = "Stop RTSP" 61 | } 62 | } 63 | } 64 | 65 | override fun onRtspConnected(sdpInfo: RtspClient.SdpInfo) { 66 | if (DEBUG) Log.v(TAG, "onRtspConnected()") 67 | binding.apply { 68 | root.post { 69 | tvStatusSurface.text = "RTSP connected" 70 | } 71 | } 72 | startStatistics() 73 | } 74 | 75 | override fun onRtspVideoNalUnitReceived(data: ByteArray, offset: Int, length: Int, timestamp: Long) { 76 | val numBytesDump = min(length, 25) // dump max 25 bytes 77 | Log.i(TAG, "RTSP video data ($length bytes): ${data.toHexString(offset, offset + numBytesDump)}") 78 | rtspVideoBytesReceived += length 79 | rtspVideoFramesReceived++ 80 | } 81 | 82 | override fun onRtspAudioSampleReceived(data: ByteArray, offset: Int, length: Int, timestamp: Long) { 83 | val numBytesDump = min(length, 25) // dump max 25 bytes 84 | Log.i(TAG, "RTSP audio data ($length bytes): ${data.toHexString(offset, offset + numBytesDump)}") 85 | rtspAudioBytesReceived += length 86 | rtspAudioSamplesReceived++ 87 | } 88 | 89 | override fun onRtspApplicationDataReceived(data: ByteArray, offset: Int, length: Int, timestamp: Long) { 90 | val numBytesDump = min(length, 25) // dump max 25 bytes 91 | Log.i(TAG, "RTSP app data ($length bytes): ${data.toHexString(offset, offset + numBytesDump)}") 92 | rtspApplicationBytesReceived += length 93 | rtspApplicationSamplesReceived++ 94 | } 95 | 96 | override fun onRtspDisconnecting() { 97 | if (DEBUG) Log.v(TAG, "onRtspDisconnecting()") 98 | binding.apply { 99 | root.post { 100 | tvStatusSurface.text = "RTSP disconnecting" 101 | } 102 | } 103 | stopStatistics() 104 | } 105 | 106 | override fun onRtspDisconnected() { 107 | if (DEBUG) Log.v(TAG, "onRtspDisconnected()") 108 | binding.apply { 109 | root.post { 110 | tvStatusSurface.text = "RTSP disconnected" 111 | bnStartStop.text = "Start RTSP" 112 | llRtspParams.cbVideo.isEnabled = true 113 | llRtspParams.cbAudio.isEnabled = true 114 | llRtspParams.cbApplication.isEnabled = true 115 | llRtspParams.cbDebug.isEnabled = true 116 | llRtspParams.etRtspRequest.isEnabled = true 117 | llRtspParams.etRtspUsername.isEnabled = true 118 | llRtspParams.etRtspPassword.isEnabled = true 119 | } 120 | } 121 | } 122 | 123 | override fun onRtspFailedUnauthorized() { 124 | if (DEBUG) Log.e(TAG, "onRtspFailedUnauthorized()") 125 | Log.e(TAG, "RTSP failed unauthorized") 126 | if (context == null) return 127 | onRtspDisconnected() 128 | binding.apply { 129 | root.post { 130 | tvStatusSurface.text = "RTSP username or password invalid" 131 | } 132 | } 133 | } 134 | 135 | override fun onRtspFailed(message: String?) { 136 | if (DEBUG) Log.e(TAG, "onRtspFailed(message='$message')") 137 | Log.e(TAG, "RTSP failed with message '$message'") 138 | if (context == null) return 139 | onRtspDisconnected() 140 | binding.apply { 141 | root.post { 142 | tvStatusSurface.text = "Error: $message" 143 | } 144 | } 145 | } 146 | } 147 | 148 | private val threadRunnable = Runnable { 149 | Log.i(TAG, "Thread started") 150 | var socket: Socket? = null 151 | try { 152 | val uri = Uri.parse(liveViewModel.rtspRequest.value) 153 | val port = if (uri.port == -1) DEFAULT_RTSP_PORT else uri.port 154 | socket = NetUtils.createSocketAndConnect(uri.host!!, port, 5000) 155 | 156 | val rtspClient = 157 | RtspClient.Builder( 158 | socket, 159 | uri.toString(), 160 | rtspStopped, 161 | rtspClientListener 162 | ) 163 | .requestVideo(binding.llRtspParams.cbVideo.isChecked) 164 | .requestAudio(binding.llRtspParams.cbAudio.isChecked) 165 | .requestApplication(binding.llRtspParams.cbApplication.isChecked) 166 | .withDebug(binding.llRtspParams.cbDebug.isChecked) 167 | .withUserAgent("rtsp-client-android") 168 | .withCredentials( 169 | binding.llRtspParams.etRtspUsername.text.toString(), 170 | binding.llRtspParams.etRtspPassword.text.toString()) 171 | .build() 172 | 173 | rtspClient.execute() 174 | } catch (e: Exception) { 175 | e.printStackTrace() 176 | binding.root.post { rtspClientListener.onRtspFailed(e.message) } 177 | } finally { 178 | NetUtils.closeSocket(socket) 179 | } 180 | Log.i(TAG, "Thread stopped") 181 | } 182 | 183 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { 184 | if (DEBUG) Log.v(TAG, "onCreateView()") 185 | 186 | liveViewModel = ViewModelProvider(this)[LiveViewModel::class.java] 187 | binding = FragmentRawBinding.inflate(inflater, container, false) 188 | 189 | liveViewModel.initEditTexts( 190 | binding.llRtspParams.etRtspRequest, 191 | binding.llRtspParams.etRtspUsername, 192 | binding.llRtspParams.etRtspPassword 193 | ) 194 | liveViewModel.rtspRequest.observe(viewLifecycleOwner) { 195 | if (binding.llRtspParams.etRtspRequest.text.toString() != it) 196 | binding.llRtspParams.etRtspRequest.setText(it) 197 | } 198 | liveViewModel.rtspUsername.observe(viewLifecycleOwner) { 199 | if (binding.llRtspParams.etRtspUsername.text.toString() != it) 200 | binding.llRtspParams.etRtspUsername.setText(it) 201 | } 202 | liveViewModel.rtspPassword.observe(viewLifecycleOwner) { 203 | if (binding.llRtspParams.etRtspPassword.text.toString() != it) 204 | binding.llRtspParams.etRtspPassword.setText(it) 205 | } 206 | 207 | binding.bnStartStop.setOnClickListener { 208 | if (DEBUG) Log.v(TAG, "onClick() rtspStopped=${rtspStopped.get()}") 209 | if (rtspStopped.get()) { 210 | rtspStopped.set(false) 211 | Log.i(TAG, "Thread starting...") 212 | Thread(threadRunnable).apply { 213 | name = "RTSP raw thread" 214 | start() 215 | } 216 | } else { 217 | Log.i(TAG, "Thread stopping...") 218 | rtspStopped.set(true) 219 | } 220 | } 221 | return binding.root 222 | } 223 | 224 | override fun onResume() { 225 | if (DEBUG) Log.v(TAG, "onResume()") 226 | super.onResume() 227 | liveViewModel.loadParams(requireContext()) 228 | } 229 | 230 | override fun onPause() { 231 | if (DEBUG) Log.v(TAG, "onPause()") 232 | super.onPause() 233 | liveViewModel.saveParams(requireContext()) 234 | 235 | stopStatistics() 236 | rtspStopped.set(true) 237 | } 238 | 239 | private fun updateStatistics() { 240 | // if (DEBUG) Log.v(TAG, "updateStatistics()") 241 | binding.apply { 242 | tvStatisticsVideo.text = "Video: $rtspVideoBytesReceived bytes, $rtspVideoFramesReceived frames" 243 | tvStatisticsAudio.text = "Audio: $rtspAudioBytesReceived bytes, $rtspAudioSamplesReceived samples" 244 | tvStatisticsApplication.text = "Application: $rtspApplicationBytesReceived bytes, $rtspApplicationSamplesReceived samples" 245 | } 246 | } 247 | 248 | private fun startStatistics() { 249 | if (DEBUG) Log.v(TAG, "startStatistics()") 250 | Log.i(TAG, "Start statistics") 251 | if (statisticsTimer == null) { 252 | val task: TimerTask = object : TimerTask() { 253 | override fun run() { 254 | binding.root.post { 255 | updateStatistics() 256 | } 257 | } 258 | } 259 | statisticsTimer = Timer("${TAG}::Statistics").apply { 260 | schedule(task, 0, 1000) 261 | } 262 | } 263 | } 264 | 265 | private fun stopStatistics() { 266 | if (DEBUG) Log.v(TAG, "stopStatistics()") 267 | statisticsTimer?.apply { 268 | Log.i(TAG, "Stop statistics") 269 | cancel() 270 | } 271 | statisticsTimer = null 272 | } 273 | 274 | companion object { 275 | private val TAG: String = RawFragment::class.java.simpleName 276 | private const val DEBUG = true 277 | 278 | private const val DEFAULT_RTSP_PORT = 554 279 | } 280 | 281 | } 282 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_camera_black_24dp.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_cctv_black_24dp.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_text_subject_black_24dp.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 17 | 18 | 25 | 26 | -------------------------------------------------------------------------------- /app/src/main/res/layout/fragment_live.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 15 | 16 | 19 | 20 | 27 | 28 |