Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 165 additions & 0 deletions cmd/trace-mobile/internal/codeccheck/check.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
package codeccheck

import (
"fmt"
"strings"
"sync"
)

// Result describes the outcome of pre-checking a track's codec support.
type Result struct {
Supported bool
Known bool
CodecLabel string
IsAudio bool
Message string
}

// ProbeFunc queries whether the device can decode the given MIME type at (width, height).
// Returning known=false means the platform has no native MediaCodecList query (e.g. desktop).
type ProbeFunc func(mime string, width, height int) (supported bool, known bool)

var (
probeMu sync.RWMutex
customProbe ProbeFunc
)

// SetProbeForTest overrides the native codec probe (pass nil to restore default).
func SetProbeForTest(fn ProbeFunc) {
probeMu.Lock()
customProbe = fn
probeMu.Unlock()
}

func runProbe(mime string, width, height int) (bool, bool) {
probeMu.RLock()
fn := customProbe
probeMu.RUnlock()
if fn != nil {
return fn(mime, width, height)
}
ch, err := NewChecker()
if err != nil {
return true, false
}
defer func() { _ = ch.Close() }()
ok, err := ch.CanDecode(mime, width, height)
if err != nil {
return true, false
}
return ok, true
}

// ParseCodecHints extracts normalized video and audio MIME types + display labels
// from free-form codec or quality summary strings (e.g. "1080P 高码率 · AV1 · 杜比全景声",
// "av01.0.08M.08", "hvc1", "hevc", "avc1", "flac").
func ParseCodecHints(hints ...string) (videoMIME, videoLabel, audioMIME, audioLabel string) {
joined := strings.ToLower(strings.Join(hints, " "))
if joined == "" {
return "", "", "", ""
}
tokens := splitCodecTokens(joined)
for _, tok := range tokens {
if videoMIME == "" {
switch {
case tok == "av1" || tok == "av01" || strings.HasPrefix(tok, "av01."):
videoMIME, videoLabel = "video/av01", "AV1"
case tok == "hevc" || tok == "h265" || tok == "h.265" || tok == "hvc1" || tok == "hev1" || strings.HasPrefix(tok, "hvc1.") || strings.HasPrefix(tok, "hev1."):
videoMIME, videoLabel = "video/hevc", "HEVC"
case tok == "avc" || tok == "h264" || tok == "h.264" || tok == "avc1" || strings.HasPrefix(tok, "avc1."):
videoMIME, videoLabel = "video/avc", "AVC"
case tok == "vp9" || tok == "vp09" || strings.HasPrefix(tok, "vp09."):
videoMIME, videoLabel = "video/x-vnd.on2.vp9", "VP9"
}
}
if audioMIME == "" {
switch {
case tok == "flac" || strings.Contains(tok, "hi-res"):
audioMIME, audioLabel = "audio/flac", "FLAC"
case tok == "eac3" || tok == "ec-3" || tok == "dolby" || strings.Contains(tok, "杜比"):
audioMIME, audioLabel = "audio/eac3", "杜比音轨"
case tok == "ac3" || tok == "ac-3":
audioMIME, audioLabel = "audio/ac3", "AC-3"
}
}
}
return videoMIME, videoLabel, audioMIME, audioLabel
}

func splitCodecTokens(s string) []string {
return strings.FieldsFunc(s, func(r rune) bool {
switch r {
case ' ', '\t', '\n', '\r', ',', ';', '/', '|', '·', '(', ')', '[', ']', '(', ')':
return true
default:
return false
}
})
}

// CheckTrack runs Layer-1 (MediaCodecList pre-check) on video and audio codec hints.
// If the device explicitly reports it cannot decode the track's video or audio codec,
// Result.Known is true, Result.Supported is false, and Result.Message gives a clear
// Chinese explanation (FR-MOB-014).
func CheckTrack(videoCodecHint, audioCodecHint string, width, height int) Result {
vMIME, vLabel, aMIME, aLabel := ParseCodecHints(videoCodecHint, audioCodecHint)
if vMIME != "" {
ok, known := runProbe(vMIME, width, height)
if known && !ok {
return Result{
Supported: false,
Known: true,
CodecLabel: vLabel,
IsAudio: false,
Message: UnsupportedMessage(vLabel, false),
}
}
if known {
if aMIME != "" {
aOK, aKnown := runProbe(aMIME, 0, 0)
if aKnown && !aOK {
return Result{
Supported: false,
Known: true,
CodecLabel: aLabel,
IsAudio: true,
Message: UnsupportedMessage(aLabel, true),
}
}
}
return Result{Supported: true, Known: true, CodecLabel: vLabel}
}
}
if aMIME != "" {
aOK, aKnown := runProbe(aMIME, 0, 0)
if aKnown && !aOK {
return Result{
Supported: false,
Known: true,
CodecLabel: aLabel,
IsAudio: true,
Message: UnsupportedMessage(aLabel, true),
}
}
if aKnown {
return Result{Supported: true, Known: true, CodecLabel: aLabel, IsAudio: true}
}
}
return Result{Supported: true, Known: false, CodecLabel: vLabel}
}

// UnsupportedMessage returns the user-facing Chinese explanation when a codec
// cannot be decoded on this phone (docs/ui.md §3.12, FR-MOB-014).
func UnsupportedMessage(codecLabel string, isAudio bool) string {
label := strings.TrimSpace(codecLabel)
if label == "" {
return "这台手机不能播放这段视频的编码格式"
}
if isAudio {
if strings.HasSuffix(label, "音轨") {
return fmt.Sprintf("这台手机不能播放 %s", label)
}
return fmt.Sprintf("这台手机不能播放 %s 音轨", label)
}
return fmt.Sprintf("这台手机不能播放 %s 视频", label)
}
18 changes: 18 additions & 0 deletions cmd/trace-mobile/internal/codeccheck/codeccheck.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Package codeccheck queries Android's MediaCodecList for video/audio decoder
// capabilities before starting playback (FR-MOB-014, docs/design/mobile.md §6 & §9).
// On non-Android platforms (desktop/tests), NewChecker returns errors.ErrUnsupported
// and CheckTrack gracefully reports Known=false so desktop builds need no cgo.
package codeccheck

// Checker queries the platform media codec registry for decoder support.
//
//mygo:native
type Checker interface {
// CanDecode reports whether the device has a decoder supporting the given
// MIME type (e.g. "video/av01", "video/hevc", "video/avc", "audio/flac").
// When width > 0 and height > 0 for video MIME types, the decoder's
// supported frame size range is also checked.
CanDecode(mime string, width, height int) (bool, error)
// Close releases resources held by the checker.
Close() error
}
73 changes: 73 additions & 0 deletions cmd/trace-mobile/internal/codeccheck/codeccheck_native.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

64 changes: 64 additions & 0 deletions cmd/trace-mobile/internal/codeccheck/codeccheck_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package codeccheck

import "testing"

func TestParseCodecHints(t *testing.T) {
cases := []struct {
hints []string
vMIME string
vLabel string
aMIME string
aLabel string
}{
{[]string{"1080P 高码率 · AV1 · 杜比全景声"}, "video/av01", "AV1", "audio/eac3", "杜比音轨"},
{[]string{"av01.0.08M.08"}, "video/av01", "AV1", "", ""},
{[]string{"4K · HEVC", "FLAC"}, "video/hevc", "HEVC", "audio/flac", "FLAC"},
{[]string{"hvc1.1.6.L120.90"}, "video/hevc", "HEVC", "", ""},
{[]string{"原画 · AVC"}, "video/avc", "AVC", "", ""},
{[]string{"vp09.00.41.08"}, "video/x-vnd.on2.vp9", "VP9", "", ""},
{[]string{"Hi-Res 无损"}, "", "", "audio/flac", "FLAC"},
}
for _, tc := range cases {
vm, vl, am, al := ParseCodecHints(tc.hints...)
if vm != tc.vMIME || vl != tc.vLabel || am != tc.aMIME || al != tc.aLabel {
t.Fatalf("ParseCodecHints(%v) = (%q,%q,%q,%q), want (%q,%q,%q,%q)",
tc.hints, vm, vl, am, al, tc.vMIME, tc.vLabel, tc.aMIME, tc.aLabel)
}
}
}

func TestCheckTrackPrecheckAndFallback(t *testing.T) {
// Default on desktop/non-Android: graceful fallback with Known=false, Supported=true.
SetProbeForTest(nil)
res := CheckTrack("1080P · AV1", "", 1920, 1080)
if !res.Supported || res.Known {
t.Fatalf("desktop fallback should be Supported=true Known=false, got %+v", res)
}

// Mock Android phone without AV1 decoder.
SetProbeForTest(func(mime string, w, h int) (bool, bool) {
if mime == "video/av01" {
return false, true
}
if mime == "audio/flac" {
return false, true
}
return true, true
})
defer SetProbeForTest(nil)

av1 := CheckTrack("1080P · AV1", "", 1920, 1080)
if av1.Supported || !av1.Known || av1.Message != "这台手机不能播放 AV1 视频" {
t.Fatalf("expected AV1 unsupported message, got %+v", av1)
}

flac := CheckTrack("1080P · AVC", "FLAC", 1920, 1080)
if flac.Supported || !flac.Known || flac.Message != "这台手机不能播放 FLAC 音轨" {
t.Fatalf("expected FLAC unsupported message, got %+v", flac)
}

avc := CheckTrack("1080P · AVC", "AAC", 1920, 1080)
if !avc.Supported || !avc.Known {
t.Fatalf("expected AVC supported, got %+v", avc)
}
}
1 change: 1 addition & 0 deletions cmd/trace-mobile/internal/codeccheck/kotlin/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
15 changes: 15 additions & 0 deletions cmd/trace-mobile/internal/codeccheck/kotlin/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// The Kotlin of the native module codeccheck: an Android library, which mygo
// build adds to the app's Gradle build. The build sets its SDK levels, Java
// and Kotlin, and its dependency on MyGo's host library (dev.mygo), which
// brings coroutines: add only what the implementation uses.
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
}

android {
namespace = "com.github.chialecode.trace.cmd.trace_mobile.internal.codeccheck"
}

dependencies {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.github.chialecode.trace.cmd.trace_mobile.internal.codeccheck

import android.media.MediaCodecList
import android.util.Log

fun makeChecker(): Checker = AndroidCodecChecker()

private class AndroidCodecChecker : Checker {
override fun canDecode(mime: String, width: Long, height: Long): Boolean {
val target = mime.trim().lowercase()
if (target.isEmpty()) return true
val w = width.coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
val h = height.coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
return try {
val list = MediaCodecList(MediaCodecList.ALL_CODECS)
val isVideo = target.startsWith("video/")
for (info in list.codecInfos) {
if (info.isEncoder) continue
val matchedType = info.supportedTypes.firstOrNull { it.equals(target, ignoreCase = true) }
?: continue
if (!isVideo || w <= 0 || h <= 0) {
return true
}
val caps = try {
info.getCapabilitiesForType(matchedType)
} catch (_: Throwable) {
null
}
val vcaps = caps?.videoCapabilities
if (vcaps == null) {
return true
}
if (vcaps.isSizeSupported(w, h)) {
return true
}
// Some decoders declare portrait/landscape transposed bounds.
if (vcaps.isSizeSupported(h, w)) {
return true
}
}
false
} catch (t: Throwable) {
Log.w("trace-codeccheck", "MediaCodecList query failed for $target: $t")
true
}
}

override fun close() {
// Stateless query wrapper; nothing to release.
}
}
Loading