Files
piik/native/capture/windows/h264_encoder.h
T
AAA 59d21702fe fix(media): preserve sharing startup and viewing continuity
## Problem and outcome / 问题与结果

Native sharing could start capture before discovering that the browser could not create its local media connection. Connected Viewer routes could also be retired solely because decoded frames stopped advancing, including quiet or backgrounded game sources. This maintenance phase acquires the browser bridge before capture, preserves connected routes through frame silence, scopes Native keyframe recovery to the requested outputs, and reports terminal Browser sender failures to the existing connection owner. It also includes the accepted narrow-screen layout and tooltip corrections.

## Release notes

### 中文

这是一次维护更新,重点修复分享启动、观看连续性和手机窄屏布局。

- 修复浏览器媒体连接无法初始化时,App 仍启动采集后立即停止的问题,并保留更明确的失败原因。
- 避免仅因画面暂时没有更新,就断开已连接的观看线路;适用于游戏切后台等静止画面场景。
- 修正原生画面恢复请求的范围,避免某一路请求关键帧时影响其他输出;浏览器发送失败也会及时通知现有连接处理流程。
- 修复窄屏下房间号与操作按钮的排布,改善长标题和提示浮层的显示。

短时模糊与部分用户报告的偶发断流仍在调查,本次更新不代表所有相关情况均已解决。升级 App 或自部署 Server 后刷新页面即可,无需修改配置。

### English

This maintenance update focuses on sharing startup, viewing continuity, and compact layouts on phones.

- Fix capture starting and immediately stopping when the browser cannot initialize its local media connection, and preserve clearer failure details.
- Keep connected viewing routes alive when the picture temporarily stops updating, including quiet or backgrounded game sources.
- Keep Native keyframe recovery scoped to the requested outputs and report terminal Browser sender failures to the existing connection handler.
- Fix room-code and action layout on narrow screens, and improve long headings and tooltip placement.

Brief quality drops and some reports of intermittent stream loss remain under investigation; this update does not claim to resolve every reported case. Update Piik App or your self-hosted Server and refresh the page. No configuration changes are required.

## Verification / 验证

- `npm run check`: 76 files / 1,133 tests, TypeScript and production Web build passed.
- Targeted Browser sender/pool checks: 97 tests passed on maintenance and interaction candidates.
- Go mediaedge/nativehost/nativecapture/forwarding tests and scoped vet passed; output-scope regression tests reject the old behavior.
- Matched Chrome 152 VP8/H264 ordinary/pool tests with two viewers and a one-second network constraint completed with healthy sibling isolation. VP8's deeper pooled quality dip remains open.
- Physical startup/resource-exhaustion and quiet-game reproduction boundaries are documented in the existing research owners.
- `npm run check:go`: formatting, Go tests/vet, Windows/Linux builds, Windows native capture compilation/probes and regressions passed. Darwin packaging and Go race checks run on the native CI runners.
- Actual Windows App H264 and VP8 Host gates passed: decoded video, live/paused profile changes, quiet/background-source recovery, source replacement, failure cleanup and subsequent sharing; all experiment-owned processes and ports closed.
- Website build and repository hygiene checks passed. Independent full-phase frontend and native reviews found no release-blocking regression.

## Impact / 影响

Patch release v1.6.6. Browser/server v23, Native control v9, capture v7 and SQLite schema 2 remain unchanged. No interaction prototype, route-selection policy, new quality heuristic, or configuration migration is included. Real-phone and heterogeneous network/device coverage remain bounded by the existing verification record.
2026-09-27 11:03:25 +08:00

240 lines
7.4 KiB
C++

#pragma once
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <codecapi.h>
#include <d3d11.h>
#include <dxgi1_2.h>
#include <strmif.h>
#include <mfapi.h>
#include <mfidl.h>
#include <mftransform.h>
#include <wrl/client.h>
#include "capture_error.h"
#include <chrono>
#include <iomanip>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
namespace piik::capture {
enum class OutputKind : UINT8;
}
namespace piik::capture::windows {
using Microsoft::WRL::ComPtr;
enum class DegradationPreference {
resolution,
balanced,
framerate,
};
struct VideoProfile final {
UINT32 width = 1280;
UINT32 height = 720;
UINT32 frame_rate = 30;
UINT32 bit_rate = 3'000'000;
DegradationPreference preference = DegradationPreference::balanced;
UINT32 gop_frames() const { return frame_rate * 2; }
LONGLONG frame_duration_100ns() const {
return 10'000'000 / static_cast<LONGLONG>(frame_rate);
}
UINT32 quality_vs_speed() const {
if (preference == DegradationPreference::resolution) return 100;
if (preference == DegradationPreference::framerate) return 0;
return 50;
}
UINT32 h264_level() const {
const UINT64 macroblocks =
((static_cast<UINT64>(width) + 15) / 16) *
((static_cast<UINT64>(height) + 15) / 16);
const UINT64 macroblocks_per_second = macroblocks * frame_rate;
if (macroblocks <= 3'600 && macroblocks_per_second <= 108'000) return 31;
if (macroblocks <= 8'192 && macroblocks_per_second <= 245'760) return 40;
if (macroblocks <= 8'704 && macroblocks_per_second <= 522'240) return 42;
if (macroblocks <= 22'080 && macroblocks_per_second <= 589'824) return 50;
return 51;
}
std::string profile_level_id() const {
std::ostringstream output;
output << "42c0" << std::hex << std::setfill('0') << std::setw(2)
<< h264_level();
return output.str();
}
};
constexpr VideoProfile kDefaultVideoProfile{};
struct Runtime final {
Runtime() {
Check(CoInitializeEx(nullptr, COINIT_MULTITHREADED), "com-initialize");
com_started = true;
Check(MFStartup(MF_VERSION, MFSTARTUP_FULL), "mf-startup");
mf_started = true;
}
~Runtime() {
if (mf_started) {
MFShutdown();
}
if (com_started) {
CoUninitialize();
}
}
bool com_started = false;
bool mf_started = false;
};
struct Adapter final {
UINT index = 0;
DXGI_ADAPTER_DESC1 description = {};
ComPtr<IDXGIAdapter1> value;
};
struct DeviceContext final {
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
ComPtr<IMFDXGIDeviceManager> manager;
D3D_FEATURE_LEVEL feature_level = D3D_FEATURE_LEVEL_9_1;
};
class ActivationList final {
public:
ActivationList() = default;
ActivationList(const ActivationList&) = delete;
ActivationList& operator=(const ActivationList&) = delete;
ActivationList(ActivationList&& other) noexcept
: values(std::exchange(other.values, nullptr)),
count(std::exchange(other.count, 0)) {}
~ActivationList() {
for (UINT32 index = 0; index < count; ++index) {
values[index]->Release();
}
CoTaskMemFree(values);
}
IMFActivate** values = nullptr;
UINT32 count = 0;
};
struct SelectedTransform final {
SelectedTransform() = default;
SelectedTransform(const SelectedTransform&) = delete;
SelectedTransform& operator=(const SelectedTransform&) = delete;
SelectedTransform(SelectedTransform&&) noexcept = default;
SelectedTransform& operator=(SelectedTransform&&) = delete;
~SelectedTransform() { if (activation) activation->ShutdownObject(); }
std::string name;
std::string clsid;
ComPtr<IMFActivate> activation;
ComPtr<IMFTransform> transform;
ComPtr<ICodecAPI> codec;
ComPtr<IMFMediaEventGenerator> events;
};
struct NalSummary final {
bool annex_b = false;
bool sps = false;
bool pps = false;
bool idr = false;
std::optional<std::string> profile_level_id;
};
std::vector<Adapter> EnumerateAdapters();
const Adapter& SelectAdapter(const std::vector<Adapter>& adapters, UINT index);
DeviceContext CreateDevice(const Adapter& adapter);
ActivationList EnumerateHardwareEncoders(const Adapter& adapter,
bool require_candidate = true);
SelectedTransform ActivateTransform(const ActivationList& list, UINT index,
IMFDXGIDeviceManager* manager);
std::wstring GetOptionalString(IMFAttributes* attributes, const GUID& key);
std::string NarrowAscii(const std::wstring& value);
std::string GuidString(const GUID& value);
// The hardware fixture uses the same configuration and output validation.
void SetU32(ICodecAPI* codec, const GUID& key, UINT32 expected,
const std::string& name);
void ConfigureCodec(ICodecAPI* codec,
const VideoProfile& profile = kDefaultVideoProfile);
ComPtr<IMFMediaType> CreateOutputType(
const VideoProfile& profile = kDefaultVideoProfile);
ComPtr<IMFMediaType> CreateInputType(
const VideoProfile& profile = kDefaultVideoProfile);
void ValidateMediaTypes(IMFTransform* transform,
const VideoProfile& profile = kDefaultVideoProfile);
void ValidateCodecReadback(ICodecAPI* codec,
const VideoProfile& profile = kDefaultVideoProfile);
void ForceKeyFrame(ICodecAPI* codec);
ComPtr<IMFSample> PullOutput(IMFTransform* transform,
const MFT_OUTPUT_STREAM_INFO& info);
NalSummary InspectAnnexB(const std::vector<UINT8>& bytes);
std::vector<UINT8> ReadSample(IMFSample* sample);
struct EncodedAccessUnit final {
UINT64 timestamp100ns = 0;
bool key_frame = false;
std::vector<UINT8> bytes;
};
using EncoderClock = std::chrono::steady_clock;
void RequireEncoderTime(EncoderClock::time_point deadline);
class VideoEncoder {
public:
VideoEncoder(OutputKind kind, std::string name, std::string identity)
: kind(kind), name(std::move(name)), identity(std::move(identity)) {}
virtual ~VideoEncoder() = default;
virtual EncodedAccessUnit Encode(ID3D11Texture2D* texture,
UINT64 timestamp100ns,
bool force_key_frame,
EncoderClock::time_point deadline =
EncoderClock::time_point::max()) = 0;
virtual void SetBitrate(UINT32 bitrate) = 0;
const OutputKind kind;
const std::string name;
const std::string identity;
};
// The caller owns COM/MF startup and serializes access to each encoder.
class LiveEncoder final : public VideoEncoder {
public:
explicit LiveEncoder(SelectedTransform selected,
VideoProfile profile = kDefaultVideoProfile);
~LiveEncoder() override;
LiveEncoder(const LiveEncoder&) = delete;
LiveEncoder& operator=(const LiveEncoder&) = delete;
void SetBitrate(UINT32 bitrate) override;
EncodedAccessUnit Encode(
ID3D11Texture2D* texture, UINT64 timestamp100ns, bool force_key_frame,
EncoderClock::time_point deadline = EncoderClock::time_point::max()) override;
private:
MediaEventType NextEvent(EncoderClock::time_point deadline, const char* timeout_stage);
void WaitForInput(EncoderClock::time_point deadline);
SelectedTransform selected_;
VideoProfile profile_;
MFT_OUTPUT_STREAM_INFO output_info_ = {};
UINT32 input_requests_ = 0;
std::optional<std::string> profile_level_id_;
bool started_ = false;
};
} // namespace piik::capture::windows