Repository: alexeyvasilyev/rtsp-client-android Branch: master Commit: 0c0dd61e20eb Files: 66 Total size: 354.9 KB Directory structure: gitextract_xa9itofy/ ├── .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 ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.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 │ │ │ │ ├── AudioParser.kt │ │ │ │ ├── G711Parser.kt │ │ │ │ ├── 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 ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ github: alexeyvasilyev ================================================ FILE: .gitignore ================================================ *.iml .gradle /local.properties /.idea /build .DS_Store ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # rtsp-client-android 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.). 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. [![Release](https://jitpack.io/v/alexeyvasilyev/rtsp-client-android.svg)](https://jitpack.io/#alexeyvasilyev/rtsp-client-android) ![Screenshot](docs/images/rtsp-demo-app.webp?raw=true "Screenshot") ## Features: - RTSP/RTSPS over TCP. - Supports majority of RTSP IP cameras. - Video H.264/H.265. - Audio AAC LC, G.711 uLaw, G.711 aLaw. - 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)) - Basic/Digest authentication. - Uses Android's [Low-Latency MediaCodec](https://source.android.com/docs/core/media/low-latency-media) by default if available. - Ability to select hardware or software video decoder. - 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). - Video rotation (90, 180, 270 degrees). - Android min API 24. ## Upcoming features: - 2-w talk. ## Permissions: ```xml ``` ## Compile To use this library in your project add this to your build.gradle: ```gradle allprojects { repositories { maven { url 'https://jitpack.io' } } } dependencies { implementation 'com.github.alexeyvasilyev:rtsp-client-android:x.x.x' } ``` ## How to use: Easiest way is just to use `RtspSurfaceView` (recommended) or `RtspImageView` classes for showing video stream in UI. 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) 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). ```xml ``` Then in code use: ```kotlin val uri = Uri.parse("rtsps://10.0.1.3/test.sdp") val username = "admin" val password = "secret" svVideo.init(uri, username, password) svVideo.start( requestVideo = true, requestAudio = true, requestApplication = false) // ... svVideo.stop() ``` 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. ```kotlin val rtspClientListener = object: RtspClient.RtspClientListener { override fun onRtspConnecting() {} override fun onRtspConnected(sdpInfo: SdpInfo) {} override fun onRtspVideoNalUnitReceived(data: ByteArray, offset: Int, length: Int, timestamp: Long) { // Send raw H264/H265 NAL unit to decoder } override fun onRtspAudioSampleReceived(data: ByteArray, offset: Int, length: Int, timestamp: Long) { // Send raw audio to decoder } override fun onRtspApplicationDataReceived(data: ByteArray, offset: Int, length: Int, timestamp: Long) { // Send raw application data to app specific parser } override fun onRtspDisconnected() {} override fun onRtspFailedUnauthorized() { Log.e(TAG, "RTSP failed unauthorized"); } override fun onRtspFailed(message: String?) { Log.e(TAG, "RTSP failed with message '$message'") } } val uri = Uri.parse("rtsps://10.0.1.3/test.sdp") val username = "admin" val password = "secret" val stopped = new AtomicBoolean(false) val sslSocket = NetUtils.createSslSocketAndConnect(uri.getHost(), uri.getPort(), 5000) val rtspClient = RtspClient.Builder(sslSocket, uri.toString(), stopped, rtspClientListener) .requestVideo(true) .requestAudio(true) .withDebug(false) .withUserAgent("RTSP client") .withCredentials(username, password) .build() // Blocking call until stopped variable is true or connection failed rtspClient.execute() NetUtils.closeSocket(sslSocket) ``` ## How to get lowest possible latency: There are two types of latencies: ### Network latency 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). Another option to try is to decrease stream bitrate on RTSP camera. Less frame size leads to less time needed for frame transfer. ### Video decoder latency Video decoder latency can vary significantly on different Android devices and on different RTSP camera streams. 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. 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. Check `max_num_reorder_frames` param as well. For best latency it's value should be `0`. 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. ================================================ FILE: app/.gitignore ================================================ # Created by https://www.gitignore.io/api/android,java,intellij ### Android ### # Built application files *.apk *.ap_ # Files for the Dalvik VM *.dex # Java class files *.class # Generated files bin/ gen/ # Gradle files .gradle/ build/ # Local configuration file (sdk path, etc) local.properties # Proguard folder generated by Eclipse proguard/ xactmobile/class_files.txt xactmobile/mapping.txt xactmobile/seeds.txt # Log Files *.log # Android Studio Navigation editor temp files .navigation/ ### Android Patch ### gen-external-apklibs ### Java ### *.class # Mobile Tools for Java (J2ME) .mtj.tmp/ # Package Files # #*.jar *.war *.ear # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* ### Intellij ### # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio *.iml ## Directory-based project format: .idea/ # if you remove the above rule, at least ignore the following: # User-specific stuff: .idea/workspace.xml .idea/tasks.xml .idea/dictionaries # Sensitive or high-churn files: .idea/dataSources.ids .idea/dataSources.xml .idea/sqlDataSources.xml .idea/dynamic.xml .idea/uiDesigner.xml # Gradle: .idea/gradle.xml .idea/libraries # Mongo Explorer plugin: .idea/mongoSettings.xml ## File-based project format: *.ipr *.iws ## Plugin-specific files: # IntelliJ /out/ # mpeltonen/sbt-idea plugin .idea_modules/ # JIRA plugin atlassian-ide-plugin.xml # Crashlytics plugin (for Android Studio and IntelliJ) com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties xactmobile/.DS_Store~64be78fe3602626c61b52bcbfd09e09a6107b50a xactmobile/.DS_Store~HEAD oslab-viewpager/._.DS_Store oslab-viewpager/src/main/.DS_Store oslab-viewpager/src/main/._.DS_Store oslab-viewpager/src/main/res/.DS_Store oslab-viewpager/src/main/res/._.DS_Store oslab-viewpager/.gitignore oslab-materialdesign/.DS_Store oslab-materialdesign/._.DS_Store oslab-materialdesign/src/.DS_Store oslab-materialdesign/src/._.DS_Store oslab-materialdesign/src/main/.DS_Store oslab-materialdesign/src/main/._.DS_Store oslab-materialdesign/src/main/res/.DS_Store oslab-materialdesign/src/main/res/._.DS_Store ================================================ FILE: app/build.gradle ================================================ apply plugin: 'com.android.application' apply plugin: 'kotlin-android' android { compileSdkVersion 36 defaultConfig { applicationId "com.alexvas.rtsp.demo" minSdk 24 targetSdk 34 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } // To inline the bytecode built with JVM target 1.8 into // bytecode that is being built with JVM target 1.6. (e.g. navArgs) compileOptions { sourceCompatibility JavaVersion.VERSION_17 targetCompatibility JavaVersion.VERSION_17 } kotlinOptions { jvmTarget = JavaVersion.VERSION_17.toString() } buildFeatures { viewBinding true } namespace 'com.alexvas.rtsp.demo' } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'androidx.appcompat:appcompat:1.7.1' implementation 'androidx.core:core-ktx:1.18.0' implementation 'com.google.android.material:material:1.13.0' implementation 'androidx.constraintlayout:constraintlayout:2.2.1' implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' def androidx_navigation_version = '2.9.7' implementation "androidx.navigation:navigation-fragment-ktx:$androidx_navigation_version" implementation "androidx.navigation:navigation-ui-ktx:$androidx_navigation_version" implementation "androidx.navigation:navigation-fragment-ktx:$androidx_navigation_version" implementation "androidx.navigation:navigation-ui-ktx:$androidx_navigation_version" def logcat_core_version = '3.4' api "com.github.AppDevNext.Logcat:LogcatCoreLib:$logcat_core_version" api "com.github.AppDevNext.Logcat:LogcatCoreUI:$logcat_core_version" implementation project(':library-client-rtsp') } ================================================ FILE: app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/java/com/alexvas/rtsp/demo/MainActivity.kt ================================================ package com.alexvas.rtsp.demo import android.os.Bundle import com.google.android.material.bottomnavigation.BottomNavigationView import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.setupWithNavController class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val navView: BottomNavigationView = findViewById(R.id.nav_view) val navController = findNavController(R.id.nav_host_fragment) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. // val appBarConfiguration = AppBarConfiguration(setOf( // R.id.navigation_live, R.id.navigation_logs)) // setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) } } ================================================ FILE: app/src/main/java/com/alexvas/rtsp/demo/live/LiveFragment.kt ================================================ package com.alexvas.rtsp.demo.live import android.annotation.SuppressLint import android.graphics.Bitmap import android.os.Bundle import android.os.Handler import android.os.HandlerThread import android.util.Log import android.view.LayoutInflater import android.view.PixelCopy import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.widget.Toast import androidx.constraintlayout.widget.ConstraintSet import androidx.core.net.toUri import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.alexvas.rtsp.codec.VideoDecodeThread import com.alexvas.rtsp.demo.databinding.FragmentLiveBinding import com.alexvas.rtsp.widget.RtspDataListener import com.alexvas.rtsp.widget.RtspImageView import com.alexvas.rtsp.widget.RtspStatusListener import com.alexvas.rtsp.widget.toHexString import java.util.Timer import java.util.TimerTask import java.util.concurrent.atomic.AtomicBoolean import kotlin.math.min @SuppressLint("LogNotTimber") class LiveFragment : Fragment() { private lateinit var binding: FragmentLiveBinding private lateinit var liveViewModel: LiveViewModel private var statisticsTimer: Timer? = null private var svVideoSurfaceResolution = Pair(0, 0) private val rtspStatusSurfaceListener = object: RtspStatusListener { override fun onRtspStatusConnecting() { if (DEBUG) Log.v(TAG, "onRtspStatusConnecting()") binding.apply { tvStatusSurface.text = "RTSP connecting" pbLoadingSurface.visibility = View.VISIBLE vShutterSurface.visibility = View.VISIBLE llRtspParams.apply { etRtspRequest.isEnabled = false etRtspUsername.isEnabled = false etRtspPassword.isEnabled = false cbVideo.isEnabled = false cbAudio.isEnabled = false cbApplication.isEnabled = false cbDebug.isEnabled = false } tgRotation.isEnabled = false } } override fun onRtspStatusConnected() { if (DEBUG) Log.v(TAG, "onRtspStatusConnected()") binding.apply { tvStatusSurface.text = "RTSP connected" bnStartStopSurface.text = "Stop RTSP" } setKeepScreenOn(true) } override fun onRtspStatusDisconnecting() { if (DEBUG) Log.v(TAG, "onRtspStatusDisconnecting()") binding.apply { tvStatusSurface.text = "RTSP disconnecting" } } override fun onRtspStatusDisconnected() { if (DEBUG) Log.v(TAG, "onRtspStatusDisconnected()") binding.apply { tvStatusSurface.text = "RTSP disconnected" bnStartStopSurface.text = "Start RTSP" pbLoadingSurface.visibility = View.GONE vShutterSurface.visibility = View.VISIBLE pbLoadingSurface.isEnabled = false llRtspParams.apply { cbVideo.isEnabled = true cbAudio.isEnabled = true cbApplication.isEnabled = true cbDebug.isEnabled = true etRtspRequest.isEnabled = true etRtspUsername.isEnabled = true etRtspPassword.isEnabled = true } tgRotation.isEnabled = true } setKeepScreenOn(false) } override fun onRtspStatusFailedUnauthorized() { if (DEBUG) Log.e(TAG, "onRtspStatusFailedUnauthorized()") if (context == null) return onRtspStatusDisconnected() binding.apply { tvStatusSurface.text = "RTSP username or password invalid" pbLoadingSurface.visibility = View.GONE } } override fun onRtspStatusFailed(message: String?) { if (DEBUG) Log.e(TAG, "onRtspStatusFailed(message='$message')") if (context == null) return onRtspStatusDisconnected() binding.apply { tvStatusSurface.text = "Error: $message" pbLoadingSurface.visibility = View.GONE } } override fun onRtspFirstFrameRendered() { if (DEBUG) Log.v(TAG, "onRtspFirstFrameRendered()") Log.i(TAG, "First frame rendered") binding.apply { pbLoadingSurface.visibility = View.GONE vShutterSurface.visibility = View.GONE bnSnapshotSurface.isEnabled = true } } override fun onRtspFrameSizeChanged(width: Int, height: Int) { if (DEBUG) Log.v(TAG, "onRtspFrameSizeChanged(width=$width, height=$height)") Log.i(TAG, "Video resolution changed to ${width}x${height}") svVideoSurfaceResolution = Pair(width, height) ConstraintSet().apply { clone(binding.csVideoSurface) setDimensionRatio(binding.svVideoSurface.id, "$width:$height") applyTo(binding.csVideoSurface) } } } private val rtspDataListener = object: RtspDataListener { override fun onRtspDataApplicationDataReceived(data: ByteArray, offset: Int, length: Int, timestamp: Long) { val numBytesDump = min(length, 25) // dump max 25 bytes Log.i(TAG, "RTSP app data ($length bytes): ${data.toHexString(offset, offset + numBytesDump)}") } } private val rtspStatusImageListener = object: RtspStatusListener { override fun onRtspStatusConnecting() { if (DEBUG) Log.v(TAG, "onRtspStatusConnecting()") binding.apply { tvStatusImage.text = "RTSP connecting" pbLoadingImage.visibility = View.VISIBLE vShutterImage.visibility = View.VISIBLE } } override fun onRtspStatusConnected() { if (DEBUG) Log.v(TAG, "onRtspStatusConnected()") binding.apply { tvStatusImage.text = "RTSP connected" bnStartStopImage.text = "Stop RTSP" } setKeepScreenOn(true) } override fun onRtspStatusDisconnecting() { if (DEBUG) Log.v(TAG, "onRtspStatusDisconnecting()") binding.apply { tvStatusImage.text = "RTSP disconnecting" } } override fun onRtspStatusDisconnected() { if (DEBUG) Log.v(TAG, "onRtspStatusDisconnected()") binding.apply { tvStatusImage.text = "RTSP disconnected" bnStartStopImage.text = "Start RTSP" pbLoadingImage.visibility = View.GONE vShutterImage.visibility = View.VISIBLE pbLoadingImage.isEnabled = false } setKeepScreenOn(false) } override fun onRtspStatusFailedUnauthorized() { if (DEBUG) Log.e(TAG, "onRtspStatusFailedUnauthorized()") if (context == null) return onRtspStatusDisconnected() binding.apply { tvStatusImage.text = "RTSP username or password invalid" pbLoadingImage.visibility = View.GONE } } override fun onRtspStatusFailed(message: String?) { if (DEBUG) Log.e(TAG, "onRtspStatusFailed(message='$message')") if (context == null) return onRtspStatusDisconnected() binding.apply { tvStatusImage.text = "Error: $message" pbLoadingImage.visibility = View.GONE } } override fun onRtspFirstFrameRendered() { if (DEBUG) Log.v(TAG, "onRtspFirstFrameRendered()") Log.i(TAG, "First frame rendered") binding.apply { vShutterImage.visibility = View.GONE pbLoadingImage.visibility = View.GONE } } override fun onRtspFrameSizeChanged(width: Int, height: Int) { if (DEBUG) Log.v(TAG, "onRtspFrameSizeChanged(width=$width, height=$height)") Log.i(TAG, "Video resolution changed to ${width}x${height}") ConstraintSet().apply { clone(binding.csVideoImage) setDimensionRatio(binding.ivVideoImage.id, "$width:$height") applyTo(binding.csVideoImage) } } } private fun getSnapshot(): Bitmap? { if (DEBUG) Log.v(TAG, "getSnapshot()") val surfaceBitmap = Bitmap.createBitmap( svVideoSurfaceResolution.first, svVideoSurfaceResolution.second, Bitmap.Config.ARGB_8888 ) val lock = Object() val success = AtomicBoolean(false) val thread = HandlerThread("PixelCopyHelper") thread.start() val sHandler = Handler(thread.looper) val listener = PixelCopy.OnPixelCopyFinishedListener { copyResult -> success.set(copyResult == PixelCopy.SUCCESS) synchronized (lock) { lock.notify() } } synchronized (lock) { PixelCopy.request(binding.svVideoSurface.holder.surface, surfaceBitmap, listener, sHandler) lock.wait() } thread.quitSafely() return if (success.get()) surfaceBitmap else null } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { if (DEBUG) Log.v(TAG, "onCreateView()") liveViewModel = ViewModelProvider(this)[LiveViewModel::class.java] binding = FragmentLiveBinding.inflate(inflater, container, false) binding.bnVideoDecoderGroup.check(binding.bnVideoDecoderHardware.id) binding.svVideoSurface.setStatusListener(rtspStatusSurfaceListener) binding.svVideoSurface.setDataListener(rtspDataListener) binding.ivVideoImage.setStatusListener(rtspStatusImageListener) binding.ivVideoImage.setDataListener(rtspDataListener) liveViewModel.initEditTexts( binding.llRtspParams.etRtspRequest, binding.llRtspParams.etRtspUsername, binding.llRtspParams.etRtspPassword ) liveViewModel.rtspRequest.observe(viewLifecycleOwner) { if (binding.llRtspParams.etRtspRequest.text.toString() != it) binding.llRtspParams.etRtspRequest.setText(it) } liveViewModel.rtspUsername.observe(viewLifecycleOwner) { if (binding.llRtspParams.etRtspUsername.text.toString() != it) binding.llRtspParams.etRtspUsername.setText(it) } liveViewModel.rtspPassword.observe(viewLifecycleOwner) { if (binding.llRtspParams.etRtspPassword.text.toString() != it) binding.llRtspParams.etRtspPassword.setText(it) } binding.cbVideoFpsStabilization.setOnCheckedChangeListener { _, isChecked -> binding.svVideoSurface.videoFrameRateStabilization = isChecked } binding.cbExperimentalRewriteSps.setOnCheckedChangeListener { _, isChecked -> binding.svVideoSurface.experimentalUpdateSpsFrameWithLowLatencyParams = isChecked } binding.bnRotate0.setOnClickListener { binding.svVideoSurface.videoRotation = 0 binding.ivVideoImage.videoRotation = 0 } binding.bnRotate90.setOnClickListener { binding.svVideoSurface.videoRotation = 90 binding.ivVideoImage.videoRotation = 90 } binding.bnRotate180.setOnClickListener { binding.svVideoSurface.videoRotation = 180 binding.ivVideoImage.videoRotation = 180 } binding.bnRotate270.setOnClickListener { binding.svVideoSurface.videoRotation = 270 binding.ivVideoImage.videoRotation = 270 } binding.bnRotate0.performClick() binding.bnVideoDecoderHardware.setOnClickListener { binding.svVideoSurface.videoDecoderType = VideoDecodeThread.DecoderType.HARDWARE binding.ivVideoImage.videoDecoderType = VideoDecodeThread.DecoderType.HARDWARE } binding.bnVideoDecoderSoftware.setOnClickListener { binding.svVideoSurface.videoDecoderType = VideoDecodeThread.DecoderType.SOFTWARE binding.ivVideoImage.videoDecoderType = VideoDecodeThread.DecoderType.SOFTWARE } binding.bnStartStopSurface.setOnClickListener { if (binding.svVideoSurface.isStarted()) { binding.svVideoSurface.stop() stopStatistics() } else { val uri = liveViewModel.rtspRequest.value!!.toUri() binding.svVideoSurface.apply { init( uri, username = liveViewModel.rtspUsername.value, password = liveViewModel.rtspPassword.value, userAgent = "rtsp-client-android" ) debug = binding.llRtspParams.cbDebug.isChecked videoFrameRateStabilization = binding.cbVideoFpsStabilization.isChecked start( requestVideo = binding.llRtspParams.cbVideo.isChecked, requestAudio = binding.llRtspParams.cbAudio.isChecked, requestApplication = binding.llRtspParams.cbApplication.isChecked ) } startStatistics() } } binding.bnStartStopImage.setOnClickListener { if (binding.ivVideoImage.isStarted()) { binding.ivVideoImage.stop() stopStatistics() } else { val uri = liveViewModel.rtspRequest.value!!.toUri() binding.ivVideoImage.apply { init( uri, username = liveViewModel.rtspUsername.value, password = liveViewModel.rtspPassword.value, userAgent = "rtsp-client-android" ) debug = binding.llRtspParams.cbDebug.isChecked onRtspImageBitmapListener = object : RtspImageView.RtspImageBitmapListener { override fun onRtspImageBitmapObtained(bitmap: Bitmap) { // TODO: You can send bitmap for processing } } start( requestVideo = binding.llRtspParams.cbVideo.isChecked, requestAudio = binding.llRtspParams.cbAudio.isChecked, requestApplication = binding.llRtspParams.cbApplication.isChecked ) } startStatistics() } } binding.bnSnapshotSurface.setOnClickListener { val bitmap = getSnapshot() // TODO Save snapshot to DCIM folder if (bitmap != null) { Toast.makeText(requireContext(), "Snapshot succeeded ${bitmap.width}x${bitmap.height}", Toast.LENGTH_LONG).show() } else { Toast.makeText(requireContext(), "Snapshot failed", Toast.LENGTH_LONG).show() } } return binding.root } override fun onResume() { if (DEBUG) Log.v(TAG, "onResume()") super.onResume() liveViewModel.loadParams(requireContext()) } override fun onPause() { val started = binding.svVideoSurface.isStarted() if (DEBUG) Log.v(TAG, "onPause(), started:$started") super.onPause() liveViewModel.saveParams(requireContext()) if (started) { binding.svVideoSurface.stop() stopStatistics() } } private fun startStatistics() { if (DEBUG) Log.v(TAG, "startStatistics()") Log.i(TAG, "Start statistics") if (statisticsTimer == null) { val task: TimerTask = object : TimerTask() { override fun run() { val statistics = binding.svVideoSurface.statistics val text = "Video decoder: ${statistics.videoDecoderType.toString().lowercase()} ${if (statistics.videoDecoderName.isNullOrEmpty()) "" else "(${statistics.videoDecoderName})"}" + "\nVideo decoder latency: ${statistics.videoDecoderLatencyMsec} ms" + "\nResolution: ${svVideoSurfaceResolution.first}x${svVideoSurfaceResolution.second}" // "\nNetwork latency: " // // Assume that difference between current Android time and camera time cannot be more than 5 sec. // // Otherwise time need to be synchronized on both devices. // text += if (statistics.networkLatencyMsec == -1) { // "-" // } else if (statistics.networkLatencyMsec < 0 || statistics.networkLatencyMsec > TimeUnit.SECONDS.toMillis(5)) { // "[time out of sync]" // } else { // "${statistics.networkLatencyMsec} ms" // } binding.tvStatistics.post { binding.tvStatistics.text = text } } } statisticsTimer = Timer("${TAG}::Statistics").apply { schedule(task, 0, 1000) } } } private fun stopStatistics() { if (DEBUG) Log.v(TAG, "stopStatistics()") statisticsTimer?.apply { Log.i(TAG, "Stop statistics") cancel() } statisticsTimer = null } private fun setKeepScreenOn(enable: Boolean) { if (DEBUG) Log.v(TAG, "setKeepScreenOn(enable=$enable)") if (enable) { activity?.apply { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) Log.i(TAG, "Enabled keep screen on") } } else { activity?.apply { window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) Log.i(TAG, "Disabled keep screen on") } } } companion object { private val TAG: String = LiveFragment::class.java.simpleName private const val DEBUG = true } } ================================================ FILE: app/src/main/java/com/alexvas/rtsp/demo/live/LiveViewModel.kt ================================================ package com.alexvas.rtsp.demo.live import android.annotation.SuppressLint import android.content.Context import android.text.Editable import android.text.TextWatcher import android.util.Log import android.widget.EditText import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel private const val RTSP_REQUEST_KEY = "rtsp_request" private const val RTSP_USERNAME_KEY = "rtsp_username" private const val RTSP_PASSWORD_KEY = "rtsp_password" private const val DEFAULT_RTSP_REQUEST = "rtsp://10.0.1.3:554/axis-media/media.amp" private const val DEFAULT_RTSP_USERNAME = "" private const val DEFAULT_RTSP_PASSWORD = "" private const val LIVE_PARAMS_FILENAME = "live_params" @SuppressLint("LogNotTimber") class LiveViewModel : ViewModel() { val rtspRequest = MutableLiveData().apply { value = DEFAULT_RTSP_REQUEST } val rtspUsername = MutableLiveData().apply { value = DEFAULT_RTSP_USERNAME } val rtspPassword = MutableLiveData().apply { value = DEFAULT_RTSP_PASSWORD } // private val _text = MutableLiveData().apply { // value = "This is live Fragment" // } // val text: LiveData = _text // init { // // Here you could use the ID to get the user info from the DB or remote server // rtspRequest.value = "rtsp://10.0.1.3:554/axis-media/media.amp" // } fun loadParams(context: Context) { if (DEBUG) Log.v(TAG, "loadParams()") val pref = context.getSharedPreferences(LIVE_PARAMS_FILENAME, Context.MODE_PRIVATE) try { rtspRequest.setValue(pref.getString(RTSP_REQUEST_KEY, DEFAULT_RTSP_REQUEST)) } catch (e: ClassCastException) { e.printStackTrace() } try { rtspUsername.setValue(pref.getString(RTSP_USERNAME_KEY, DEFAULT_RTSP_USERNAME)) } catch (e: ClassCastException) { e.printStackTrace() } try { rtspPassword.setValue(pref.getString(RTSP_PASSWORD_KEY, DEFAULT_RTSP_PASSWORD)) } catch (e: ClassCastException) { e.printStackTrace() } } fun saveParams(context: Context) { if (DEBUG) Log.v(TAG, "saveParams()") context.getSharedPreferences(LIVE_PARAMS_FILENAME, Context.MODE_PRIVATE).edit().apply { putString(RTSP_REQUEST_KEY, rtspRequest.value) putString(RTSP_USERNAME_KEY, rtspUsername.value) putString(RTSP_PASSWORD_KEY, rtspPassword.value) apply() } } fun initEditTexts(etRtspRequest: EditText, etRtspUsername: EditText, etRtspPassword: EditText) { if (DEBUG) Log.v(TAG, "initEditTexts()") etRtspRequest.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { val text = s.toString() if (text != rtspRequest.value) { rtspRequest.value = text } } }) etRtspUsername.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { val text = s.toString() if (text != rtspUsername.value) { rtspUsername.value = text } } }) etRtspPassword.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { val text = s.toString() if (text != rtspPassword.value) { rtspPassword.value = text } } }) } companion object { private val TAG: String = LiveViewModel::class.java.simpleName private const val DEBUG = false } } ================================================ FILE: app/src/main/java/com/alexvas/rtsp/demo/live/RawFragment.kt ================================================ package com.alexvas.rtsp.demo.live import android.annotation.SuppressLint import android.net.Uri import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.alexvas.rtsp.RtspClient import com.alexvas.rtsp.demo.databinding.FragmentRawBinding import com.alexvas.rtsp.widget.toHexString import com.alexvas.utils.NetUtils import kotlinx.coroutines.Runnable import java.net.Socket import java.util.Timer import java.util.TimerTask import java.util.concurrent.atomic.AtomicBoolean import kotlin.math.min @SuppressLint("LogNotTimber") class RawFragment : Fragment() { private lateinit var binding: FragmentRawBinding private lateinit var liveViewModel: LiveViewModel private var statisticsTimer: Timer? = null private val rtspStopped = AtomicBoolean(true) private var rtspVideoBytesReceived: Long = 0 private var rtspVideoFramesReceived: Long = 0 private var rtspAudioBytesReceived: Long = 0 private var rtspAudioSamplesReceived: Long = 0 private var rtspApplicationBytesReceived: Long = 0 private var rtspApplicationSamplesReceived: Long = 0 private val rtspClientListener = object: RtspClient.RtspClientListener { override fun onRtspConnecting() { if (DEBUG) Log.v(TAG, "onRtspConnecting()") rtspVideoBytesReceived = 0 rtspVideoFramesReceived = 0 rtspAudioBytesReceived = 0 rtspAudioSamplesReceived = 0 rtspApplicationBytesReceived = 0 rtspApplicationSamplesReceived = 0 binding.apply { root.post { updateStatistics() llRtspParams.etRtspRequest.isEnabled = false llRtspParams.etRtspUsername.isEnabled = false llRtspParams.etRtspPassword.isEnabled = false llRtspParams.cbVideo.isEnabled = false llRtspParams.cbAudio.isEnabled = false llRtspParams.cbApplication.isEnabled = false llRtspParams.cbDebug.isEnabled = false tvStatusSurface.text = "RTSP connecting" bnStartStop.text = "Stop RTSP" } } } override fun onRtspConnected(sdpInfo: RtspClient.SdpInfo) { if (DEBUG) Log.v(TAG, "onRtspConnected()") binding.apply { root.post { tvStatusSurface.text = "RTSP connected" } } startStatistics() } override fun onRtspVideoNalUnitReceived(data: ByteArray, offset: Int, length: Int, timestamp: Long) { val numBytesDump = min(length, 25) // dump max 25 bytes Log.i(TAG, "RTSP video data ($length bytes): ${data.toHexString(offset, offset + numBytesDump)}") rtspVideoBytesReceived += length rtspVideoFramesReceived++ } override fun onRtspAudioSampleReceived(data: ByteArray, offset: Int, length: Int, timestamp: Long) { val numBytesDump = min(length, 25) // dump max 25 bytes Log.i(TAG, "RTSP audio data ($length bytes): ${data.toHexString(offset, offset + numBytesDump)}") rtspAudioBytesReceived += length rtspAudioSamplesReceived++ } override fun onRtspApplicationDataReceived(data: ByteArray, offset: Int, length: Int, timestamp: Long) { val numBytesDump = min(length, 25) // dump max 25 bytes Log.i(TAG, "RTSP app data ($length bytes): ${data.toHexString(offset, offset + numBytesDump)}") rtspApplicationBytesReceived += length rtspApplicationSamplesReceived++ } override fun onRtspDisconnecting() { if (DEBUG) Log.v(TAG, "onRtspDisconnecting()") binding.apply { root.post { tvStatusSurface.text = "RTSP disconnecting" } } stopStatistics() } override fun onRtspDisconnected() { if (DEBUG) Log.v(TAG, "onRtspDisconnected()") binding.apply { root.post { tvStatusSurface.text = "RTSP disconnected" bnStartStop.text = "Start RTSP" llRtspParams.cbVideo.isEnabled = true llRtspParams.cbAudio.isEnabled = true llRtspParams.cbApplication.isEnabled = true llRtspParams.cbDebug.isEnabled = true llRtspParams.etRtspRequest.isEnabled = true llRtspParams.etRtspUsername.isEnabled = true llRtspParams.etRtspPassword.isEnabled = true } } } override fun onRtspFailedUnauthorized() { if (DEBUG) Log.e(TAG, "onRtspFailedUnauthorized()") Log.e(TAG, "RTSP failed unauthorized") if (context == null) return onRtspDisconnected() binding.apply { root.post { tvStatusSurface.text = "RTSP username or password invalid" } } } override fun onRtspFailed(message: String?) { if (DEBUG) Log.e(TAG, "onRtspFailed(message='$message')") Log.e(TAG, "RTSP failed with message '$message'") if (context == null) return onRtspDisconnected() binding.apply { root.post { tvStatusSurface.text = "Error: $message" } } } } private val threadRunnable = Runnable { Log.i(TAG, "Thread started") var socket: Socket? = null try { val uri = Uri.parse(liveViewModel.rtspRequest.value) val port = if (uri.port == -1) DEFAULT_RTSP_PORT else uri.port socket = NetUtils.createSocketAndConnect(uri.host!!, port, 5000) val rtspClient = RtspClient.Builder( socket, uri.toString(), rtspStopped, rtspClientListener ) .requestVideo(binding.llRtspParams.cbVideo.isChecked) .requestAudio(binding.llRtspParams.cbAudio.isChecked) .requestApplication(binding.llRtspParams.cbApplication.isChecked) .withDebug(binding.llRtspParams.cbDebug.isChecked) .withUserAgent("rtsp-client-android") .withCredentials( binding.llRtspParams.etRtspUsername.text.toString(), binding.llRtspParams.etRtspPassword.text.toString()) .build() rtspClient.execute() } catch (e: Exception) { e.printStackTrace() binding.root.post { rtspClientListener.onRtspFailed(e.message) } } finally { NetUtils.closeSocket(socket) } Log.i(TAG, "Thread stopped") } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { if (DEBUG) Log.v(TAG, "onCreateView()") liveViewModel = ViewModelProvider(this)[LiveViewModel::class.java] binding = FragmentRawBinding.inflate(inflater, container, false) liveViewModel.initEditTexts( binding.llRtspParams.etRtspRequest, binding.llRtspParams.etRtspUsername, binding.llRtspParams.etRtspPassword ) liveViewModel.rtspRequest.observe(viewLifecycleOwner) { if (binding.llRtspParams.etRtspRequest.text.toString() != it) binding.llRtspParams.etRtspRequest.setText(it) } liveViewModel.rtspUsername.observe(viewLifecycleOwner) { if (binding.llRtspParams.etRtspUsername.text.toString() != it) binding.llRtspParams.etRtspUsername.setText(it) } liveViewModel.rtspPassword.observe(viewLifecycleOwner) { if (binding.llRtspParams.etRtspPassword.text.toString() != it) binding.llRtspParams.etRtspPassword.setText(it) } binding.bnStartStop.setOnClickListener { if (DEBUG) Log.v(TAG, "onClick() rtspStopped=${rtspStopped.get()}") if (rtspStopped.get()) { rtspStopped.set(false) Log.i(TAG, "Thread starting...") Thread(threadRunnable).apply { name = "RTSP raw thread" start() } } else { Log.i(TAG, "Thread stopping...") rtspStopped.set(true) } } return binding.root } override fun onResume() { if (DEBUG) Log.v(TAG, "onResume()") super.onResume() liveViewModel.loadParams(requireContext()) } override fun onPause() { if (DEBUG) Log.v(TAG, "onPause()") super.onPause() liveViewModel.saveParams(requireContext()) stopStatistics() rtspStopped.set(true) } private fun updateStatistics() { // if (DEBUG) Log.v(TAG, "updateStatistics()") binding.apply { tvStatisticsVideo.text = "Video: $rtspVideoBytesReceived bytes, $rtspVideoFramesReceived frames" tvStatisticsAudio.text = "Audio: $rtspAudioBytesReceived bytes, $rtspAudioSamplesReceived samples" tvStatisticsApplication.text = "Application: $rtspApplicationBytesReceived bytes, $rtspApplicationSamplesReceived samples" } } private fun startStatistics() { if (DEBUG) Log.v(TAG, "startStatistics()") Log.i(TAG, "Start statistics") if (statisticsTimer == null) { val task: TimerTask = object : TimerTask() { override fun run() { binding.root.post { updateStatistics() } } } statisticsTimer = Timer("${TAG}::Statistics").apply { schedule(task, 0, 1000) } } } private fun stopStatistics() { if (DEBUG) Log.v(TAG, "stopStatistics()") statisticsTimer?.apply { Log.i(TAG, "Stop statistics") cancel() } statisticsTimer = null } companion object { private val TAG: String = RawFragment::class.java.simpleName private const val DEBUG = true private const val DEFAULT_RTSP_PORT = 554 } } ================================================ FILE: app/src/main/res/drawable/ic_camera_black_24dp.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_cctv_black_24dp.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_launcher_background.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_launcher_foreground.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_text_subject_black_24dp.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_main.xml ================================================ ================================================ FILE: app/src/main/res/layout/fragment_live.xml ================================================