Files
piik/internal/media/forwarding/encoded_source.go
T
AAA 815f1a07c4 fix(media): stabilize sharing recovery and remote input (#513)
## Problem and outcome

Connection recovery and packet repair could leave stale pictures, missing sound or unreliable remote input. This maintenance release repairs media/route ownership, H.264 negotiation, voice forwarding and Windows input recovery, and makes shared mobile controls and popovers easier to use.

## Release notes
**Piik, now in your pocket.**

Piik App supports Android screen sharing, with touch controls for a friend's computer.

**手机,也能开播。**

Piik App 支持 Android 屏幕分享,也能用手机控制朋友的电脑。

### English

Piik v2.5.1 improves sharing recovery, voice playback and remote control, with clearer mobile controls. It keeps the existing 2.x compatibility baseline.

- Improve H.264 selection and picture recovery after reconnecting, changing sources or recovering lost packets; keep a working share when a replacement source fails.
- Keep audio and room voice continuous, and prevent duplicate sound when switching playback windows.
- Improve Windows input recovery and release remote-control permissions when their connection ends.
- Keep mobile controls together and popovers usable after layout changes or in short viewports.
- Open the appropriate Android update download, including the Gitee ZIP containing the APK. Self-hosted SFU servers refresh public addresses for new connections without a restart.
- Add macOS source-thumbnail support.

Update the App and self-hosted site together to receive all fixes. Browser settings and existing room data are retained.

### 中文

Piik v2.5.1 改善分享恢复、语音播放与远程控制的稳定性,让手机操作更顺手,沿用现有 2.x 兼容基线。

- 改善 H.264 编码选择,以及重连、切换分享源和丢包后的画面恢复;新分享源切换失败时保留正常分享。
- 保持声音与房间语音连续,避免切换播放窗口时出现双重声音。
- 改善 Windows 输入恢复,并在连接结束时释放远程控制授权。
- 手机控件保持成组,浮层在布局变化或可见高度较小时仍可操作。
- Android 更新打开对应下载入口,Gitee 提供内含 APK 的 ZIP;自部署 SFU 为新连接刷新公网地址,无需重启服务。
- 补齐 macOS 选源缩略图支持。

请一起更新 App 与自部署站点,以获得全部修复。浏览器设置与已有房间数据保留。
## Validation

- Full frontend typecheck, test and production-build acceptance; current Windows App/Server packaging, extracted-file checks and exact served JavaScript verified locally.
- Existing Go, vulnerability, native media and controlled-network results retained at their tested revisions. The final production delta from the fully checked candidate is the shared short-viewport popover correction.
- The diagnostic report supplied for #502 informed the Windows input fixes. #500 sharing is confirmed working; its missing source previews are implemented. Original-device follow-up remains separate from this release's verified local fixes.

## Compatibility and scope

Preserves the published 2.x Browser/server, Native control, capture and SQLite contracts. No 3.0 or iOS implementation or external contributor patch is included. Related: #500, #502, #510, #512.
2026-10-31 16:34:12 -04:00

149 lines
5.4 KiB
Go

package forwarding
import (
"errors"
"math"
"time"
"github.com/TNTcraftHIM/Piik/internal/media/encoded"
"github.com/livekit/mediatransportutil"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/utils/mono"
"github.com/pion/rtp"
"github.com/pion/rtp/codecs"
"github.com/pion/webrtc/v4"
)
// EncodedSource feeds complete codec outputs into the same forwarding buffers
// used for received RTP. Its capture/decoder owner serializes calls and fences
// replacement input; no network, capture or wall-clock scheduler lives here.
type EncodedSource struct {
*Source
packetizers []*encoded.Packetizer
packets []uint32
octets []uint64
codecBytes []uint64
rtpBytes []uint64
inputPTS time.Duration
anchorPTS time.Duration
anchorTime time.Time
originTime time.Time
hasInput bool
clockSource *Source
clockLayer int
}
func NewEncodedSource(options SourceOptions) (*EncodedSource, error) {
source, err := NewSource(options)
if err != nil {
return nil, err
}
input := &EncodedSource{
Source: source, packetizers: make([]*encoded.Packetizer, len(options.Formats)),
packets: make([]uint32, len(options.Formats)), octets: make([]uint64, len(options.Formats)),
codecBytes: make([]uint64, len(options.Formats)), rtpBytes: make([]uint64, len(options.Formats)),
}
for layer := range input.packetizers {
var payloader rtp.Payloader = &codecs.H264Payloader{}
if options.Codec.MimeType == webrtc.MimeTypeVP8 {
payloader = &codecs.VP8Payloader{EnablePictureID: true}
}
input.packetizers[layer] = encoded.NewPacketizer(payloader, uint8(options.Codec.PayloadType), 1200)
// These identities stay inside this source's private buffers. DownTrack
// supplies the independently negotiated wire identity for every child.
if err = source.BindLayer(layer, uint32(layer+1), webrtc.RTPParameters{
Codecs: []webrtc.RTPCodecParameters{options.Codec}, HeaderExtensions: options.HeaderExtensions,
}); err != nil {
source.Close()
return nil, err
}
}
return input, nil
}
// UseSourceClock binds derived output to the original layer's current remote
// clock offset. The owner installs this before feeding any encoded frames.
func (input *EncodedSource) UseSourceClock(source *Source, layer int) {
input.clockSource, input.clockLayer = source, layer
}
func (input *EncodedSource) BeginFrame(pts time.Duration, at time.Time) error {
if input.IsClosed() {
return errors.New("encoded forwarding source is closed")
}
if pts < 0 || at.IsZero() || input.hasInput && pts <= input.inputPTS {
return encoded.ErrInvalidTimestamp
}
if !input.hasInput {
input.anchorPTS, input.anchorTime = pts, at
}
if input.originTime.IsZero() {
input.originTime = at
}
input.hasInput, input.inputPTS = true, pts
return nil
}
func (input *EncodedSource) WriteFrame(layer int, frame encoded.Frame) error {
if layer < 0 || layer >= len(input.packetizers) || !input.hasInput ||
frame.PTS < input.anchorPTS || frame.PTS > input.inputPTS {
return errors.New("encoded output has no matching source input")
}
sourceTime := input.anchorTime.Add(frame.PTS - input.anchorPTS)
packets, err := input.packetizers[layer].Packetize(frame.Data, sourceTime.Sub(input.originTime), frame.Duration)
if err != nil {
return err
}
for _, packet := range packets {
packet.SSRC = uint32(layer + 1)
if err = input.Source.WriteRTP(layer, packet); err != nil {
return err
}
input.packets[layer]++
input.octets[layer] += uint64(len(packet.Payload))
input.rtpBytes[layer] += uint64(packet.MarshalSize())
}
input.codecBytes[layer] += uint64(len(frame.Data))
if len(packets) == 0 {
return nil
}
// Retain the capture instant's Go monotonic component when converting to
// the media core's epoch-based monotonic clock, including after wall jumps.
localTime := mono.FromTime(sourceTime)
if input.clockSource != nil {
var ok bool
localTime, ok = input.clockSource.LocalTime(input.clockLayer, sourceTime)
if !ok {
return errors.New("encoded output has no source clock reference")
}
}
// Correlate each layer with the actual input clock, not its encoder finish
// time. This is internal correlation data, not a backdated wire sender report.
return input.SetCorrelation(layer, &livekit.RTCPSenderReportState{
RtpTimestamp: packets[0].Timestamp,
NtpTimestamp: uint64(mediatransportutil.ToNtpTime(sourceTime)),
Packets: input.packets[layer], Octets: input.octets[layer], At: localTime.UnixNano(),
})
}
// CodecBudget converts source-RTP allocation units to encoder AU-payload units.
// Actual packetization includes codec descriptors; bitrate comes from the
// existing tracker window so dormant time does not dilute the overhead rate.
// Downstream extensions and SRTP/UDP overhead are outside this source measure.
func (input *EncodedSource) CodecBudget(layer int, rtpBudget int64) int64 {
if layer < 0 || layer >= len(input.rtpBytes) || input.rtpBytes[layer] <= input.codecBytes[layer] {
return max(rtpBudget, 0)
}
_, rates := input.GetLayeredBitrate()
overhead := float64(rates[layer][0]) * float64(input.rtpBytes[layer]-input.codecBytes[layer]) / float64(input.rtpBytes[layer])
return max(rtpBudget-int64(math.Ceil(overhead)), 0)
}
func (input *EncodedSource) BeginGeneration() {
// Replacement resets input PTS, but all renditions retain the elapsed
// capture clock and RTP identities, including time spent dormant.
input.hasInput = false
clear(input.codecBytes)
clear(input.rtpBytes)
}