first commit

This commit is contained in:
srtk 2025-11-21 21:37:05 +05:30
commit 797c5c48d7
59 changed files with 3217 additions and 0 deletions

1
app/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/build

62
app/build.gradle.kts Normal file
View file

@ -0,0 +1,62 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
}
android {
namespace = "com.srtk.airlink"
compileSdk {
version = release(36)
}
defaultConfig {
applicationId = "com.srtk.airlink"
minSdk = 26
targetSdk = 36
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = "11"
}
buildFeatures {
compose = true
}
}
dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.graphics)
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.compose.material3)
implementation("androidx.compose.material:material-icons-extended:1.7.8")
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.compose.ui.test.junit4)
debugImplementation(libs.androidx.compose.ui.tooling)
debugImplementation(libs.androidx.compose.ui.test.manifest)
}

21
app/proguard-rules.pro vendored Normal file
View file

@ -0,0 +1,21 @@
# 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

View file

@ -0,0 +1,24 @@
package com.srtk.airlink
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.srtk.webcam", appContext.packageName)
}
}

View file

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus"
android:required="false" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="AirLink"
android:supportsRtl="true"
android:theme="@style/Theme.Webcam"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:screenOrientation="fullSensor"
android:configChanges="orientation|screenLayout|screenSize|smallestScreenSize"
android:theme="@style/Theme.Webcam">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

View file

@ -0,0 +1,114 @@
package com.srtk.airlink
import android.content.Context
import android.hardware.camera2.*
import android.media.MediaCodec
import android.util.Log
import android.util.Size
object CameraDiagnostics {
fun printAllCapabilities(context: Context) {
val manager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
println("\n========== CAMERA DIAGNOSTICS ==========\n")
for (cameraId in manager.cameraIdList) {
val characteristics = manager.getCameraCharacteristics(cameraId)
val facing = characteristics.get(CameraCharacteristics.LENS_FACING)
val facingStr = when(facing) {
CameraCharacteristics.LENS_FACING_BACK -> "BACK"
CameraCharacteristics.LENS_FACING_FRONT -> "FRONT"
else -> "EXTERNAL"
}
println("📷 Camera $cameraId ($facingStr)")
println("=" .repeat(50))
// Supported output sizes for MediaCodec
val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
val codecSizes = map?.getOutputSizes(MediaCodec::class.java) ?: emptyArray()
println("\n🎥 Supported Video Resolutions (${codecSizes.size} total):")
codecSizes
.sortedByDescending { it.width * it.height }
.forEach { size ->
val aspectRatio = String.format("%.2f", size.width.toFloat() / size.height)
val mpx = String.format("%.1f", (size.width * size.height) / 1_000_000f)
println("${size.width}x${size.height} ($mpx MP, $aspectRatio:1)")
}
// FPS Ranges
val fpsRanges = characteristics.get(
CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES
) ?: emptyArray()
println("\n📊 Supported FPS Ranges:")
fpsRanges.forEach { range ->
println("${range.lower}-${range.upper} fps")
}
// Max digital zoom
val maxZoom = characteristics.get(
CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM
) ?: 1f
println("\n🔍 Max Zoom: ${maxZoom}x")
// Flash
val hasFlash = characteristics.get(
CameraCharacteristics.FLASH_INFO_AVAILABLE
) == true
println("⚡ Flash: ${if(hasFlash) "Yes" else "No"}")
// Stabilization
val stabilizationModes = characteristics.get(
CameraCharacteristics.CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES
) ?: intArrayOf()
val hasStab = CameraMetadata.CONTROL_VIDEO_STABILIZATION_MODE_ON in stabilizationModes
println("📹 Video Stabilization: ${if(hasStab) "Yes" else "No"}")
// Manual focus
val minFocusDist = characteristics.get(
CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE
) ?: 0f
println("🎯 Manual Focus: ${if(minFocusDist > 0) "Yes" else "No"}")
// Effects
val effects = characteristics.get(
CameraCharacteristics.CONTROL_AVAILABLE_EFFECTS
) ?: intArrayOf()
println("\n🎨 Supported Effects:")
effects.forEach { effect ->
val name = when(effect) {
CameraMetadata.CONTROL_EFFECT_MODE_OFF -> "None"
CameraMetadata.CONTROL_EFFECT_MODE_MONO -> "Mono"
CameraMetadata.CONTROL_EFFECT_MODE_NEGATIVE -> "Negative"
CameraMetadata.CONTROL_EFFECT_MODE_SEPIA -> "Sepia"
CameraMetadata.CONTROL_EFFECT_MODE_AQUA -> "Aqua"
else -> "Unknown($effect)"
}
println("$name")
}
// White Balance
val wbModes = characteristics.get(
CameraCharacteristics.CONTROL_AWB_AVAILABLE_MODES
) ?: intArrayOf()
println("\n☀️ Supported White Balance:")
wbModes.forEach { mode ->
val name = when(mode) {
CameraMetadata.CONTROL_AWB_MODE_AUTO -> "Auto"
CameraMetadata.CONTROL_AWB_MODE_DAYLIGHT -> "Daylight"
CameraMetadata.CONTROL_AWB_MODE_CLOUDY_DAYLIGHT -> "Cloudy"
CameraMetadata.CONTROL_AWB_MODE_INCANDESCENT -> "Warm"
CameraMetadata.CONTROL_AWB_MODE_FLUORESCENT -> "Cool"
CameraMetadata.CONTROL_AWB_MODE_SHADE -> "Shade"
else -> "Unknown($mode)"
}
println("$name")
}
println("\n" + "=".repeat(50) + "\n")
}
}
}

View file

@ -0,0 +1,550 @@
package com.srtk.airlink
import android.annotation.SuppressLint
import android.content.Context
import android.hardware.camera2.*
import android.media.MediaCodec
import android.media.MediaCodecInfo
import android.media.MediaFormat
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import android.util.Range
import android.view.Surface
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import kotlin.math.abs
import kotlin.math.min
data class VideoConfig(val width: Int, val height: Int, val fps: Int) {
override fun toString() = "${height}p"
fun toDetailedString() = "${height}p (${width}×${height} @ ${fps}fps)"
}
data class CameraCapabilities(
val supportedConfigs: List<VideoConfig>,
val maxZoom: Float,
val hasFlash: Boolean,
val hasFrontCamera: Boolean,
val supportedWhiteBalance: List<WhiteBalance>,
val focusRange: Range<Float>?,
val exposureRange: Range<Int>?
)
enum class WhiteBalance(val value: Int, val label: String) {
AUTO(CameraMetadata.CONTROL_AWB_MODE_AUTO, "Auto"),
WARM(CameraMetadata.CONTROL_AWB_MODE_INCANDESCENT, "Warm"),
COOL(CameraMetadata.CONTROL_AWB_MODE_FLUORESCENT, "Cool")
}
class CameraStreamer(private val context: Context) {
private val TAG = "CameraStreamer"
private val manager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
private val cameraThread = HandlerThread("CamThread").apply { start() }
private val camHandler = Handler(cameraThread.looper)
private var cameraDevice: CameraDevice? = null
private var captureSession: CameraCaptureSession? = null
private var requestBuilder: CaptureRequest.Builder? = null
private var mediaCodec: MediaCodec? = null
private var socket: DatagramSocket? = null
@Volatile private var isStreaming = false
private val restartLock = Semaphore(1)
private var currentConfig = VideoConfig(960, 720, 30)
private var bitrate = 3000000
private var zoomRatio = 1f
private var flashMode = false
private var wbMode = CameraMetadata.CONTROL_AWB_MODE_AUTO
private var focusMode = CameraMetadata.CONTROL_AF_MODE_CONTINUOUS_VIDEO
private var focusDistance = 0f
private var exposureCompensation = 0
private var onErrorCallback: ((String) -> Unit)? = null
private var onDisconnectedCallback: (() -> Unit)? = null
private var lastPacketTime = 0L
private val connectionTimeout = 5000L // 5 seconds
fun setErrorCallback(callback: (String) -> Unit) {
onErrorCallback = callback
}
fun setDisconnectedCallback(callback: () -> Unit) {
onDisconnectedCallback = callback
}
// Test if a resolution actually works with the encoder
private fun testEncoderResolution(width: Int, height: Int): Boolean {
var testCodec: MediaCodec? = null
try {
val format = MediaFormat.createVideoFormat(
MediaFormat.MIMETYPE_VIDEO_AVC,
width,
height
).apply {
setInteger(
MediaFormat.KEY_COLOR_FORMAT,
MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface
)
setInteger(MediaFormat.KEY_BIT_RATE, 2000000)
setInteger(MediaFormat.KEY_FRAME_RATE, 30)
setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2)
}
testCodec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
testCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
testCodec.release()
Log.d(TAG, "✅ Resolution ${width}x${height} WORKS")
return true
} catch (e: Exception) {
Log.d(TAG, "❌ Resolution ${width}x${height} FAILED: ${e.message}")
return false
} finally {
try {
testCodec?.release()
} catch (e: Exception) {}
}
}
private fun is16by9(width: Int, height: Int): Boolean {
val ratio = width.toDouble() / height.toDouble()
return abs(ratio - 16.0 / 9.0) < 0.1
}
private fun is4by3(width: Int, height: Int): Boolean {
val ratio = width.toDouble() / height.toDouble()
return abs(ratio - 4.0 / 3.0) < 0.1
}
fun getCameraCapabilities(useFront: Boolean): CameraCapabilities {
val camId = getCameraId(useFront)
val chars = manager.getCameraCharacteristics(camId)
val map = chars.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)!!
val allSizes = map.getOutputSizes(MediaCodec::class.java)
.filter { is16by9(it.width, it.height) || is4by3(it.width, it.height) }
.sortedByDescending { it.width * it.height }
Log.d(TAG, "Testing encoder capabilities...")
val configs = mutableListOf<VideoConfig>()
val fpsRanges = chars.get(
CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES
) ?: emptyArray()
for (size in allSizes) {
try {
// TEST if encoder actually supports this resolution
if (!testEncoderResolution(size.width, size.height)) {
continue
}
val minFrameDuration = map.getOutputMinFrameDuration(
MediaCodec::class.java,
size
)
if (minFrameDuration <= 0) continue
val maxFpsFromDuration = (1_000_000_000.0 / minFrameDuration).toInt()
val validRanges = fpsRanges.filter {
it.upper <= maxFpsFromDuration && it.upper >= 15
}
val targetFps = min(validRanges.maxOfOrNull { it.upper } ?: 30, 30)
if (targetFps >= 15) {
configs.add(VideoConfig(size.width, size.height, targetFps))
}
} catch (e: Exception) {
Log.w(TAG, "Skipping ${size.width}x${size.height}: ${e.message}")
}
}
if (configs.isEmpty()) {
configs.add(VideoConfig(640, 480, 30))
Log.w(TAG, "No configs found, added 640x480 fallback")
}
val maxZoom = chars.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM) ?: 1f
val hasFlash = chars.get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true
val hasFront = manager.cameraIdList.any {
manager.getCameraCharacteristics(it).get(CameraCharacteristics.LENS_FACING) ==
CameraCharacteristics.LENS_FACING_FRONT
}
val minFocus = chars.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE)
val exposureRange = chars.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE)
return CameraCapabilities(
configs.sortedByDescending { it.width * it.height },
maxZoom,
hasFlash,
hasFront,
listOf(WhiteBalance.AUTO, WhiteBalance.WARM, WhiteBalance.COOL),
if (minFocus != null && minFocus > 0) Range(0f, minFocus) else null,
exposureRange
)
}
fun start(
ip: InetAddress,
port: Int,
config: VideoConfig,
useFront: Boolean
) {
currentConfig = config
val camId = getCameraId(useFront)
camHandler.post {
try {
if (restartLock.tryAcquire(3, TimeUnit.SECONDS)) {
try {
stopInternal()
Thread.sleep(500)
startInternal(ip, port, camId)
} finally {
restartLock.release()
}
}
} catch (e: Exception) {
Log.e(TAG, "Start error", e)
onErrorCallback?.invoke("Failed to start: ${e.message}")
}
}
}
fun updateBitrate(mbps: Int) {
val newBitrate = mbps * 1_000_000
if (bitrate == newBitrate) return
bitrate = newBitrate
camHandler.post {
try {
mediaCodec?.let { codec ->
val bundle = Bundle().apply {
putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, bitrate)
}
codec.setParameters(bundle)
Log.d(TAG, "Bitrate updated to ${mbps} Mbps")
}
} catch (e: Exception) {
Log.e(TAG, "Bitrate update failed", e)
}
}
}
fun setZoom(z: Float) {
zoomRatio = z
updateSession()
}
fun setTorch(on: Boolean) {
flashMode = on
updateSession()
}
fun setWhiteBalance(wb: WhiteBalance) {
wbMode = wb.value
updateSession()
}
fun setFocusMode(auto: Boolean) {
focusMode = if (auto) CameraMetadata.CONTROL_AF_MODE_CONTINUOUS_VIDEO
else CameraMetadata.CONTROL_AF_MODE_OFF
updateSession()
}
fun setFocusDistance(distance: Float) {
focusDistance = distance
focusMode = CameraMetadata.CONTROL_AF_MODE_OFF
updateSession()
}
fun setExposure(value: Int) {
exposureCompensation = value
updateSession()
}
@SuppressLint("MissingPermission")
private fun startInternal(
ip: InetAddress,
port: Int,
camId: String
) {
try {
socket = DatagramSocket()
isStreaming = true
lastPacketTime = System.currentTimeMillis()
val width = currentConfig.width
val height = currentConfig.height
val pixelCount = width * height
val calculatedBitrate = when {
pixelCount >= 1920 * 1080 -> 8_000_000
pixelCount >= 1280 * 720 -> 5_000_000
pixelCount >= 640 * 480 -> 2_500_000
else -> 1_500_000
}
Log.d(TAG, "Starting: ${width}x${height} @ ${currentConfig.fps}fps")
val format = MediaFormat.createVideoFormat(
MediaFormat.MIMETYPE_VIDEO_AVC,
width,
height
).apply {
setInteger(
MediaFormat.KEY_COLOR_FORMAT,
MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface
)
setInteger(MediaFormat.KEY_BIT_RATE, calculatedBitrate)
setInteger(MediaFormat.KEY_FRAME_RATE, currentConfig.fps)
setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2)
}
mediaCodec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
mediaCodec?.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
val surface = mediaCodec?.createInputSurface()
?: throw Exception("Failed to create input surface")
mediaCodec?.start()
Log.d(TAG, "✅ Encoder started with ${width}x${height}")
// Start connection monitor
Thread {
while (isStreaming) {
Thread.sleep(1000)
if (System.currentTimeMillis() - lastPacketTime > connectionTimeout) {
Log.w(TAG, "Server disconnected - no data sent")
stop()
onDisconnectedCallback?.invoke()
break
}
}
}.start()
Thread {
Thread.currentThread().priority = Thread.MAX_PRIORITY
streamLoop(ip, port)
}.start()
manager.openCamera(
camId,
object : CameraDevice.StateCallback() {
override fun onOpened(camera: CameraDevice) {
cameraDevice = camera
createSession(camera, surface)
}
override fun onDisconnected(camera: CameraDevice) {
Log.w(TAG, "Camera disconnected")
stopInternal()
}
override fun onError(camera: CameraDevice, error: Int) {
Log.e(TAG, "Camera error: $error")
stopInternal()
onErrorCallback?.invoke("Camera error: $error")
}
},
camHandler
)
} catch (e: Exception) {
Log.e(TAG, "Start failed: ${e.message}", e)
onErrorCallback?.invoke("Failed to start: ${e.message}")
stopInternal()
}
}
private fun createSession(camera: CameraDevice, surface: Surface) {
try {
camera.createCaptureSession(
listOf(surface),
object : CameraCaptureSession.StateCallback() {
override fun onConfigured(session: CameraCaptureSession) {
if (!isStreaming) return
captureSession = session
requestBuilder = camera.createCaptureRequest(
CameraDevice.TEMPLATE_RECORD
).apply {
addTarget(surface)
set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO)
set(CaptureRequest.CONTROL_AE_MODE, CameraMetadata.CONTROL_AE_MODE_ON)
set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,
Range(currentConfig.fps, currentConfig.fps))
set(CaptureRequest.CONTROL_AF_MODE, focusMode)
set(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE,
CameraMetadata.CONTROL_VIDEO_STABILIZATION_MODE_ON)
if (focusMode == CameraMetadata.CONTROL_AF_MODE_OFF) {
set(CaptureRequest.LENS_FOCUS_DISTANCE, focusDistance)
}
set(CaptureRequest.CONTROL_AE_EXPOSURE_COMPENSATION, exposureCompensation)
}
updateSession()
Log.d(TAG, "Camera session started")
}
override fun onConfigureFailed(session: CameraCaptureSession) {
Log.e(TAG, "Session config failed")
onErrorCallback?.invoke("Camera session failed")
}
},
camHandler
)
} catch (e: Exception) {
Log.e(TAG, "Create session error", e)
}
}
private fun updateSession() {
val builder = requestBuilder ?: return
val session = captureSession ?: return
try {
if (zoomRatio > 1f) {
builder.set(CaptureRequest.CONTROL_ZOOM_RATIO, zoomRatio)
}
builder.set(
CaptureRequest.FLASH_MODE,
if (flashMode) CameraMetadata.FLASH_MODE_TORCH
else CameraMetadata.FLASH_MODE_OFF
)
builder.set(CaptureRequest.CONTROL_AWB_MODE, wbMode)
builder.set(CaptureRequest.CONTROL_AF_MODE, focusMode)
if (focusMode == CameraMetadata.CONTROL_AF_MODE_OFF) {
builder.set(CaptureRequest.LENS_FOCUS_DISTANCE, focusDistance)
}
builder.set(CaptureRequest.CONTROL_AE_EXPOSURE_COMPENSATION, exposureCompensation)
session.setRepeatingRequest(builder.build(), null, camHandler)
} catch (e: Exception) {
Log.e(TAG, "Update session error", e)
}
}
private fun streamLoop(ip: InetAddress, port: Int) {
val bufferInfo = MediaCodec.BufferInfo()
val maxChunkSize = 1400
Log.d(TAG, "Stream loop started")
try {
while (isStreaming) {
val codec = mediaCodec ?: break
val index = codec.dequeueOutputBuffer(bufferInfo, 10000)
when (index) {
MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> {
val format = codec.outputFormat
Log.d(TAG, "Output format: $format")
}
in 0..Int.MAX_VALUE -> {
try {
if (bufferInfo.size <= 0) {
codec.releaseOutputBuffer(index, false)
continue
}
val buffer = codec.getOutputBuffer(index) ?: continue
buffer.position(bufferInfo.offset)
buffer.limit(bufferInfo.offset + bufferInfo.size)
val frameData = ByteArray(bufferInfo.size)
buffer.get(frameData)
var offset = 0
while (offset < frameData.size && isStreaming) {
val chunkSize = min(maxChunkSize, frameData.size - offset)
socket?.send(
DatagramPacket(frameData, offset, chunkSize, ip, port)
)
offset += chunkSize
}
lastPacketTime = System.currentTimeMillis()
codec.releaseOutputBuffer(index, false)
} catch (e: Exception) {
Log.e(TAG, "Buffer processing error", e)
}
}
}
}
} catch (e: Exception) {
Log.e(TAG, "Stream loop error", e)
}
Log.d(TAG, "Stream loop ended")
}
fun stop() {
camHandler.post { stopInternal() }
}
fun cleanup() {
stop()
cameraThread.quitSafely()
}
private fun stopInternal() {
isStreaming = false
try {
captureSession?.stopRepeating()
captureSession?.close()
captureSession = null
} catch (e: Exception) {
Log.e(TAG, "Session stop error", e)
}
try {
cameraDevice?.close()
cameraDevice = null
} catch (e: Exception) {
Log.e(TAG, "Camera close error", e)
}
try {
mediaCodec?.stop()
mediaCodec?.release()
mediaCodec = null
} catch (e: Exception) {
Log.e(TAG, "Codec stop error", e)
}
try {
socket?.close()
socket = null
} catch (e: Exception) {
Log.e(TAG, "Socket close error", e)
}
requestBuilder = null
}
private fun getCameraId(front: Boolean): String {
val target = if (front)
CameraCharacteristics.LENS_FACING_FRONT
else
CameraCharacteristics.LENS_FACING_BACK
return manager.cameraIdList.firstOrNull {
manager.getCameraCharacteristics(it)
.get(CameraCharacteristics.LENS_FACING) == target
} ?: manager.cameraIdList[0]
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,125 @@
package com.srtk.airlink
import android.content.Context
import android.net.nsd.NsdManager
import android.net.nsd.NsdServiceInfo
import android.util.Log
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import java.net.InetAddress
data class ServerInfo(
val name: String,
val ip: InetAddress,
val port: Int
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ServerInfo) return false
return ip == other.ip && port == other.port
}
override fun hashCode(): Int {
return 31 * ip.hashCode() + port
}
}
class DiscoveryManager(context: Context) {
private val TAG = "DiscoveryManager"
private val nsdManager = context.getSystemService(
Context.NSD_SERVICE
) as NsdManager
private val SERVICE_TYPE = "_procam._udp."
fun discover(): Flow<ServerInfo> = callbackFlow {
val discoveryListener = object : NsdManager.DiscoveryListener {
override fun onDiscoveryStarted(regType: String) {
Log.d(TAG, "Discovery started")
}
override fun onServiceFound(service: NsdServiceInfo) {
if (service.serviceType.contains("_procam")) {
try {
nsdManager.resolveService(
service,
object : NsdManager.ResolveListener {
override fun onResolveFailed(
serviceInfo: NsdServiceInfo,
errorCode: Int
) {
Log.w(TAG, "Resolve failed: $errorCode")
}
override fun onServiceResolved(
serviceInfo: NsdServiceInfo
) {
try {
val server = ServerInfo(
name = serviceInfo.serviceName,
ip = serviceInfo.host,
port = serviceInfo.port
)
trySend(server)
} catch (e: Exception) {
Log.e(
TAG,
"Error creating ServerInfo: ${e.message}"
)
}
}
}
)
} catch (e: Exception) {
Log.e(TAG, "Resolve error: ${e.message}")
}
}
}
override fun onServiceLost(service: NsdServiceInfo) {
Log.d(TAG, "Service lost: ${service.serviceName}")
}
override fun onDiscoveryStopped(serviceType: String) {
Log.d(TAG, "Discovery stopped")
}
override fun onStartDiscoveryFailed(
serviceType: String,
errorCode: Int
) {
Log.e(TAG, "Start discovery failed: $errorCode")
try {
nsdManager.stopServiceDiscovery(this)
} catch (e: Exception) {
Log.e(TAG, "Stop discovery error: ${e.message}")
}
}
override fun onStopDiscoveryFailed(
serviceType: String,
errorCode: Int
) {
Log.e(TAG, "Stop discovery failed: $errorCode")
}
}
try {
nsdManager.discoverServices(
SERVICE_TYPE,
NsdManager.PROTOCOL_DNS_SD,
discoveryListener
)
} catch (e: Exception) {
Log.e(TAG, "Discovery start error: ${e.message}")
}
awaitClose {
try {
nsdManager.stopServiceDiscovery(discoveryListener)
} catch (e: Exception) {
Log.e(TAG, "Discovery cleanup error: ${e.message}")
}
}
}
}

View file

@ -0,0 +1,11 @@
package com.srtk.airlink.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)

View file

@ -0,0 +1,57 @@
package com.srtk.airlink.ui.theme
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun WebcamTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}

View file

@ -0,0 +1,34 @@
package com.srtk.airlink.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)

View file

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-8"?>
<vector
android:height="108dp"
android:width="108dp"
android:viewportHeight="108"
android:viewportWidth="108"
xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z"/>
<path android:fillColor="#00000000" android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
</vector>

View file

@ -0,0 +1,30 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

View file

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>

View file

@ -0,0 +1,3 @@
<resources>
<string name="app_name">webcam</string>
</resources>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Webcam" parent="android:Theme.Material.Light.NoActionBar" />
</resources>

View file

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample backup rules file; uncomment and customize as necessary.
See https://developer.android.com/guide/topics/data/autobackup
for details.
Note: This file is ignored for devices older than API 31
See https://developer.android.com/about/versions/12/backup-restore
-->
<full-backup-content>
<!--
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="device.xml"/>
-->
</full-backup-content>

View file

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample data extraction rules file; uncomment and customize as necessary.
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
for details.
-->
<data-extraction-rules>
<cloud-backup>
<!-- TODO: Use <include> and <exclude> to control what is backed up.
<include .../>
<exclude .../>
-->
</cloud-backup>
<!--
<device-transfer>
<include .../>
<exclude .../>
</device-transfer>
-->
</data-extraction-rules>

View file

@ -0,0 +1,17 @@
package com.srtk.airlink
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}