feat: init codecs detect

This commit is contained in:
hughew 2025-11-07 11:37:09 +08:00
commit 4e0b181c2b
34 changed files with 5664 additions and 0 deletions

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

73
README.md Normal file
View File

@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

22
components.json Normal file
View File

@ -0,0 +1,22 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/index.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"registries": {}
}

23
eslint.config.js Normal file
View File

@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

13
index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>test_webcodecs</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

4070
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

46
package.json Normal file
View File

@ -0,0 +1,46 @@
{
"name": "test_webcodecs",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@radix-ui/react-accordion": "^1.2.12",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.552.0",
"preact": "^10.27.2",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"tailwind-merge": "^3.3.1"
},
"devDependencies": {
"@eslint/js": "^9.36.0",
"@tailwindcss/vite": "^4.1.17",
"@types/node": "^24.6.0",
"@types/react": "^19.1.16",
"@types/react-dom": "^19.1.9",
"@vitejs/plugin-react": "^5.0.4",
"autoprefixer": "^10.4.21",
"eslint": "^9.36.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.22",
"globals": "^16.4.0",
"postcss": "^8.5.6",
"tailwindcss": "^4.1.17",
"tw-animate-css": "^1.4.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.45.0",
"vite": "npm:rolldown-vite@7.1.14"
},
"overrides": {
"vite": "npm:rolldown-vite@7.1.14"
}
}

1
public/vite.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

42
src/App.css Normal file
View File

@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

10
src/App.tsx Normal file
View File

@ -0,0 +1,10 @@
import DetectorCard from './components/DetectorCard'
export function App() {
return (
<div className="min-h-screen w-full flex items-center justify-center p-4">
<DetectorCard />
</div>
)
}
export { App as default }

1
src/assets/react.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@ -0,0 +1,112 @@
import { useEffect, useMemo, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "../components/ui/card";
import { Badge } from "../components/ui/badge";
import { Separator } from "../components/ui/separator";
import { Button } from "../components/ui/button";
import type { CodecSupport, CodecStatus } from "../utils/codecs";
import { detectAll } from "../utils/codecs";
function label(status: CodecStatus) {
switch (status) {
case "supported":
return "支持";
case "unsupported":
return "不支持";
default:
return "未知";
}
}
function variant(status: CodecStatus): "default" | "destructive" | "outline" {
switch (status) {
case "supported":
return "default";
case "unsupported":
return "destructive";
default:
return "outline";
}
}
export default function DetectorCard() {
const [support, setSupport] = useState<CodecSupport | null>(null);
const [loading, setLoading] = useState(false);
const webCodecsLabel = useMemo(() => (support?.webCodecs ? "可用" : loading ? "检测中" : "不可用"), [support, loading]);
async function runDetect() {
setLoading(true);
try {
const result = await detectAll();
setSupport(result);
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
}
useEffect(() => {
runDetect();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const onCopy = async () => {
const text = JSON.stringify(support?.details ?? {}, null, 2);
try {
await navigator.clipboard.writeText(text);
} catch {}
};
return (
<Card className="max-w-2xl mx-auto">
<CardHeader>
<CardTitle>WebCodecs </CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-sm text-muted-foreground">
WebCodecsAVC(H.264)HEVC(H.265) /
</div>
<Separator />
<div className="grid grid-cols-1 gap-3">
<div className="flex items-center justify-between">
<span className="font-medium">WebCodecs</span>
<Badge variant={support ? (support.webCodecs ? "default" : "destructive") : "outline"}>{webCodecsLabel}</Badge>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="font-medium">AVC (H.264) </span>
<Badge variant={variant(support?.avc.overall ?? 'unknown')}>{label(support?.avc.overall ?? 'unknown')}</Badge>
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground"></span>
<Badge variant={variant(support?.avc.hardware ?? 'unknown')}>{label(support?.avc.hardware ?? 'unknown')}</Badge>
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground"></span>
<Badge variant={variant(support?.avc.software ?? 'unknown')}>{label(support?.avc.software ?? 'unknown')}</Badge>
</div>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="font-medium">HEVC (H.265) </span>
<Badge variant={variant(support?.hevc.overall ?? 'unknown')}>{label(support?.hevc.overall ?? 'unknown')}</Badge>
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground"></span>
<Badge variant={variant(support?.hevc.hardware ?? 'unknown')}>{label(support?.hevc.hardware ?? 'unknown')}</Badge>
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground"></span>
<Badge variant={variant(support?.hevc.software ?? 'unknown')}>{label(support?.hevc.software ?? 'unknown')}</Badge>
</div>
</div>
</div>
<div className="flex gap-2 pt-2">
<Button aria-label="重新检测" onClick={runDetect} disabled={loading}>{loading ? "检测中" : "重新检测"}</Button>
<Button variant="outline" aria-label="复制详情" onClick={onCopy} disabled={!support}></Button>
</div>
</CardContent>
</Card>
);
}

View File

@ -0,0 +1,64 @@
import * as React from "react"
import * as AccordionPrimitive from "@radix-ui/react-accordion"
import { ChevronDownIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Accordion({
...props
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
}
function AccordionItem({
className,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
return (
<AccordionPrimitive.Item
data-slot="accordion-item"
className={cn("border-b last:border-b-0", className)}
{...props}
/>
)
}
function AccordionTrigger({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
return (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
data-slot="accordion-trigger"
className={cn(
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
className
)}
{...props}
>
{children}
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
)
}
function AccordionContent({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
return (
<AccordionPrimitive.Content
data-slot="accordion-content"
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
{...props}
>
<div className={cn("pt-0 pb-4", className)}>{children}</div>
</AccordionPrimitive.Content>
)
}
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }

View File

@ -0,0 +1,66 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
{
variants: {
variant: {
default: "bg-card text-card-foreground",
destructive:
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Alert({
className,
variant,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
return (
<div
data-slot="alert"
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
)
}
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-title"
className={cn(
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
className
)}
{...props}
/>
)
}
function AlertDescription({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-description"
className={cn(
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
className
)}
{...props}
/>
)
}
export { Alert, AlertTitle, AlertDescription }

View File

@ -0,0 +1,46 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant,
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span"
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
}
export { Badge, badgeVariants }

View File

@ -0,0 +1,60 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View File

@ -0,0 +1,92 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

View File

@ -0,0 +1,28 @@
"use client"
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className
)}
{...props}
/>
)
}
export { Separator }

151
src/index.css Normal file
View File

@ -0,0 +1,151 @@
@import "tailwindcss";
@custom-variant dark (&:is(.dark *));
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
/* 移除 Vite 模板的全局样式,改由 Tailwind 控制布局与按钮外观 */
@theme inline {
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
/* 精简动画:仅保留折叠面板所需动画,替代 tw-animate-css */
@layer utilities {
@keyframes accordion-down {
from { height: 0 }
to { height: var(--radix-accordion-content-height) }
}
@keyframes accordion-up {
from { height: var(--radix-accordion-content-height) }
to { height: 0 }
}
.animate-accordion-down {
animation: accordion-down 0.2s ease-out;
}
.animate-accordion-up {
animation: accordion-up 0.2s ease-out;
}
}

6
src/lib/utils.ts Normal file
View File

@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

10
src/main.tsx Normal file
View File

@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

159
src/utils/codecs/detect.ts Normal file
View File

@ -0,0 +1,159 @@
import type { CodecDetail, CodecSupport, CodecStatus, CheckRecord, HardwarePref } from './types'
function nowTs() {
return Date.now()
}
function toOverall(hardware: CodecStatus, software: CodecStatus): CodecStatus {
if (hardware === 'supported' || software === 'supported') return 'supported'
if (hardware === 'unknown' && software === 'unknown') return 'unknown'
return 'unsupported'
}
const AVC_VARIANTS = ['avc1.42E01E', 'avc1.640028']
const HEVC_VARIANTS = ['hvc1', 'hev1', 'hvc1.1.6.L93.B0', 'hev1.1.6.L93.B0']
async function sleep(ms: number) {
return new Promise((r) => setTimeout(r, ms))
}
async function tryConfig(
codec: string,
hardwareAcceleration: HardwarePref,
checks: CheckRecord[],
): Promise<boolean> {
// Step 1: isConfigSupported
try {
const support = await VideoDecoder.isConfigSupported({
codec,
hardwareAcceleration,
optimizeForLatency: false,
})
checks.push({
codec,
hardwareAcceleration,
phase: 'isConfigSupported',
ok: !!support?.supported,
result: support ? { supported: support.supported } : undefined,
})
if (!support?.supported) return false
} catch (e) {
checks.push({
codec,
hardwareAcceleration,
phase: 'isConfigSupported',
ok: false,
error: e instanceof Error ? e.message : String(e),
})
return false
}
// Step 2: configure
let errorMsg: string | undefined
const decoder = new window.VideoDecoder({
output: () => {},
error: (e) => {
errorMsg = e?.message ?? String(e)
},
})
try {
decoder.configure({ codec, hardwareAcceleration, optimizeForLatency: false })
// Give the decoder a brief window to surface async errors (if any)
await sleep(100)
const ok = !errorMsg
checks.push({
codec,
hardwareAcceleration,
phase: 'configure',
ok,
error: errorMsg,
result: ok ? { configured: true } : undefined,
})
return ok
} catch (e) {
checks.push({
codec,
hardwareAcceleration,
phase: 'configure',
ok: false,
error: e instanceof Error ? e.message : String(e),
})
return false
} finally {
try {
decoder.close()
} catch {
// Ignore close errors
}
}
}
async function checkWithPref(
variants: string[],
hardwareAcceleration: HardwarePref,
checks: CheckRecord[],
): Promise<CodecStatus> {
for (const codec of variants) {
const ok = await tryConfig(codec, hardwareAcceleration, checks)
if (ok) return 'supported'
}
return 'unsupported'
}
async function checkCodecDetail(
variants: string[],
checks: CheckRecord[],
): Promise<CodecDetail> {
// Prefer paths are commonly supported across browsers; use them to infer HW/SW
const hardware = await checkWithPref(variants, 'prefer-hardware', checks)
const software = await checkWithPref(variants, 'prefer-software', checks)
const overall = toOverall(hardware, software)
return { hardware, software, overall }
}
export async function checkAVCDetail(): Promise<CodecDetail> {
const checks: CheckRecord[] = []
return checkCodecDetail(AVC_VARIANTS, checks)
}
export async function checkHEVCDetail(): Promise<CodecDetail> {
const checks: CheckRecord[] = []
return checkCodecDetail(HEVC_VARIANTS, checks)
}
export async function checkAVC(): Promise<CodecStatus> {
const d = await checkAVCDetail()
return d.overall
}
export async function checkHEVC(): Promise<CodecStatus> {
const d = await checkHEVCDetail()
return d.overall
}
export async function detectAll(): Promise<CodecSupport> {
const checks: CheckRecord[] = []
const env = {
userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : 'unknown',
isSecureContext: typeof window !== 'undefined' ? window.isSecureContext : false,
hasVideoDecoder: typeof window !== 'undefined' && 'VideoDecoder' in window,
}
if (!env.isSecureContext || !env.hasVideoDecoder) {
return {
webCodecs: false,
avc: { hardware: 'unknown', software: 'unknown', overall: 'unknown' },
hevc: { hardware: 'unknown', software: 'unknown', overall: 'unknown' },
details: { env, checks, errors: [], timestamp: nowTs() },
}
}
const avc = await checkCodecDetail(AVC_VARIANTS, checks)
const hevc = await checkCodecDetail(HEVC_VARIANTS, checks)
return {
webCodecs: true,
avc,
hevc,
details: { env, checks, timestamp: nowTs() },
}
}

View File

@ -0,0 +1,2 @@
export * from './types'
export * from './detect'

37
src/utils/codecs/types.ts Normal file
View File

@ -0,0 +1,37 @@
export type CodecStatus = 'supported' | 'unsupported' | 'unknown'
export interface CodecDetail {
hardware: CodecStatus
software: CodecStatus
overall: CodecStatus
}
export type HardwarePref =
| 'prefer-hardware'
| 'prefer-software'
| 'no-preference'
export interface CheckRecord {
codec: string
hardwareAcceleration?: HardwarePref
phase: 'isConfigSupported' | 'configure'
ok: boolean
result?: unknown
error?: string
}
export interface CodecSupport {
webCodecs: boolean
avc: CodecDetail
hevc: CodecDetail
details: {
env: {
userAgent: string
isSecureContext: boolean
hasVideoDecoder: boolean
}
checks: CheckRecord[]
errors?: string[]
timestamp: number
}
}

109
trae/design.md Normal file
View File

@ -0,0 +1,109 @@
# UI 指导文档WebCodecs AVC/HEVC 判定单页
本页旨在用 React + TailwindCSS + shadcn/ui + TypeScript + Vite 实现“当前页面是否支持 WebCodecs 的 AVC 与 HEVC”的判定与展示。仅做能力判定与结果呈现不进行视频解码、上传、登录等额外功能。
## 1. 目标与范围
- 目标:清晰、可靠地展示浏览器对 WebCodecs、AVC(H.264) 与 HEVC(H.265) 的支持状态。
- 范围:
- 首屏自动判定,并支持手动“重新检测”。
- 展示支持、非支持、未知三种状态,并提供详细信息(环境、判定过程、错误)。
- 仅单页应用,无路由与多页结构。
- 非目标:
- 不做实际视频解码/播放。
- 不做账号、权限、国际化切换等。
## 2. 信息架构与布局
- 顶部:标题与简述
- 标题WebCodecs 编码能力判定
- 说明:展示当前环境对 WebCodecs、AVC 与 HEVC 的支持情况
- 核心卡片DetectorCard
- 总览状态行:
- WebCodecs可用/不可用
- AVC(H.264):支持/不支持/未知
- HEVC(H.265):支持/不支持/未知(重点关注)
- 操作区:
- 按钮重新检测Button
- 按钮复制检测详情Button可选
- 详情折叠区(可展开):
- 环境信息UA、`isSecureContext`、平台信息
- 判定细节:各 `VideoDecoder.isConfigSupported` 的输入与返回
- 错误信息:异常堆栈、失败原因
- 底部:
- 兼容性声明与提示链接(例如参考文档)
## 3. 组件清单与样式shadcn/ui + Tailwind
- Card`<Card> <CardHeader> <CardTitle> <CardContent>` 用于包裹判定结果
- Badge用于标识状态
- 成功(支持):绿色 `bg-emerald-500` / shadcn `variant="default"` + `text-white`
- 失败(不支持):红色 `bg-red-500` / `variant="destructive"`
- 未知:琥珀色或灰色 `bg-amber-500`/`bg-gray-500`
- Button主要重新检测、次要复制详情
- Separator分隔信息块
- Collapsible / Accordion用于展开判定详情
- Alert可选在 WebCodecs 不可用或非安全上下文时提示
Tailwind 约定:
- 容器宽度:`max-w-2xl mx-auto px-4`;移动优先布局。
- 字体与层级:标题 `text-xl font-semibold`,正文 `text-sm text-muted-foreground`
- 状态色统一:支持=绿色、失败=红色、未知=琥珀/灰。
## 4. 状态与数据流
- 数据源:`utils/codecs` 封装的检测函数Promise
- 类型(页面侧以只读消费):
- `CodecStatus = 'supported' | 'unsupported' | 'unknown'`
- `CodecSupport`
- `webCodecs: boolean`
- `avc: CodecStatus`
- `hevc: CodecStatus`
- `details: { env, checks, errors, timestamp }`
- 生命周期:
- 初次渲染显示加载状态Skeleton/Spinner完成后渲染结果。
- 重新检测:刷新整个检测流程并更新时间戳。
- 错误:捕获并在详情区展示,页面用 Alert 简述。
## 5. 交互流程(主要场景)
1) 首屏加载:
- 调用 `detectAll()` -> 返回 `CodecSupport`
- 显示三行状态WebCodecs/AVC/HEVC与详情入口
2) 用户点击“重新检测”:
- 再次调用 `detectAll()`,展示加载与最新结果
3) 用户点击“复制检测详情”(可选):
- 将 `details` 序列化为 JSON 并复制至剪贴板
## 6. 响应式与可访问性
- 响应式:
- 移动端:单列卡片;按钮占满或并排但保持可点击区域
- 桌面端:保持居中与合理留白
- 可访问性:
- 所有交互元素有可见焦点态Tailwind focus 样式)
- 状态色同时提供文本标签(如“支持/不支持/未知”),避免仅靠颜色传达
- 按钮加上 `aria-label`
## 7. 文案与视觉规则
- 标题:`WebCodecs 编码能力判定`
- 说明:简述仅判定能力,不做解码测试
- 状态行文案:
- WebCodecs`可用`/`不可用`
- AVC(H.264)`支持`/`不支持`/`未知`
- HEVC(H.265)`支持`/`不支持`/`未知`
- 详情区:
- 环境信息UA、安全上下文、平台
- 判定过程:每次 `isConfigSupported` 的输入与输出
- 错误:异常消息与堆栈(裁剪)
## 8. 错误与边界情况提示
- 非安全上下文(`!isSecureContext`):提示必须在 HTTPS 下使用 WebCodecs
- 浏览器不支持 WebCodecs如部分 Firefox
- 顶部 Alert 提示不支持 WebCodecs
- AVC/HEVC 状态标为 `未知`
- HEVC 平台依赖性强:不同系统/浏览器的结果可能不同;详情区给出判定依据
## 9. 组件映射到目录结构
- 页面:`src/App.tsx`(单页)
- 组件:`src/components/DetectorCard.tsx`(包含状态、操作与详情)
- 工具:`src/utils/codecs/*`(判定逻辑与类型)
## 10. 未来扩展(暂不实现)
- 导出检测报告 JSON
- 增加更多编码VP9/AV1判定
- 国际化与主题切换

114
trae/prd.md Normal file
View File

@ -0,0 +1,114 @@
# PRDWebCodecs AVC/HEVC 判定页面
## 1. 背景与目标
- 背景:不同浏览器/平台对 WebCodecs 的支持不一致,尤其 HEVC(H.265) 支持高度依赖平台与浏览器实现。开发者需要一个简单页面来判定当前环境是否支持 WebCodecs、AVC(H.264) 与 HEVC(H.265)。
- 目标:构建一个单页应用,使用 WebCodecs 相关 API主要是 `VideoDecoder.isConfigSupported`)进行判定,给出清晰的结果与可追溯的详情。
## 2. 范围与非目标
- 范围:
- 判定 WebCodecs 可用性
- 判定 AVC(H.264) 解码支持
- 判定 HEVC(H.265) 解码支持
- 展示判定详情(环境、输入配置、返回信息、错误)
- 非目标:
- 不进行视频解码、编码或渲染
- 不做登录、权限、国际化、路由、多页
## 3. 用户场景与价值
- 前端/视频开发者打开页面即可得知当前环境是否能安全地依赖 WebCodecs 的 AVC/HEVC 解码能力,用于后续策略选择(如降级到 H.264、走 MSE 或 WebAssembly 等)。
## 4. 功能描述
- 首屏自动判定并展示三类状态WebCodecs、AVC、HEVC。
- 提供“重新检测”按钮,重新执行全部判定。
- 在详情中展示UA、安全上下文`isSecureContext`)、每次 `isConfigSupported` 的输入/输出、错误信息。
## 5. 技术方案与实现策略
- 判定基于 WebCodecs
- WebCodecs 可用判定:`typeof window.VideoDecoder !== 'undefined'`
- 统一使用 `VideoDecoder.isConfigSupported(config)` 来探测是否支持某种编码配置。
- AVC 探测建议:
- 常见且广泛支持的配置字符串(示例):
- `avc1.42E01E`Baseline
- `avc1.640028`High Profile Level 4.0
- 逻辑:若任意代表性配置返回 `supported: true`,则判定为“支持”。若全部返回 `supported: false` 或抛错,则“未支持/未知”。
- HEVC 探测建议(平台相关):
- 尝试 `hvc1``hev1` 两种品牌。
- 代表性字符串(示例):
- `hvc1.1.6.L93.B0`
- `hev1.1.6.L93.B0`
- 不同实现对 `description`codec private data与 profile-level 的要求可能不同。策略:从简到繁,先试纯 `codec`,再试带 profile-level如上面的示例
- 安全上下文:
- WebCodecs 在非安全上下文可能不可用;`!isSecureContext` 时直接给出提示,并将 AVC/HEVC 标记为 `unknown`
- 错误处理:
- 统一捕获异常与拒绝,记录在详情中,页面通过 Alert 简述。
### 判定调用示例(伪代码,仅文档说明)
```ts
await VideoDecoder.isConfigSupported({
codec: 'hvc1.1.6.L93.B0',
hardwareAcceleration: 'prefer-hardware',
});
```
## 6. 数据结构与接口(由 `utils/codecs` 对外暴露)
- 类型:
```ts
export type CodecStatus = 'supported' | 'unsupported' | 'unknown';
export interface CodecSupport {
webCodecs: boolean;
avc: CodecStatus;
hevc: CodecStatus;
details: {
env: {
userAgent: string;
isSecureContext: boolean;
hasVideoDecoder: boolean;
};
checks: Array<{
codec: string; // 传入的 codec 字符串
result?: any; // isConfigSupported 的返回(裁剪)
ok: boolean; // 是否成功/支持
error?: string;
}>;
errors?: string[];
timestamp: number;
};
}
```
- 接口:
```ts
export async function detectAll(): Promise<CodecSupport>;
export async function checkAVC(): Promise<CodecStatus>;
export async function checkHEVC(): Promise<CodecStatus>;
```
## 7. 验收标准
- 在支持 WebCodecs 且支持 HEVC 的浏览器(如部分 Safari/iOS/macOS显示
- WebCodecs可用
- AVC支持大概率
- HEVC支持
- 在支持 WebCodecs 但不支持 HEVC 的浏览器(如多数默认配置的 Chrome/Windows
- WebCodecs可用
- AVC支持
- HEVC不支持
- 在不支持 WebCodecs 的浏览器(如部分 Firefox
- WebCodecs不可用Alert 提示)
- AVC/HEVC未知
- 详情区包含环境、检查输入/输出、错误信息与时间戳。
## 8. 兼容性与风险
- HEVC 支持强平台依赖,可能需要操作系统编解码器或浏览器实验开关;结果可能随版本变化。
- 字符串语法profile-level在不同实现中解析差异需在详情中透明记录。
- 非安全上下文导致 WebCodecs 不可用。
## 9. 依赖与约束
- 依赖现代浏览器、HTTPS 环境
- 技术栈React + Tailwind + shadcn/ui + TypeScript + Vite
## 10. 发布与度量
- 发布:静态资源即可部署
- 度量:
- 首屏交互完成时间(粗略)
- 判定耗时(检测 Promise 完成时间)
- 用户使用“重新检测”与“复制详情”的频次(可选)

3
trae/prompts/init.md Normal file
View File

@ -0,0 +1,3 @@
目标生成一个webcodecs avc和hevc判定页面通过webcodecs相关api判定当前web页面是否支持hevc。请专注于该功能不要做其他功能比如去视频解码或者登陆之类的。你可以使用react+tailwindcss+shdcn+typescript+vite。做一个单页应用即可。Webcodecs相关判定尽量封装到一个目录中(utils/codecs),在页面中调用即可。
任务执行先生成UI指导文档到./trae/design.md列出功能设计./trae/prd.md, 然后进行计划./trae/tasks/README.md最后拆解为小功能点./trae/tasks/task01, ./trae/tasks/task02...。在我下指令前,不要进一步实施。

37
trae/tasks/README.md Normal file
View File

@ -0,0 +1,37 @@
# 任务计划Roadmap
本项目分为五个阶段,当前仅完成文档交付,等待指令后再实施。
## 阶段 0文档
- 产出:`./trae/design.md``./trae/prd.md``./trae/tasks/*`
- 状态:已完成
## 阶段 1项目脚手架
- 使用 Vite + React + TypeScript 初始化项目
- 集成 TailwindCSS 与 shadcn/ui 组件库
- 基础目录搭建:`src/components``src/utils/codecs`
## 阶段 2判定模块utils/codecs
- 封装 WebCodecs 判定逻辑:`detectAll``checkAVC``checkHEVC`
- 设计类型与返回结构,记录判定详情(环境、检查、错误、时间戳)
## 阶段 3UI 页面实现
- 单页 App渲染判定结果卡片、操作按钮、详情折叠
- 统一状态色与文案,提供复制详情能力(可选)
## 阶段 4验证与交付
- 基本跨浏览器验证Chrome/Edge/Safari/Firefox
- 打包与静态部署(如 `dist/`
---
## 环境准备
- Node.js >= 18
- 包管理器npm 或 pnpm
- 浏览器:最新版 Chrome/Edge/Safari/Firefox
## 执行顺序与里程碑
1. 初始化项目与 UI 库Task01
2. 封装判定模块Task02
3. 实现单页 UI后续 Task
4. 验证与交付(后续 Task

32
trae/tasks/task01.md Normal file
View File

@ -0,0 +1,32 @@
# Task01项目初始化与 UI 库集成
## 目标
- 使用 Vite + React + TypeScript 创建项目骨架
- 集成 TailwindCSS 与 shadcn/ui准备基础组件Card/Badge/Button/Alert/Accordion/Separator
## 步骤(计划)
1) 初始化 Vite 项目(在 `g:\work\projects\ai-stuff\test_webcodecs` 目录内):
- `npm create vite@latest . -- --template react-ts`
- `npm install`
2) 安装并配置 TailwindCSS
- `npm install -D tailwindcss postcss autoprefixer`
- `npx tailwindcss init -p`
- Tailwind 配置:`content` 指向 `./index.html``./src/**/*.{ts,tsx}`
- 在 `src/index.css` 添加:`@tailwind base; @tailwind components; @tailwind utilities;`
3) 初始化 shadcn/ui
- `npx shadcn-ui@latest init`
- 选择 Vite + React + TypeScript 模板,路径默认 `./src/components/ui`
- 添加组件:
- `npx shadcn-ui@latest add button card badge alert accordion separator`
4) 建立基础目录:
- `src/components/DetectorCard.tsx`(空组件占位)
- `src/utils/codecs/`(空目录占位)
## 验收标准
- `npm run dev` 能启动并渲染示例页面
- Tailwind 与 shadcn/ui 样式正常(按钮与卡片能显示)
- 存在 `src/utils/codecs` 目录为后续实现准备
## 产出
- Vite + React + TS 基础工程
- Tailwind 与 shadcn/ui 已集成,组件可用

103
trae/tasks/task02.md Normal file
View File

@ -0,0 +1,103 @@
# Task02封装 WebCodecs 判定模块utils/codecs
## 目标
- 在 `src/utils/codecs` 封装 WebCodecs 判定逻辑
- 提供统一接口:`detectAll``checkAVC``checkHEVC`
- 返回结构包含环境、检查细节、错误与时间戳,便于 UI 展示
- 增强输出:分别判定 H.264(AVC) 与 H.265(HEVC) 的“硬解/软解”支持情况
- 可靠性校验:在 `isConfigSupported` 为真后,实际执行 `VideoDecoder.configure(config)`,若抛错或触发 `error` 回调,则视为“不支持”
## 目录结构(计划)
- `src/utils/codecs/types.ts`(类型定义)
- `src/utils/codecs/detect.ts`(具体判定逻辑)
- `src/utils/codecs/index.ts`(导出聚合)
## 类型与接口(拟定)
```ts
export type CodecStatus = 'supported' | 'unsupported' | 'unknown';
export interface CodecDetail {
hardware: CodecStatus; // 硬件解码支持
software: CodecStatus; // 软件解码支持
overall: CodecStatus; // hardware 或 software 任一为 supported 则为 supported
}
export interface CodecSupport {
webCodecs: boolean;
avc: CodecDetail;
hevc: CodecDetail;
details: {
env: {
userAgent: string;
isSecureContext: boolean;
hasVideoDecoder: boolean;
};
checks: Array<{
codec: string;
hardwareAcceleration?:
| 'require-hardware'
| 'require-software'
| 'prefer-hardware'
| 'prefer-software'
| 'no-preference';
phase: 'isConfigSupported' | 'configure';
ok: boolean;
result?: unknown; // isConfigSupported 返回或 configure 成功标记
error?: string; // 异常或 VideoDecoder error 回调信息
}>;
errors?: string[];
timestamp: number;
};
}
export async function detectAll(): Promise<CodecSupport>;
export async function checkAVCDetail(): Promise<CodecDetail>;
export async function checkHEVCDetail(): Promise<CodecDetail>;
// 可选:保留聚合态接口(返回 overall
export async function checkAVC(): Promise<CodecStatus>;
export async function checkHEVC(): Promise<CodecStatus>;
```
## 判定逻辑(思路)
1) WebCodecs 可用性:
- `const hasVideoDecoder = typeof window.VideoDecoder !== 'undefined'`
- `const secure = isSecureContext`
- 若 `!secure || !hasVideoDecoder`:返回 `webCodecs=false``avc='unknown'``hevc='unknown'`
2) AVC 检查(代表性配置 + 硬解/软解):
- 代表性 `codec``avc1.42E01E`Baseline`avc1.640028`High L4.0
- 对每个 `codec` 分别尝试:
- `hardwareAcceleration: 'require-hardware'`(硬解)
- `hardwareAcceleration: 'require-software'`(软解)
- 先调用 `await VideoDecoder.isConfigSupported(config)`;若 `supported: true`,继续创建 `new VideoDecoder({ output, error })` 并执行 `decoder.configure(configWithDims)`
- 为避免不完整配置导致误判,`configWithDims` 需包含最小维度:`codedWidth: 16, codedHeight: 16``optimizeForLatency: false`
- 若 `configure` 抛错或随后触发 `error` 回调(建议等待 ~300ms则该路径判定为 `unsupported`
- 成功则记录为 `supported`
- 若某实现忽略 `hardwareAcceleration`(常见):
- 回退策略:尝试 `prefer-hardware`/`prefer-software` 并记录结果为“弱证据”UI 仍以严格 `require-*` 结果为准;弱证据仅进入 `details`
3) HEVC 检查(代表性配置 + 硬解/软解):
- 代表性 `codec``hvc1``hev1`,以及带 profile-level 的示例:`hvc1.1.6.L93.B0``hev1.1.6.L93.B0`
- 检查流程同 AVC分别对硬解/软解进行 `isConfigSupported``configure` 双重校验,维度与等待策略一致
- 注意:不同平台对 `description` 要求不一;本版默认不提供 `description`,如遇特定浏览器需补充,可在 `details` 记录并作为特例处理
4) 记录详情:
- `env`UA、`isSecureContext``hasVideoDecoder`
- `checks`:每次调用的 `codec``hardwareAcceleration`、阶段(`isConfigSupported`/`configure`)、结果/错误
- `timestamp`:毫秒时间戳
## 错误处理与未知态
- `isConfigSupported` 可能抛错或返回不明确信息,统一捕获并记录
- 条件不足(如非安全上下文、缺少 API时标记为 `unknown`
- 在 `isConfigSupported` 为真后仍需 `configure`:若抛错或 `error` 回调被触发(在约定时间窗内),则视为“不支持”
- 统一在完成检查后 `decoder.close()`,避免资源泄漏
## 测试计划(开发机验证)
- ChromeWindows/macOS
- WebCodecs 可用AVC 软件解码支持硬解由平台驱动与浏览器策略决定HEVC 通常不支持(硬/软均可能失败)
- SafarimacOS/iOS 16+
- WebCodecs 与 HEVC 可能支持;对 HEVC 硬解/软解的结果依平台版本而异AVC 支持
- Firefox
- WebCodecs 可能不可用AVC/HEVC 显示未知
## 验收标准
- `detectAll()` 返回结构符合最新类型定义(含 `CodecDetail` 的硬解/软解与 `overall`
- `details.checks` 对 AVC/HEVC 均包含:硬解(`require-hardware`)与软解(`require-software`)的 `isConfigSupported``configure` 两阶段记录
- 在上述浏览器场景下,页面能分别展示 H.264/H.265 的“硬解/软解/总体”状态Safari 的 HEVC 正确反映平台支持Chrome/Windows 的 HEVC 显示不支持或未知

32
tsconfig.app.json Normal file
View File

@ -0,0 +1,32 @@
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

13
tsconfig.json Normal file
View File

@ -0,0 +1,13 @@
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

26
tsconfig.node.json Normal file
View File

@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

37
vite.config.ts Normal file
View File

@ -0,0 +1,37 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import { fileURLToPath, URL } from 'node:url'
// https://vite.dev/config/
const config = defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
// Reduce bundle size by aliasing React to Preact
'react': 'preact/compat',
'react-dom': 'preact/compat',
'react-dom/test-utils': 'preact/test-utils',
'react/jsx-runtime': 'preact/jsx-runtime',
},
},
build: {
sourcemap: false,
target: 'es2018',
rollupOptions: {
output: {
// Split vendor libraries to avoid inflating the main chunk
manualChunks(id) {
if (id.includes('node_modules')) {
if (id.includes('preact') || id.includes('react')) return 'vendor'
if (id.includes('@radix-ui')) return 'radix'
}
return undefined
},
},
},
},
})
export { config as default}