diff --git a/src/call/call.c b/src/call/call.c index f270b17a0..6c8805a3d 100644 --- a/src/call/call.c +++ b/src/call/call.c @@ -209,7 +209,7 @@ static void call_event_incoming(struct call_ctx* ctx, uint64_t group_id, uint64_ uint8_t call_phone_status(struct UTUN_INSTANCE* inst) { if (!inst || !(inst->incoming_call_policy & CALL_POLICY_PUBLISH_PHONE)) return 0; if (inst->phone_state == 2 || call_busy(inst)) return TOPO_FLAG_PHONE_KNOWN | TOPO_FLAG_PHONE_BUSY; - return inst->phone_state == 1 ? TOPO_FLAG_PHONE_KNOWN : 0; + return inst->phone_state == 1 || inst->client_type == CLIENT_TYPE_DESKTOP ? TOPO_FLAG_PHONE_KNOWN : 0; } /* Меняются только live-флаги. Публикация использует существующее версионирование NODEINFO. */ @@ -222,7 +222,8 @@ static void call_publish_phone_status(struct UTUN_INSTANCE* inst) { DEBUG_ERROR(DEBUG_CATEGORY_CALL, "phone status publication failed group=%016llx flags=%u", (unsigned long long)g->group_id, status); continue; } - DEBUG_INFO(DEBUG_CATEGORY_BGP, "phone status group=%016llx flags=%u", (unsigned long long)g->group_id, status); + DEBUG_INFO(DEBUG_CATEGORY_BGP, "call status group=%016llx flags=%u os=%u app_busy=%d policy=%u", + (unsigned long long)g->group_id, status, inst->phone_state, call_busy(inst), inst->incoming_call_policy); for (struct topo_node_cbk_entry* cb = g->node_cbks; cb; cb = cb->next) cb->fn(g, inst->node_id, TOPO_NODE_EVENT_UPDATE, cb->arg); for (struct ll_entry* p = g->senders_list ? g->senders_list->head : NULL; p; p = p->next) { @@ -237,7 +238,8 @@ void call_set_phone_state(struct UTUN_INSTANCE* inst, int state, unsigned policy DEBUG_ERROR(DEBUG_CATEGORY_CALL, "invalid phone state=%d policy=%u", state, policy); return; } if (inst->phone_state == state && inst->incoming_call_policy == policy) return; - DEBUG_INFO(DEBUG_CATEGORY_CALL, "phone state old=%u new=%d policy=%u", inst->phone_state, state, policy); + DEBUG_INFO(DEBUG_CATEGORY_CALL, "phone state old=%u new=%d policy=%u->%u", + inst->phone_state, state, inst->incoming_call_policy, policy); inst->phone_state = (uint8_t)state; inst->incoming_call_policy = (uint8_t)policy; call_publish_phone_status(inst); @@ -918,6 +920,7 @@ int call_init(struct UTUN_INSTANCE* inst) { DEBUG_ERROR(DEBUG_CATEGORY_CALL, "call media channel bind failed"); call_destroy(inst); return -1; } + call_publish_phone_status(inst); DEBUG_INFO(DEBUG_CATEGORY_CALL, "%s: initialized (svc=0x%02x)", CALL_ID, ETCP_RT_ID_CALL); return 0; } diff --git a/src/call/call.h b/src/call/call.h index d3f52deec..a1b37e035 100644 --- a/src/call/call.h +++ b/src/call/call.h @@ -47,7 +47,8 @@ enum call_policy { /* Живое состояние ОС: 0=неизвестно, 1=свободен, 2=занят; policy — маска call_policy. * Только uasync. Изменение статуса публикуется в BGP, если включён PUBLISH_PHONE. */ void call_set_phone_state(struct UTUN_INSTANCE* inst, int state, unsigned policy); -/* Флаги BGP PHONE_KNOWN/BUSY с учётом собственного обычного звонка. Только uasync. */ +/* Флаги BGP PHONE_KNOWN/BUSY с учётом звонка приложения и разрешения публикации. + * Desktop без звонка свободен; у mobile состояние ОС может быть неизвестно. Только uasync. */ uint8_t call_phone_status(struct UTUN_INSTANCE* inst); /* Read-only онлайн-проверка (GUI может звать из любого потока). */ diff --git a/src/chat/chat_setting.c b/src/chat/chat_setting.c index 64b5dbd7e..19da7b74b 100644 --- a/src/chat/chat_setting.c +++ b/src/chat/chat_setting.c @@ -7,6 +7,7 @@ #include "chat_setting.h" #include "chat_local.h" +#include "../call/call.h" #include "../call/call_video_rate.h" #include "../utun_instance.h" #include "../../lib/debug_config.h" @@ -67,7 +68,7 @@ static const struct chat_setting_def g_setting_defs[] = { {"group_autoconnect", CHAT_SETTING_BOOL, 1, 0, 1}, {"aec_enabled", CHAT_SETTING_BOOL, 1, 0, 1}, /* AEC (SpeexDSP) в звонке, desktop GUI */ {"call_jitter_max_reserve_ms", CHAT_SETTING_INT, 1000, 500, 2000}, - {"incoming_call_policy", CHAT_SETTING_INT, 1, 0, 31}, /* CALL_POLICY_*; применяется при старте и обновлении статуса ОС */ + {"incoming_call_policy", CHAT_SETTING_INT, 1, 0, 31}, /* CALL_POLICY_*; публикация по умолчанию разрешена */ {"call_video_bitrate_range_kbps", CHAT_SETTING_STRING, 0, 0, 0}, {"call_compressor_enabled", CHAT_SETTING_BOOL, 1, 0, 1}, {"call_compressor_max_gain_db",CHAT_SETTING_INT, 15, 1, 60}, @@ -209,6 +210,8 @@ int chat_setting_set(struct UTUN_INSTANCE* inst, const char* name, const char* v struct chat_setting_state* s = cs_state(inst); if (!s) return -2; int result = chat_setting_set_state(s, name, value); + if (!result && !strcmp(name, "incoming_call_policy")) + call_set_phone_state(inst, inst->phone_state, (unsigned)chat_setting_get_int(inst, name, CALL_POLICY_PUBLISH_PHONE)); if (!result && (!strcmp(name, "local_invites_enabled") || !strcmp(name, "local_broadcasts_enabled"))) return chat_local_apply_settings(inst); return result; diff --git a/tests/test_call.c b/tests/test_call.c index 2658922a8..74e264798 100644 --- a/tests/test_call.c +++ b/tests/test_call.c @@ -62,6 +62,7 @@ enum call_phase { P_WAIT_CONN, P_SETUP, P_WAIT_BGP, + P_STATUS_IDLE, P_STATUS_HIDE, P_STATUS_RESTORE, P_STATUS_RESTORED, P_STATUS_ENDED, P_CALL1_START, /* A: call_start */ P_WAIT_INCOMING1, /* B: INCOMING */ P_ACCEPT, /* B: call_accept */ @@ -461,6 +462,16 @@ static int test_pm_route(struct UTUN_INSTANCE* inst, uint64_t peer, char target[ /* ── master state-machine ── */ +/* Проверяем вычисленный статус, локальный NODEINFO и доставленную BGP-копию у другого узла. */ +static int published_status_matches(struct UTUN_INSTANCE* sender, struct UTUN_INSTANCE* receiver, uint8_t expected) { + uint64_t group_id = strtoull(CH_ID, NULL, 10); + struct TOPO_GROUP* local = topo_groups_find(sender->topo_groups, group_id); + struct TOPO_GROUP* remote = topo_groups_find(receiver->topo_groups, group_id); + struct TOPO_GROUP_NODE* node = remote ? topo_node_find_by_id(remote, sender->node_id) : NULL; + return call_phone_status(sender) == expected && local && local->local_node && local->local_node->phone_status == expected + && node && node->phone_status == expected; +} + static void call_tick(void* arg) { struct call_test_ctx* t = arg; t->timer = NULL; @@ -482,7 +493,15 @@ static void call_tick(void* arg) { t->phase = P_WAIT_BGP; break; case P_WAIT_BGP: - if (bgp_has(A, nb) && bgp_has(B, na)) t->phase = P_CALL1_START; + if (bgp_has(A, nb) && bgp_has(B, na)) t->phase = P_STATUS_IDLE; + break; + case P_STATUS_IDLE: + if (!published_status_matches(A, B, TOPO_FLAG_PHONE_KNOWN)) break; + if (A->phone_state || call_phone_status(B)) { + DEBUG_ERROR(DEBUG_CATEGORY_CALL, "desktop idle status changed OS state or unknown phone status"); t->result = 2; break; + } + DEBUG_INFO(DEBUG_CATEGORY_CALL, "desktop call status: idle published by default without OS phone state"); + t->phase = P_CALL1_START; break; case P_CALL1_START: { memset(ea, 0, sizeof(*ea)); @@ -500,11 +519,35 @@ static void call_tick(void* arg) { if (eb->incoming && eb->incoming_call_id == t->call_id) t->phase = P_ACCEPT; break; case P_ACCEPT: + if (!published_status_matches(A, B, TOPO_FLAG_PHONE_KNOWN | TOPO_FLAG_PHONE_BUSY) + || !published_status_matches(B, A, TOPO_FLAG_PHONE_KNOWN | TOPO_FLAG_PHONE_BUSY)) break; call_accept(B, t->call_id); t->phase = P_WAIT_ACCEPTED; break; case P_WAIT_ACCEPTED: - if (ea->accepted && eb->accepted && ea->accepted_call_id == t->call_id) t->phase = P_SEND_MEDIA; + if (ea->accepted && eb->accepted && ea->accepted_call_id == t->call_id) t->phase = P_STATUS_HIDE; + break; + case P_STATUS_HIDE: + if (!published_status_matches(A, B, TOPO_FLAG_PHONE_KNOWN | TOPO_FLAG_PHONE_BUSY)) break; + if (chat_setting_set(A, "incoming_call_policy", "16")) { t->result = 2; break; } + t->phase = P_STATUS_RESTORE; + break; + case P_STATUS_RESTORE: + if (!published_status_matches(A, B, 0)) break; + if (!call_busy(A) || A->phone_state || A->incoming_call_policy != CALL_POLICY_BLOCK_RADIO) { + DEBUG_ERROR(DEBUG_CATEGORY_CALL, "desktop status disable changed call/OS state or unrelated policy"); t->result = 2; break; + } + if (chat_setting_set(A, "incoming_call_policy", "17")) { t->result = 2; break; } + t->phase = P_STATUS_RESTORED; + break; + case P_STATUS_RESTORED: + if (!published_status_matches(A, B, TOPO_FLAG_PHONE_KNOWN | TOPO_FLAG_PHONE_BUSY)) break; + if (A->phone_state || A->incoming_call_policy != (CALL_POLICY_BLOCK_RADIO | CALL_POLICY_PUBLISH_PHONE)) { + DEBUG_ERROR(DEBUG_CATEGORY_CALL, "desktop status enable changed OS state or unrelated policy"); t->result = 2; break; + } + if (chat_setting_set(A, "incoming_call_policy", "1")) { t->result = 2; break; } + DEBUG_INFO(DEBUG_CATEGORY_CALL, "desktop call status: outgoing/incoming busy, runtime hide/restore delivered over BGP"); + t->phase = P_SEND_MEDIA; break; case P_SEND_MEDIA: { // Потеря CM-пути не завершает звонок; роутер продолжает доставку. @@ -769,9 +812,14 @@ static void call_tick(void* arg) { ea->ended_reason, eb->ended_reason); t->result = 2; break; } - t->phase = P_CALL2_START; + t->phase = P_STATUS_ENDED; } break; + case P_STATUS_ENDED: + if (!published_status_matches(A, B, TOPO_FLAG_PHONE_KNOWN) || !published_status_matches(B, A, 0)) break; + DEBUG_INFO(DEBUG_CATEGORY_CALL, "desktop call status: hangup publishes free, unknown phone remains unknown"); + t->phase = P_CALL2_START; + break; case P_CALL2_START: { memset(ea, 0, sizeof(*ea)); memset(eb, 0, sizeof(*eb)); @@ -1000,6 +1048,7 @@ int main(int argc, char** argv) { return 1; } test_etcp_set_peer(t.inst[IDX_B], "to_a", t.inst[IDX_A], "s1"); + t.inst[IDX_A]->config->global.client_type = CLIENT_TYPE_DESKTOP; utun_instance_init(t.inst[IDX_A]); utun_instance_init(t.inst[IDX_B]); diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/ConfigProvider.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/ConfigProvider.kt index bb675b92c..ed9074c14 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/ConfigProvider.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/ConfigProvider.kt @@ -191,7 +191,7 @@ class ConfigProvider(private val context: Context) { suspend fun getStreamCaptureSettings(): StreamCaptureSettings { val prefs = context.dataStore.data.first() return StreamCaptureSettings(prefs[streamCamera] ?: "", prefs[streamWidth] ?: 1280, prefs[streamHeight] ?: 720, - prefs[streamFps] ?: 30, prefs[streamCodec] ?: StreamVideoCodec.H264.id, prefs[streamRotation] ?: StreamOrientation.LEFT.degrees, + prefs[streamFps] ?: 30, prefs[streamCodec] ?: StreamVideoCodec.H264.id, prefs[streamRotation] ?: StreamOrientation.AUTO.degrees, prefs[streamBitrate], prefs[streamAudio] ?: true) } diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureConfig.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureConfig.kt index 356ce09b6..11ebc468e 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureConfig.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureConfig.kt @@ -1,14 +1,18 @@ package com.utun.chat.data -/** Ручной поворот относительно обычного положения устройства; фронтальный сенсор учитывается отдельно. */ +/** AUTO следует датчику положения, остальные углы задаются вручную относительно обычного положения устройства. */ enum class StreamOrientation(val degrees: Int) { - UPRIGHT(0), RIGHT(90), UPSIDE_DOWN(180), LEFT(270); + // -1 хранится только в настройках; в видео передаётся вычисленный угол 0/90/180/270. + AUTO(-1), UPRIGHT(0), RIGHT(90), UPSIDE_DOWN(180), LEFT(270); - fun sensorRotation(sensor: Int, front: Boolean): Int = (sensor + (if (front) degrees else -degrees) + 360) % 360 + fun sensorRotation(sensor: Int, front: Boolean, deviceDegrees: Int = 0): Int { + val turn = if (this == AUTO) (360 - deviceDegrees) % 360 else degrees + return (sensor + (if (front) turn else -turn) + 360) % 360 + } } /** Режим камеры и ориентация подтверждаются и восстанавливаются одним значением. */ -data class StreamCaptureConfig(val mode: StreamCaptureMode, val orientation: StreamOrientation = StreamOrientation.LEFT, +data class StreamCaptureConfig(val mode: StreamCaptureMode, val orientation: StreamOrientation = StreamOrientation.AUTO, val videoBitrate: Int? = null) { val bitrate get() = videoBitrate ?: mode.bitrate init { require(bitrate in mode.minimumBitrate..mode.maximumBitrate) } diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureEngine.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureEngine.kt index 556f36d9e..14d87524f 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureEngine.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureEngine.kt @@ -18,7 +18,9 @@ import android.os.Build import android.os.Bundle import android.os.Handler import android.os.HandlerThread +import android.os.SystemClock import android.util.Range +import android.view.OrientationEventListener import android.view.Surface import java.io.ByteArrayOutputStream @@ -54,6 +56,17 @@ class StreamCaptureEngine( private var openingGeneration = 0L private var releaseDone: ((Boolean) -> Unit)? = null private var generation = 0L + private var videoRevision = 0L + private var videoRotation = 0 + private val orientation = CallVideoOrientation() + private var orientationEnabled = false + private val orientationListener = object : OrientationEventListener(context) { + override fun onOrientationChanged(angle: Int) { + if (!handler.post { + if (orientationEnabled && orientation.observe(angle, SystemClock.elapsedRealtime())) logOrientation() + }) LogManager.addLog("WARN", "video", "stream orientation after capture worker stopped id=$id") + } + } private var lastGood: StreamCaptureConfig? = null private var reverting = false private var waitingFirst = true @@ -78,6 +91,19 @@ class StreamCaptureEngine( private var reportBytes = 0L private var lastPts = -1L + private fun logOrientation() { + LogManager.addLog("INFO", "video", "stream device orientation id=$id degrees=${orientation.degrees} mode=${activeConfig?.orientation}") + } + + private fun observeOrientation(enabled: Boolean) { + if (orientationEnabled == enabled) return + orientationEnabled = enabled; orientation.resetPending() + if (!enabled) orientationListener.disable() + else if (orientationListener.canDetectOrientation()) orientationListener.enable() + else LogManager.addLog("WARN", "video", "stream orientation sensor unavailable id=$id; using ${orientation.degrees}") + LogManager.addLog("DEBUG", "video", "stream orientation monitoring id=$id enabled=$enabled") + } + fun start() { preview.bind { target -> if (!handler.post { @@ -86,7 +112,7 @@ class StreamCaptureEngine( val previous = previewTarget; previewTarget = target; previous?.release() val config = activeConfig; val device = camera LogManager.addLog("DEBUG", "video", "preview output change id=$id target=${target?.let(System::identityHashCode)} " + - "revision=$generation camera=${device != null} opening=$opening") + "generation=$generation camera=${device != null} opening=$opening") if (device != null && config != null && current(generation)) createSession(device, config, generation) }) { LogManager.addLog("WARN", "video", "preview command rejected id=$id capture handler stopped") @@ -97,7 +123,8 @@ class StreamCaptureEngine( if (stopping || stopped) return@post try { val mode = initialConfig.mode - val rotation = cameraPose(mode.camera).rotation(initialConfig.orientation.degrees) + val pose = cameraPose(mode.camera) + val rotation = initialConfig.orientation.sensorRotation(pose.sensor, pose.front, orientation.degrees) check(NativeLib.streamOpen(id, group, width = mode.width, height = mode.height, rotation = rotation, audio = microphone, videoCodec = mode.videoCodec.id)) { "Publisher open rejected" } originNs = System.nanoTime() @@ -118,14 +145,14 @@ class StreamCaptureEngine( try { encoder!!.setParameters(Bundle().apply { putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, config.bitrate) }) lastGood = config; activeConfig = config; ready(config, false) - LogManager.addLog("INFO", "video", "bitrate changed id=$id revision=$generation ${previous.bitrate}->${config.bitrate}") + LogManager.addLog("INFO", "video", "bitrate changed id=$id revision=$videoRevision ${previous.bitrate}->${config.bitrate}") return@post } catch (e: Exception) { LogManager.addLog("WARN", "video", "live bitrate refused id=$id target=${config.bitrate}; reconfigure: ${e.message}") } } waitingFirst = true; reverting = false; switchStartedNs = System.nanoTime() - LogManager.addLog("INFO", "video", "switch capture id=$id camera=${config.mode.camera} ${config.mode.label} orientation=${config.orientation.degrees}") + LogManager.addLog("INFO", "video", "switch capture id=$id camera=${config.mode.camera} ${config.mode.label} orientation=${config.orientation}") releaseVideo { closed -> if (closed) configure(config) else failed("camera close timed out during switch") } } } @@ -142,13 +169,14 @@ class StreamCaptureEngine( val mode = config.mode val token = ++generation try { - check(token <= 0xffffffffL) { "Video revision exhausted" } + check(++videoRevision <= 0xffffffffL) { "Video revision exhausted" } val cameraPose = cameraPose(mode.camera) - val rotation = cameraPose.rotation(config.orientation.degrees) + videoRotation = config.orientation.sensorRotation(cameraPose.sensor, cameraPose.front, orientation.degrees) activeConfig = config + observeOrientation(config.orientation == StreamOrientation.AUTO) preview.update(null) - LogManager.addLog("DEBUG", "video", "capture camera id=$id revision=$token camera=${mode.camera} " + - "sensor=${cameraPose.sensor} front=${cameraPose.front} broadcastRotation=$rotation") + LogManager.addLog("DEBUG", "video", "capture camera id=$id revision=$videoRevision generation=$token camera=${mode.camera} " + + "sensor=${cameraPose.sensor} front=${cameraPose.front} orientation=${config.orientation} broadcastRotation=$videoRotation") csd = byteArrayOf(); partial.reset(); partialConfig.reset(); requireKey = true; lastKeyRequest = 0; waitingFirst = true confirming = mode.highSpeed; confirmStartNs = 0 reportNs = System.nanoTime(); reportFrames = encodedFrames; reportBytes = bytesSent @@ -172,7 +200,7 @@ class StreamCaptureEngine( ByteArray(b.remaining()).also { b.get(it) }.let(mode.videoCodec::normalize) } }.fold(byteArrayOf()) { a, b -> a + b } check(csd.size <= StreamVideoCodec.MAX_CONFIG) { "Codec configuration too large" } - LogManager.addLog("INFO", "video", "encoder format id=$id revision=$token codec=${codec.name} csd=${csd.size} format=$format") + LogManager.addLog("INFO", "video", "encoder format id=$id generation=$token codec=${codec.name} csd=${csd.size} format=$format") } catch (e: Exception) { captureError(token, "encoder format: ${e.message}") } } override fun onOutputBufferAvailable(codec: MediaCodec, index: Int, info: MediaCodec.BufferInfo) { @@ -189,7 +217,7 @@ class StreamCaptureEngine( if (info.flags and MediaCodec.BUFFER_FLAG_PARTIAL_FRAME == 0) { csd = mode.videoCodec.mergeConfig(csd, partialConfig.toByteArray()); partialConfig.reset() } - } else encoded(bytes, info, config, rotation, token) + } else encoded(bytes, info, config, cameraPose, token) } if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) problem = "unexpected encoder EOS" } catch (e: Exception) { problem = "encoded frame: ${e.message}" } @@ -214,7 +242,7 @@ class StreamCaptureEngine( override fun onClosed(device: CameraDevice) { if (camera === device) camera = null val pending = cameraSessions.values.filter { it.first === device }.map { it.second } - LogManager.addLog("DEBUG", "video", "camera closed id=$id revision=$token retiringSessions=${pending.size}") + LogManager.addLog("DEBUG", "video", "camera closed id=$id generation=$token retiringSessions=${pending.size}") pending.forEach { it("cameraClosed") } if (releaseDone != null && camera == null && !opening) finishRelease(true) maybeQuit() @@ -292,7 +320,7 @@ class StreamCaptureEngine( val now = System.nanoTime() if (now - sensorReportNs < 1_000_000_000) return val fps = (sensorResults - sensorReportCount) * 1_000_000_000.0 / (now - sensorReportNs) - LogManager.addLog("DEBUG", "video", "sensor id=$id revision=$token session=$serial results=$sensorResults " + + LogManager.addLog("DEBUG", "video", "sensor id=$id generation=$token session=$serial results=$sensorResults " + "callbackFps=${"%.1f".format(fps)} range=${result.get(CaptureResult.CONTROL_AE_TARGET_FPS_RANGE)} " + "durationNs=${result.get(CaptureResult.SENSOR_FRAME_DURATION)} " + "exposureNs=${result.get(CaptureResult.SENSOR_EXPOSURE_TIME)} timestamp=${result.get(CaptureResult.SENSOR_TIMESTAMP)}") @@ -300,7 +328,7 @@ class StreamCaptureEngine( } override fun onCaptureFailed(session: CameraCaptureSession, request: CaptureRequest, failed: android.hardware.camera2.CaptureFailure) { - if (valid()) LogManager.addLog("WARN", "video", "sensor capture failed id=$id revision=$token " + + if (valid()) LogManager.addLog("WARN", "video", "sensor capture failed id=$id generation=$token " + "session=$serial frame=${failed.frameNumber} reason=${failed.reason} captured=${failed.wasImageCaptured()}") } } @@ -309,7 +337,7 @@ class StreamCaptureEngine( highSpeed.setRepeatingBurst(highSpeed.createHighSpeedRequestList(request), diagnostics, handler) } else configured.setRepeatingRequest(request, diagnostics, handler) if (output != null) preview.update(format, active = true) - LogManager.addLog("INFO", "video", "capture started id=$id revision=$token session=$serial camera=${mode.camera} ${mode.label} " + + LogManager.addLog("INFO", "video", "capture started id=$id generation=$token session=$serial camera=${mode.camera} ${mode.label} " + "range=${mode.minimumFps}..${mode.fps} highSpeed=${mode.highSpeed} encoder=${encoder?.name} " + "preview=${output != null} previewSize=${format?.let { "${it.width}x${it.height}" }} origin=$originNs") } catch (e: Exception) { configured.close(); rejected("camera request: ${e.message}") } @@ -322,7 +350,7 @@ class StreamCaptureEngine( complete("sessionClosed") } } - LogManager.addLog("DEBUG", "video", "camera session configuring id=$id revision=$token session=$serial outputs=${targets.size}") + LogManager.addLog("DEBUG", "video", "camera session configuring id=$id generation=$token session=$serial outputs=${targets.size}") if (mode.highSpeed) device.createConstrainedHighSpeedCaptureSession(targets, callback, handler) else device.createCaptureSession(targets, callback, handler) } catch (e: Exception) { complete("exception"); rejected("camera session: ${e.message}") } @@ -336,16 +364,16 @@ class StreamCaptureEngine( } private fun captureError(token: Long, detail: String) { - if (!current(token)) { LogManager.addLog("DEBUG", "video", "stale capture error revision=$token: $detail"); return } - LogManager.addLog("ERROR", "video", "capture error id=$id revision=$token: $detail") + if (!current(token)) { LogManager.addLog("DEBUG", "video", "stale capture error generation=$token: $detail"); return } + LogManager.addLog("ERROR", "video", "capture error id=$id generation=$token: $detail") val previous = lastGood if (previous == null || reverting) { failed(detail); return } waitingFirst = true; reverting = true - LogManager.addLog("WARN", "video", "restoring camera=${previous.mode.camera} ${previous.mode.label} orientation=${previous.orientation.degrees} id=$id") + LogManager.addLog("WARN", "video", "restoring camera=${previous.mode.camera} ${previous.mode.label} orientation=${previous.orientation} id=$id") releaseVideo { closed -> if (closed) configure(previous) else failed("camera close timed out during restore") } } - private fun encoded(bytes: ByteArray, info: MediaCodec.BufferInfo, config: StreamCaptureConfig, rotation: Int, revision: Long) { + private fun encoded(bytes: ByteArray, info: MediaCodec.BufferInfo, config: StreamCaptureConfig, pose: StreamPreviewCamera, token: Long) { val mode = config.mode if (partial.size() == 0) { partialPts = info.presentationTimeUs; partialKey = false } check(info.presentationTimeUs == partialPts) { "Partial video frame PTS changed" } @@ -357,17 +385,28 @@ class StreamCaptureEngine( val pts = partialPts - originNs / 1000 check(pts >= 0 && pts > lastPts) { "Video PTS outside timeline pts=$pts last=$lastPts" } lastPts = pts; encodedFrames++ + if (orientationEnabled && orientation.confirm(SystemClock.elapsedRealtime())) logOrientation() + val rotation = config.orientation.sensorRotation(pose.sensor, pose.front, orientation.degrees) + // Новый угол передаём с KEY и отдельной revision, не перезапуская камеру и микрофон. + if (rotation != videoRotation) { + if (key) { + check(++videoRevision <= 0xffffffffL) { "Video revision exhausted" } + LogManager.addLog("INFO", "video", "stream rotation id=$id revision=$videoRevision device=${orientation.degrees} " + + "sensor=${pose.sensor} front=${pose.front} rotation=$videoRotation->$rotation pts=$pts") + videoRotation = rotation + } else requestKey() + } if (requireKey && !key) { dropped++; requestKey() } else { val output = if (key) mode.videoCodec.keyFrame(data, csd) else data if (key) mode.videoCodec.unpackKey(output) - when (NativeLib.streamFeed(id, true, pts, key, output, revision, mode.width, mode.height, rotation, microphone, mode.videoCodec.id)) { + when (NativeLib.streamFeed(id, true, pts, key, output, videoRevision, mode.width, mode.height, videoRotation, microphone, mode.videoCodec.id)) { 1 -> { requireKey = false; frames++; bytesSent += output.size if (waitingFirst) { check(key); waitingFirst = false confirmStartNs = System.nanoTime(); confirmFrames = encodedFrames - if (!confirming) confirmed(config, revision, pts) + if (!confirming) confirmed(config, videoRevision, pts) } } 0 -> { dropped++; requireKey = true; requestKey() } @@ -378,14 +417,14 @@ class StreamCaptureEngine( if (confirming && confirmStartNs != 0L && now - confirmStartNs >= 3_000_000_000) { val actualFps = (encodedFrames - confirmFrames) * 1_000_000_000.0 / (now - confirmStartNs) if (actualFps < mode.fps * 0.8) { - captureError(revision, "high speed rate insufficient: camera=${mode.camera} target=${mode.fps} actual=${"%.1f".format(actualFps)} fps") + captureError(token, "high speed rate insufficient: camera=${mode.camera} target=${mode.fps} actual=${"%.1f".format(actualFps)} fps") return } - confirmed(config, revision, pts) + confirmed(config, videoRevision, pts) } if (now - reportNs >= 1_000_000_000) { val seconds = (now - reportNs) / 1_000_000_000.0 - LogManager.addLog("DEBUG", "video", "capture id=$id revision=$revision targetFps=${mode.fps} " + + LogManager.addLog("DEBUG", "video", "capture id=$id revision=$videoRevision targetFps=${mode.fps} " + "fps=${"%.1f".format((encodedFrames - reportFrames) / seconds)} bitrate=${((bytesSent - reportBytes) * 8 / seconds).toLong()} " + "frames=$frames dropped=$dropped pts=$pts waitingKey=$requireKey") reportNs = now; reportFrames = encodedFrames; reportBytes = bytesSent @@ -397,7 +436,7 @@ class StreamCaptureEngine( val mode = config.mode confirming = false; lastGood = config LogManager.addLog("INFO", "video", "capture ready id=$id revision=$revision camera=${mode.camera} ${mode.label} " + - "orientation=${config.orientation.degrees} switchMs=${(System.nanoTime() - switchStartedNs) / 1_000_000} restored=$reverting pts=$pts") + "orientation=${config.orientation} rotation=$videoRotation switchMs=${(System.nanoTime() - switchStartedNs) / 1_000_000} restored=$reverting pts=$pts") ready(config, reverting); reverting = false; switchStartedNs = 0 } @@ -406,7 +445,7 @@ class StreamCaptureEngine( if (now - lastKeyRequest < 500_000_000) return lastKeyRequest = now encoder?.setParameters(Bundle().apply { putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0) }) - LogManager.addLog("INFO", "video", "requested video keyframe id=$id encoder=${encoder?.name} revision=$generation") + LogManager.addLog("INFO", "video", "requested video keyframe id=$id encoder=${encoder?.name} revision=$videoRevision") } /** Новая камера открывается только после onClosed; старые codec callbacks уже отсечены. */ @@ -432,7 +471,7 @@ class StreamCaptureEngine( try { encoder?.stop() } catch (e: Exception) { LogManager.addLog("WARN", "video", "encoder stop id=$id: ${e.message}") } try { encoder?.release() } catch (e: Exception) { LogManager.addLog("WARN", "video", "encoder release id=$id: ${e.message}") } encoder = null; input?.release(); input = null; partial.reset(); partialConfig.reset(); csd = byteArrayOf(); releaseDone = null - LogManager.addLog("DEBUG", "video", "video resources released id=$id closed=$closed revision=$generation") + LogManager.addLog("DEBUG", "video", "video resources released id=$id closed=$closed generation=$generation") done(closed) } /** Меняем только свою копию PCM; общий микрофон и рация продолжают работать. */ @@ -492,6 +531,7 @@ class StreamCaptureEngine( private fun failed(detail: String) { if (stopping || stopped || terminalFailure) return terminalFailure = true + observeOrientation(false) LogManager.addLog("ERROR", "stream", "capture failed id=$id $detail") failure(detail) } @@ -504,6 +544,7 @@ class StreamCaptureEngine( stopCallbacks.add(done) if (stopping) return@post stopping = true; audioRunning = false + observeOrientation(false) preview.close(); previewTarget?.release(); previewTarget = null audioCapture?.close(); audioCapture = null audioThread?.join(); audioThread = null diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureSettings.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureSettings.kt index 8799c52b0..f82812168 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureSettings.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureSettings.kt @@ -2,7 +2,7 @@ package com.utun.chat.data /** Последний выбор пользователя; возможности encoder заново берём у устройства. */ data class StreamCaptureSettings(val camera: String = "", val width: Int = 1280, val height: Int = 720, val fps: Int = 30, - val codec: Int = StreamVideoCodec.H264.id, val rotation: Int = StreamOrientation.LEFT.degrees, + val codec: Int = StreamVideoCodec.H264.id, val rotation: Int = StreamOrientation.AUTO.degrees, val bitrate: Int? = null, val audio: Boolean = true) { fun resolve(cameras: List): StreamCaptureConfig? { val selected = cameras.firstOrNull { it.id == camera } @@ -17,7 +17,7 @@ data class StreamCaptureSettings(val camera: String = "", val width: Int = 1280, if (mode == null) { LogManager.addLog("WARN", "stream", "capture settings: camera=${selected.id} has no available mode"); return null } - val orientation = StreamOrientation.values().firstOrNull { it.degrees == rotation } ?: StreamOrientation.LEFT + val orientation = StreamOrientation.values().firstOrNull { it.degrees == rotation } ?: StreamOrientation.AUTO val restored = StreamCaptureConfig(mode, orientation, bitrate?.takeUnless { mode.manualBitrateRange.isEmpty() }?.coerceIn(mode.manualBitrateRange)) if (camera.isNotEmpty() && (camera != mode.camera || width != mode.width || height != mode.height || fps != mode.fps || diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/StreamScreen.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/StreamScreen.kt index e2457119e..1d2ddb5b3 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/StreamScreen.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/StreamScreen.kt @@ -24,6 +24,7 @@ import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.automirrored.filled.VolumeOff import androidx.compose.material.icons.automirrored.filled.VolumeUp import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.filled.ScreenRotation import androidx.compose.material.icons.filled.Stop import androidx.compose.material3.* import androidx.compose.runtime.* @@ -323,12 +324,19 @@ private fun StreamCaptureToolbar(cameras: List, config: StreamCapt } } Box { - val degrees = config?.orientation?.degrees ?: 0 + val auto = config?.orientation == StreamOrientation.AUTO + val degrees = config?.orientation?.degrees?.takeIf { it >= 0 } ?: 0 val front = camera?.lens?.type == LensType.SELFIE val top = if (front) (display - degrees + 360) % 360 else (degrees - display + 360) % 360 - CaptureControlButton(stringResource(R.string.stream_orientation, degrees), enabled && config != null, - onClick = { menu = StreamOption.ORIENTATION }) { StreamRotationMark(top, degrees) } + val label = if (auto) stringResource(R.string.stream_orientation_auto) else stringResource(R.string.stream_orientation, degrees) + CaptureControlButton(label, enabled && config != null, onClick = { menu = StreamOption.ORIENTATION }) { + if (auto) Icon(Icons.Filled.ScreenRotation, contentDescription = null, modifier = Modifier.size(32.dp)) + else StreamRotationMark(top, degrees) + } DropdownMenu(expanded = menu == StreamOption.ORIENTATION && enabled, onDismissRequest = { menu = null }) { + CaptureOptionItem(stringResource(R.string.stream_orientation_auto), auto, + onClick = { menu = null; config?.let { onChange(it.copy(orientation = StreamOrientation.AUTO)) } }, + icon = { Icon(Icons.Filled.ScreenRotation, contentDescription = null, modifier = Modifier.size(32.dp)) }) for (option in listOf(StreamOrientation.UPRIGHT, StreamOrientation.RIGHT, StreamOrientation.LEFT)) { val optionTop = if (front) (display - option.degrees + 360) % 360 else (option.degrees - display + 360) % 360 CaptureOptionItem(stringResource(R.string.stream_orientation, option.degrees), config?.orientation == option, diff --git a/tools/chatgui-android/app/src/main/res/values-ru/strings.xml b/tools/chatgui-android/app/src/main/res/values-ru/strings.xml index e11100d52..c93e8c077 100644 --- a/tools/chatgui-android/app/src/main/res/values-ru/strings.xml +++ b/tools/chatgui-android/app/src/main/res/values-ru/strings.xml @@ -533,6 +533,7 @@ Переключение камеры, режима или ориентации… Нет совместимой камеры или видеокодировщика Поворот: %1$d° + Поворот: Авто Трансляция Всего субблоков Избыточных субблоков RS diff --git a/tools/chatgui-android/app/src/main/res/values/strings.xml b/tools/chatgui-android/app/src/main/res/values/strings.xml index 0e3727a15..f25dc0a4d 100644 --- a/tools/chatgui-android/app/src/main/res/values/strings.xml +++ b/tools/chatgui-android/app/src/main/res/values/strings.xml @@ -532,6 +532,7 @@ Switching camera, video mode or orientation… No compatible camera or video encoder found Rotation: %1$d° + Rotation: Auto Broadcast Total subblocks Redundant RS subblocks diff --git a/tools/chatgui-android/app/src/test/java/com/utun/chat/data/StreamOrientationTest.kt b/tools/chatgui-android/app/src/test/java/com/utun/chat/data/StreamOrientationTest.kt index a373f4719..d3da805b2 100644 --- a/tools/chatgui-android/app/src/test/java/com/utun/chat/data/StreamOrientationTest.kt +++ b/tools/chatgui-android/app/src/test/java/com/utun/chat/data/StreamOrientationTest.kt @@ -4,18 +4,40 @@ import org.junit.Assert.assertEquals import org.junit.Test class StreamOrientationTest { + private val manual = StreamOrientation.values().filter { it != StreamOrientation.AUTO } + @Test fun rearCameraRotationFollowsManualOrientation() { - assertEquals(listOf(90, 0, 270, 180), StreamOrientation.values().map { it.sensorRotation(90, false) }) - assertEquals(listOf(270, 180, 90, 0), StreamOrientation.values().map { it.sensorRotation(270, false) }) + assertEquals(listOf(90, 0, 270, 180), manual.map { it.sensorRotation(90, false) }) + assertEquals(listOf(270, 180, 90, 0), manual.map { it.sensorRotation(270, false) }) } @Test fun frontCameraUsesOppositeSensorCompensation() { - assertEquals(listOf(270, 0, 90, 180), StreamOrientation.values().map { it.sensorRotation(270, true) }) - assertEquals(listOf(90, 180, 270, 0), StreamOrientation.values().map { it.sensorRotation(90, true) }) + assertEquals(listOf(270, 0, 90, 180), manual.map { it.sensorRotation(270, true) }) + assertEquals(listOf(90, 180, 270, 0), manual.map { it.sensorRotation(90, true) }) } @Test fun camerasWithZeroSensorRotationKeepAllFourDirections() { - assertEquals(listOf(0, 270, 180, 90), StreamOrientation.values().map { it.sensorRotation(0, false) }) - assertEquals(listOf(0, 90, 180, 270), StreamOrientation.values().map { it.sensorRotation(0, true) }) + assertEquals(listOf(0, 270, 180, 90), manual.map { it.sensorRotation(0, false) }) + assertEquals(listOf(0, 90, 180, 270), manual.map { it.sensorRotation(0, true) }) + } + + @Test fun autoMatchesVideoCallsForEveryCameraAndDeviceDirection() { + for (sensor in listOf(0, 90, 180, 270)) for (angle in listOf(0, 90, 180, 270)) for (front in listOf(false, true)) { + val orientation = CallVideoOrientation() + orientation.observe(angle, 0) + assertEquals(orientation.rotation(sensor, front), StreamOrientation.AUTO.sensorRotation(sensor, front, orientation.degrees)) + } + } + + @Test fun manualOrientationIgnoresDeviceDirection() { + for (option in manual) for (angle in listOf(0, 90, 180, 270)) for (front in listOf(false, true)) { + assertEquals(option.sensorRotation(90, front), option.sensorRotation(90, front, angle)) + } + } + + @Test fun newCaptureUsesAutoByDefault() { + val mode = StreamCaptureMode("camera", 1280, 720, 30, 30, false, "encoder", 2_000_000) + assertEquals(StreamOrientation.AUTO, StreamCaptureConfig(mode).orientation) + assertEquals(StreamOrientation.AUTO.degrees, StreamCaptureSettings().rotation) } } diff --git a/tools/chatgui/src/settingsdialog.cpp b/tools/chatgui/src/settingsdialog.cpp index 4e07a3f76..5c26dc18b 100644 --- a/tools/chatgui/src/settingsdialog.cpp +++ b/tools/chatgui/src/settingsdialog.cpp @@ -22,6 +22,7 @@ #include "../../lib/debug_config.h" extern "C" { #include "chat/chat_core.h" +#include "call/call.h" } #include #include @@ -171,6 +172,16 @@ SettingsDialog::SettingsDialog(const QString& configPath, DbManager* db, UtunNod m_autoConnectCheck = new QCheckBox(QCoreApplication::translate("ChatGui", "Auto-connect to group nodes"), profilePage); m_autoConnectCheck->setStyleSheet("font-size: 13px;"); profLayout->addRow(m_autoConnectCheck); + m_publishCallStatus = new QCheckBox(QCoreApplication::translate("ChatGui", "Share my call status"), profilePage); + m_publishCallStatus->setObjectName(QStringLiteral("publishCallStatus")); + QSettings callConfig(m_configPath, QSettings::IniFormat); + const int callPolicy = callConfig.value("chatserver/incoming_call_policy", CALL_POLICY_PUBLISH_PHONE).toInt(); + m_publishCallStatus->setChecked(callPolicy & CALL_POLICY_PUBLISH_PHONE); + profLayout->addRow(m_publishCallStatus); + auto* callStatusNote = new QLabel(QCoreApplication::translate("ChatGui", + "Other participants can see whether you are busy with a call in this app."), profilePage); + callStatusNote->setWordWrap(true); + profLayout->addRow(callStatusNote); m_pages->addWidget(profilePage); // Storage page @@ -323,6 +334,27 @@ void SettingsDialog::onCategoryChanged(int row) { } void SettingsDialog::onSave() { + // Меняем только разрешение публикации, сохраняя остальные настройки входящих вызовов. + QSettings callConfig(m_configPath, QSettings::IniFormat); + int callPolicy = callConfig.value("chatserver/incoming_call_policy", CALL_POLICY_PUBLISH_PHONE).toInt(); + callPolicy = (callPolicy & ~CALL_POLICY_PUBLISH_PHONE) | (m_publishCallStatus->isChecked() ? CALL_POLICY_PUBLISH_PHONE : 0); + if (!config_update_option(m_configPath, "chatserver", "incoming_call_policy", QString::number(callPolicy))) { + DEBUG_ERROR(DEBUG_CATEGORY_CONFIG, "Call status: failed to save policy=%d path=%s", callPolicy, qPrintable(m_configPath)); + QMessageBox::warning(this, QCoreApplication::translate("ChatGui", "Settings"), + QCoreApplication::translate("ChatGui", "Failed to save call status settings. Check the configuration file.")); + return; + } + if (gui_bridge_is_uasync_ready() && gui_bridge_get_inst()) { + auto* arg = static_cast(u_calloc(1, sizeof(chat_setting_arg))); + if (!arg) { DEBUG_ERROR(DEBUG_CATEGORY_CALL, "Call status: request allocation failed"); return; } + arg->inst = gui_bridge_get_inst(); + const char* key = "incoming_call_policy"; + memcpy(arg->data, key, strlen(key) + 1); + snprintf(arg->data + strlen(key) + 1, sizeof(arg->data) - strlen(key) - 1, "%d", callPolicy); + gui_bridge_post_uasync_fn(chat_core_set_setting_trampoline, arg); + } else DEBUG_WARN(DEBUG_CATEGORY_CALL, "Call status: core unavailable; saved policy=%d applies at startup", callPolicy); + DEBUG_INFO(DEBUG_CATEGORY_CALL, "Call status: sharing=%d policy=%d saved", m_publishCallStatus->isChecked(), callPolicy); + QString newName = m_nicknameEdit->text().trimmed(); bool nameChanged = (newName != m_oldNickname); diff --git a/tools/chatgui/src/settingsdialog.h b/tools/chatgui/src/settingsdialog.h index f6e5eca69..8f7e4065c 100644 --- a/tools/chatgui/src/settingsdialog.h +++ b/tools/chatgui/src/settingsdialog.h @@ -49,6 +49,7 @@ private: QComboBox* m_languageCombo; QComboBox* m_joinPolicyCombo; QCheckBox* m_autoConnectCheck; + QCheckBox* m_publishCallStatus; // Разрешение публикации своего статуса звонка. QSpinBox* m_streamSubblocks; QSpinBox* m_streamRedundant; QString m_oldNickname; diff --git a/tools/chatgui/translations/chatgui_en.ts b/tools/chatgui/translations/chatgui_en.ts index 0f8e0e2b2..453e1eb69 100644 --- a/tools/chatgui/translations/chatgui_en.ts +++ b/tools/chatgui/translations/chatgui_en.ts @@ -3,6 +3,9 @@ ChatGui + Share my call statusShare my call status + Other participants can see whether you are busy with a call in this app.Other participants can see whether you are busy with a call in this app. + Failed to save call status settings. Check the configuration file.Failed to save call status settings. Check the configuration file. Subscriber's radio is already on in this channelSubscriber's radio is already on in this channel Subscriber is on a phone callSubscriber is on a phone call Call anywayCall anyway diff --git a/tools/chatgui/translations/chatgui_ru.ts b/tools/chatgui/translations/chatgui_ru.ts index dcd48461b..dc9c40a60 100644 --- a/tools/chatgui/translations/chatgui_ru.ts +++ b/tools/chatgui/translations/chatgui_ru.ts @@ -3,6 +3,9 @@ ChatGui + Share my call statusОтправлять мой статус звонка + Other participants can see whether you are busy with a call in this app.Другие участники видят, заняты ли вы звонком в этом приложении. + Failed to save call status settings. Check the configuration file.Не удалось сохранить настройки статуса звонка. Проверьте файл конфигурации. Subscriber's radio is already on in this channelРация абонента уже включена в этом канале Subscriber is on a phone callАбонент разговаривает по телефону Call anywayВсё равно позвонить